Compare commits

..
8 Commits
Author SHA1 Message Date
PhilandClaude Opus 5.5 2474628646 Merge branch 'fix/v2.6.3-link-cards' for v2.6.3 release
Build Container / build (push) Successful in 8s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 08:12:25 -07:00
PhilandClaude Opus 5.5 0fe341161e feat: Crosspost cards show the note's own link (v2.6.3)
When a note links somewhere (an article, say), the first link gets the
preview card instead of the note (ADR-070). Bluesky cards are built from
the page's OG/Twitter/HTML title, description and image (thumb shrunk
under 1 MB); Threads previews the first link in the text. Markdown links
no longer lose their URL on Bluesky (link text becomes a facet) or Threads
("text (url)"); Threads keeps to Meta's 5-link limit. Page fetches are
public-address only, checked at every redirect, size-capped, and never
fail the post.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 08:12:24 -07:00
PhilandClaude Opus 5.5 a62077ab30 Merge branch 'fix/v2.6.2-threads-link-preview' for v2.6.2 release
Build Container / build (push) Successful in 7s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 21:38:00 -06:00
PhilandClaude Opus 5.5 fade75fd2d fix: Let Threads build the link preview itself (v2.6.2)
An explicit link_attachment for a URL Meta hasn't fetched yet fails at
threads_publish with "Invalid Link Attachment" (subcode 4279047), which
is every new note; it only went out on the retry. Tested live with fresh
URLs: with link_attachment it fails, without it it publishes first time
and Threads still sets link_attachment_url from the first link in the
text. Reposts likewise.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 21:38:00 -06:00
PhilandClaude Opus 5.5 0dd59fbc18 Merge branch 'fix/v2.6.1-threads-publish-retry' for v2.6.1 release
Build Container / build (push) Successful in 6s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 21:18:11 -06:00
PhilandClaude Opus 5.5 11e09a0d02 fix: Retry Threads publish errors, show full error detail (v2.6.1)
Meta's threads_publish returned a one-off HTTP 400 "Fatal" for a plain
text post; the same post published fine on retry. Publish-step errors
are now retryable unless they are auth/permission errors (codes 10, 190,
200); the retry's existing-post check prevents doubles. Errors carry the
Graph code, subcode, user message and fbtrace id. A short pause before
the first container status poll.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 21:18:11 -06:00
PhilandClaude Opus 5.5 565adaeecf Merge branch 'feature/v2.6.0-threads' for v2.6.0 release
Build Container / build (push) Successful in 7s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 20:54:15 -06:00
PhilandClaude Opus 5.5 53d10ed271 feat: Crosspost notes to Threads (v2.6.0)
Third crossposting target on the ADR-065 loop (ADR-069). Text posts get a
link preview, 1 image posts as IMAGE and 2-4 as a CAROUSEL (Meta fetches
them from /media/), with alt text and the first tag as topic_tag. Posts are
shortened to 500 characters, counting non-ASCII as UTF-8 bytes. Edits don't
follow (the API has no edit); unpublish and delete remove the post. Retried
creates check for an existing post first.

The 60-day token is refreshed daily from the worker loop and kept in
DATA_PATH/threads_token.json under a file lock; a new configured token
replaces it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 20:46:56 -06:00
10 changed files with 1257 additions and 25 deletions

No files matched your search

+8
View File
@@ -63,6 +63,14 @@ GOTOSOCIAL_NAME=GoToSocial
# public, unlisted, private (default: public)
GOTOSOCIAL_VISIBILITY=public
# Threads account (v2.6.0). A long-lived user token with threads_basic,
# threads_content_publish and threads_delete; StarPunk refreshes it daily and
# keeps the current one in DATA_PATH/threads_token.json.
# How to get one: docs/design/v2.6.0/2026-10-31-threads-crossposting.md
THREADS_ACCESS_TOKEN=
# Your Threads username (for the Micropub syndicate-to uid)
THREADS_USERNAME=
# =============================================================================
# DATA STORAGE
# =============================================================================
+32
View File
@@ -7,6 +7,38 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [2.6.3] - 2026-11-01
### Changed
- **A note's own link gets the preview card** (ADR-070). When a note links somewhere (say, an article), the crosspost's card shows that page instead of the note. Bluesky cards are built from the page's title, description and image; Threads previews it from the text. Notes without links keep their own card
### Fixed
- Markdown links (`[text](url)`) lost their URL on Bluesky and Threads. On Bluesky the link text is now clickable; on Threads it's written "text (url)"
- Notes with many links failed on Threads (Meta allows 5 per post); extra links now keep just their text
## [2.6.2] - 2026-11-01
### Fixed
- New notes failed their first Threads crosspost with "Invalid Link Attachment" (Meta rejects an explicit link preview for a page it hasn't fetched yet) and only went out on the retry a minute later. StarPunk no longer sends the explicit link preview; Threads still shows one, built from the note's link in the text
## [2.6.1] - 2026-11-01
### Fixed
- Threads crossposts gave up after Meta's publish step returned a one-off `HTTP 400 Fatal`; publish errors are now retried (a retry checks for an existing post first, so nothing is posted twice). Only a bad token or missing permission stops retries
- Threads errors now include Meta's error code, subcode, user message and trace id, so the editor shows why a post failed
- Wait a moment before the first readiness check on a Threads post, since Meta can report it ready too early
## [2.6.0] - 2026-11-01
### Added
- **Crossposting to Threads** (ADR-069): set `THREADS_ACCESS_TOKEN` (and optionally `THREADS_USERNAME`) to add a Threads target. Text posts get a link preview; 1 image posts as an image, 2–4 as a carousel, with alt text; the note's first tag becomes the post's topic. Shortened to 500 characters. Edits don't follow (the API can't edit); unpublish and delete remove the post. Likes aren't crossposted to Threads; reposts post "🔁 title url" (with the comment, if any)
- The Threads token (60-day lifetime) is refreshed automatically once a day and kept in `data/threads_token.json`, so it survives restarts; setting a new token in the config replaces it. Setup steps: `docs/design/v2.6.0/`
## [2.5.0] - 2026-11-01
### Added
@@ -0,0 +1,57 @@
# ADR-069: Crossposting to Threads
## Status
Accepted (v2.6.0, 2026-10-31)
## Context
ADR-065 and ADR-066 crosspost notes to GoToSocial and Bluesky. Threads
(Meta) has a publishing API, so it can be a third target on the same loop.
## Decision
1. **Third client, same loop.** `ThreadsClient` is target id `threads`
behind the `syndications` table and reconcile loop from ADR-065.
2. **Auth.** A long-lived Threads user token (`THREADS_ACCESS_TOKEN`) with
`threads_basic`, `threads_content_publish` and `threads_delete`. These
tokens expire after 60 days, so StarPunk refreshes the token about once a
day (`th_refresh_token`) from the worker loop, even when nothing is being
posted. The current token is kept in `DATA_PATH/threads_token.json`
(mode 0600) with a hash of the configured token. A different configured
token replaces the saved one. A file lock stops gunicorn workers from
refreshing at the same time. The file avoids a migration for one value.
3. **Posting.** Create a container, poll its status until `FINISHED`, then
`threads_publish`. Text-only notes are `TEXT` posts. Threads previews
the first link in the text (the permalink) by itself. An explicit
`link_attachment` is not sent, because Meta rejects one for a page it
hasn't fetched yet ("Invalid Link Attachment", subcode 4279047), which
is always the case for a new note (v2.6.2). One image is an `IMAGE` post and 2–4 images are a
`CAROUSEL`. Meta fetches images from their public `/media/` URL. Only
JPEG and PNG up to 8 MB are allowed, so GIF and WebP images are left off.
Alt text goes in `alt_text`.
4. **Content.** Plain text (as for Bluesky), then the permalink, shortened
to 500 characters. Non-ASCII characters are counted as UTF-8 bytes,
because Threads counts emoji that way. Threads allows one tag per post,
so the note's first tag is sent as `topic_tag` and no hashtags are added
to the text.
5. **Edits don't follow.** The API has no way to edit a post. As with
Bluesky, the post stays as first sent, and unpublishing, unticking the
target or deleting the note removes it.
6. **Likes and reposts (ADR-068).** The API can't like or repost outside
content, so likes are not crossposted. Reposts are text posts with
"🔁 title" and the URL, plus the comment if there is one, and the
reposted page as the link preview.
7. **No double posts.** A retried create first looks for a recent post that
already contains the permalink.
## Consequences
- Meta limits accounts to 250 posts and 100 deletes per day. Rate-limit
errors (Graph codes 4, 17, 32, 613) are retried.
- If StarPunk is down for more than 60 days, the token expires and a new
one is needed.
- Getting the first token requires a Meta developer app with the Threads
use case. See the setup notes in `docs/design/v2.6.0/`.
- Notes with more than five links fail on Threads (a Meta limit). The
error is shown in the editor.
@@ -0,0 +1,44 @@
# ADR-070: Links and link cards in crossposts
## Status
Accepted (v2.6.3, 2026-11-01)
## Context
Every crosspost carries the note's permalink. Notes often link elsewhere
too, usually to the article being discussed. Before this change:
- Bluesky and Threads get plain text, and a Markdown link `[text](url)`
lost its URL, so readers there couldn't follow it.
- The Bluesky card always showed the note, and the Threads preview showed
whichever link came first.
- Threads rejects posts with more than 5 different links.
## Decision
1. **The card shows what the note links to.** If the note has its own link
(a Markdown link, `<url>` or a bare URL), the first one gets the
preview card. A note without links gets a card for itself, as before.
Images still take the place of a card on Bluesky.
2. **Bluesky.** The card is built by StarPunk: it fetches the page's Open
Graph, Twitter or plain HTML title, description and image, and uploads
the image (shrunk to under 1 MB) as the thumbnail. If the page can't
be fetched, the card has just the URL. Markdown link text becomes a
clickable link facet, so no characters are spent on the URL.
3. **Threads.** It has no clickable link text, so Markdown links are
written "text (url)". Threads previews the first link in the text, which
is now the linked page. To stay within Meta's 5-link limit, after 4
different links in the body a Markdown link keeps only its text.
4. **GoToSocial** already gets Markdown, so its links are unchanged.
Receiving servers build their own cards.
5. **Fetching is careful.** Only http(s) URLs on public addresses are
fetched, and this is checked again at every redirect. At most 512 KB of
a page and 5 MB of an image are read. A failed fetch never fails the
post.
## Consequences
- One or two extra requests to the linked site when a note is crossposted
to Bluesky.
- Reposts (ADR-068) are unchanged: their card is the reposted page.
@@ -0,0 +1,62 @@
# v2.6.0: Crossposting to Threads
Implements ADR-069.
## What changed
- `starpunk/syndication.py`: `ThreadsClient` (target `threads`); media
entries now carry their public `url`; `process_due()` calls each client's
optional `maintain()` hook, which Threads uses to refresh its token.
- `starpunk/config.py`: `THREADS_ACCESS_TOKEN`, `THREADS_USERNAME`,
`THREADS_NAME`, `THREADS_MAX_CHARS` (500), `THREADS_MAX_MEDIA` (4).
- `tests/test_syndication_threads.py`: a fake Graph API covering text,
image and carousel posts; container polling; edits not following; deletes
(including posts already deleted by hand); a lost publish reply;
permanent and rate-limit errors; and token refresh, persistence and
replacement.
## Configuration
| Variable | Meaning |
|---|---|
| `THREADS_ACCESS_TOKEN` | Long-lived Threads user token. Enables the target. |
| `THREADS_USERNAME` | Optional. Used for the Micropub `syndicate-to` uid (`https://www.threads.com/@name`) and for fallback links. |
| `THREADS_NAME` | Label in the editor (default `Threads`) |
After the first daily refresh, the working token lives in
`DATA_PATH/threads_token.json`. The configured value only seeds it.
Changing `THREADS_ACCESS_TOKEN` switches to the new token.
## Getting a token (one time)
1. At <https://developers.facebook.com/apps>, create an app with the
**Access the Threads API** use case.
2. Under the use case's permissions, add `threads_basic`,
`threads_content_publish` and `threads_delete`.
3. Under **App roles → Roles**, add your Threads account as a Threads
tester. Accept the invite in Threads (Settings → Account → Website
permissions → Invites). The app can stay in development mode.
4. In the use case settings, add `https://<site>/` as a redirect URI. Then
open:
https://threads.net/oauth/authorize?client_id=APP_ID&redirect_uri=https://<site>/&scope=threads_basic,threads_content_publish,threads_delete&response_type=code
After you approve, the browser lands on `https://<site>/?code=...`. Copy
the code (drop a trailing `#_`).
5. Exchange the code for a short-lived token, then exchange that for a
long-lived one:
curl -s -X POST https://graph.threads.net/oauth/access_token \
-F client_id=APP_ID -F client_secret=APP_SECRET \
-F grant_type=authorization_code -F redirect_uri=https://<site>/ -F code=CODE
curl -s "https://graph.threads.net/access_token?grant_type=th_exchange_token&client_secret=APP_SECRET&access_token=SHORT_TOKEN"
6. Set `THREADS_ACCESS_TOKEN` to the long-lived `access_token`.
The app secret is only needed for these steps. StarPunk doesn't use it.
## Not done
- Video, GIF and WebP images (Threads takes video by URL. StarPunk only
stores still images, and Threads rejects GIF and WebP).
- Edits (no API for them).
+2 -2
View File
@@ -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.5.0"
__version_info__ = (2, 1, 0)
__version__ = "2.6.3"
__version_info__ = (2, 6, 3)
+6
View File
@@ -137,6 +137,12 @@ def load_config(app, config_override=None):
app.config["BLUESKY_SERVICE"] = os.getenv("BLUESKY_SERVICE", "https://bsky.social")
app.config["BLUESKY_NAME"] = os.getenv("BLUESKY_NAME", "Bluesky")
app.config["BLUESKY_MAX_CHARS"] = int(os.getenv("BLUESKY_MAX_CHARS", "300"))
# Crossposting to Threads (v2.6.0, ADR-069): long-lived token, refreshed automatically
app.config["THREADS_ACCESS_TOKEN"] = os.getenv("THREADS_ACCESS_TOKEN", "")
app.config["THREADS_USERNAME"] = os.getenv("THREADS_USERNAME", "")
app.config["THREADS_NAME"] = os.getenv("THREADS_NAME", "Threads")
app.config["THREADS_MAX_CHARS"] = int(os.getenv("THREADS_MAX_CHARS", "500"))
app.config["THREADS_MAX_MEDIA"] = int(os.getenv("THREADS_MAX_MEDIA", "4"))
app.config["SYNDICATION_POLL_INTERVAL"] = int(os.getenv("SYNDICATION_POLL_INTERVAL", "10"))
# Apply overrides if provided
+508 -21
View File
@@ -1,10 +1,10 @@
"""
Crossposting (POSSE) for StarPunk (v2.1.0 ADR-065, v2.2.0 ADR-066)
Crossposting (POSSE) for StarPunk (v2.1.0 ADR-065, v2.2.0 ADR-066, v2.6.0 ADR-069, v2.6.3 ADR-070)
Published notes are copied to syndication targets, and later edits and
deletes follow them. Two target kinds exist: a GoToSocial (or any
Mastodon-API) account, and a Bluesky account. Bluesky posts can't be edited,
so there only deletes follow.
deletes follow them. Three target kinds exist: a GoToSocial (or any
Mastodon-API) account, a Bluesky account and a Threads account. Bluesky and
Threads posts can't be edited, so there only deletes follow.
Each (note, target) pair has a row in `syndications`. Changing a note marks
its rows pending; a background worker then reconciles the remote post with
@@ -17,9 +17,15 @@ the note:
Rows carry a version so an edit made while a send is in flight is not lost.
"""
import fcntl
import hashlib
import io
import json
import logging
import os
import re
import threading
import time
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
@@ -28,6 +34,9 @@ from typing import Dict, List, Optional
import httpx
from flask import current_app
# httpx logs request URLs at INFO, and Threads takes its token in the URL
logging.getLogger("httpx").setLevel(logging.WARNING)
from starpunk.database import get_db
MAX_ATTEMPTS = 8
@@ -268,12 +277,28 @@ class BlueskyClient:
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:
def _link_card(self, url: str) -> dict:
"""External embed for a page, with its title, description and image when we can get them"""
card = page_card(self.http, url)
external = {"uri": url, "title": card["title"][:300], "description": card["description"][:1000]}
if card["image"]:
try:
data, mime_type, _ = _fetch_public(self.http, card["image"], CARD_IMAGE_LIMIT,
truncate=False)
data, mime_type, _, _ = _fit_image(data, mime_type.split(";")[0] or "image/jpeg",
BLUESKY_BLOB_LIMIT)
external["thumb"] = self.upload_blob(data, mime_type)
except Exception as e: # a card without a picture is fine
current_app.logger.info(f"No link card image for {url}: {e}")
return {"$type": "app.bsky.embed.external", "external": external}
def _record(self, post: "Post", text: Optional[str] = None, embed: Optional[dict] = None,
anchors: List[tuple] = ()) -> dict:
if text is None:
text = compose_text(post.note, post.permalink, post.tags, post.max_chars,
body=plain_text(post.note.content))
body, anchors = plain_text_links(post.note.content, links="anchor")
text = compose_text(post.note, post.permalink, post.tags, post.max_chars, body=body)
record = {"$type": self.POST, "text": text, "createdAt": self._now()}
facets = bluesky_facets(text)
facets = bluesky_facets(text, anchors)
if facets:
record["facets"] = facets
if embed is not None:
@@ -281,6 +306,9 @@ class BlueskyClient:
elif post.media:
record["embed"] = {"$type": "app.bsky.embed.images",
"images": [self._image(m) for m in post.media]}
elif note_links(post.note.content):
# The note links somewhere: the card shows that page, not the note
record["embed"] = self._link_card(note_links(post.note.content)[0])
else:
record["embed"] = {"$type": "app.bsky.embed.external", "external": {
"uri": post.permalink,
@@ -312,7 +340,8 @@ class BlueskyClient:
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 ""
comment, anchors = (plain_text_links(post.note.content, links="anchor")
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", {
@@ -326,7 +355,8 @@ class BlueskyClient:
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}))
post, text=text, embed={"$type": "app.bsky.embed.record", "record": subject},
anchors=anchors))
return {"id": uri, "url": self._web_url(uri)}
if post.kind == "like":
return {"id": None, "url": None} # not a Bluesky post: nothing to like
@@ -380,11 +410,15 @@ class BlueskyClient:
json={"repo": repo, "collection": collection, "rkey": rkey})
def _fit_image(path: Path, mime_type: str, limit: int) -> tuple:
"""Image bytes no bigger than `limit`, re-encoded as JPEG if needed. Returns (data, mime, w, h)."""
def _fit_image(path, mime_type: str, limit: int) -> tuple:
"""
Image (a path, or bytes) no bigger than `limit`, re-encoded as JPEG if
needed. Returns (data, mime, w, h).
"""
from PIL import Image
data = Path(path).read_bytes()
data = path if isinstance(path, bytes) else Path(path).read_bytes()
name = "image" if isinstance(path, bytes) else Path(path).name
with Image.open(io.BytesIO(data)) as img:
width, height = img.size
if len(data) <= limit:
@@ -397,7 +431,355 @@ def _fit_image(path: Path, mime_type: str, limit: int) -> tuple:
copy.save(buf, format="JPEG", quality=quality, optimize=True)
if buf.tell() <= limit:
return buf.getvalue(), "image/jpeg", copy.size[0], copy.size[1]
raise SyndicationError(f"{Path(path).name}: image too large for Bluesky", permanent=True)
raise SyndicationError(f"{name}: image too large for Bluesky", permanent=True)
# --- Link cards ---------------------------------------------------------------
CARD_PAGE_LIMIT = 512 * 1024 # the <head> is near the start; read no more
CARD_IMAGE_LIMIT = 5 * 1024 * 1024
def _fetch_public(http: httpx.Client, url: str, limit: int, truncate: bool) -> tuple:
"""
GET a public web URL, checking every redirect hop (no requests into the
LAN). Reads at most `limit` bytes: stops there if `truncate`, else fails.
Returns (data, content_type, final_url).
"""
from urllib.parse import urljoin, urlparse
from starpunk.micropub import _public_address
site = current_app.config.get("SITE_URL", "")
for _ in range(5):
parsed = urlparse(url)
if parsed.scheme not in ("http", "https") or not parsed.hostname:
raise SyndicationError(f"not a web URL: {url}", permanent=True)
if not current_app.config.get("TESTING") and not _public_address(parsed.hostname):
raise SyndicationError(f"not a public address: {url}", permanent=True)
try:
with http.stream("GET", url, follow_redirects=False, timeout=10.0,
headers={"User-Agent": f"StarPunk (+{site})"}) as response:
if response.is_redirect and "location" in response.headers:
url = urljoin(url, response.headers["location"])
continue
if response.status_code >= 400:
raise SyndicationError(f"{url}: HTTP {response.status_code}")
data = bytearray()
for chunk in response.iter_bytes():
data += chunk
if len(data) > limit:
if truncate:
break
raise SyndicationError(f"{url}: too large")
return bytes(data), response.headers.get("content-type", ""), url
except httpx.HTTPError as e:
raise SyndicationError(f"{url}: {type(e).__name__}")
raise SyndicationError(f"{url}: too many redirects")
def page_card(http: httpx.Client, url: str) -> dict:
"""
A page's title, description and image URL (Open Graph, Twitter or plain
HTML tags), for a link card. Missing parts come back empty; a page that
can't be fetched gives just the URL as the title.
"""
from urllib.parse import urljoin
from bs4 import BeautifulSoup
card = {"title": url, "description": "", "image": ""}
try:
data, content_type, final = _fetch_public(http, url, CARD_PAGE_LIMIT, truncate=True)
except SyndicationError as e:
current_app.logger.info(f"No link card details for {url}: {e}")
return card
if "html" not in content_type.lower():
return card
soup = BeautifulSoup(data, "html.parser")
def meta(*names):
for name in names:
tag = soup.find("meta", attrs={"property": name}) or soup.find("meta", attrs={"name": name})
if tag and (tag.get("content") or "").strip():
return " ".join(tag["content"].split())
return ""
title = meta("og:title", "twitter:title")
if not title and soup.title:
title = " ".join(soup.title.get_text(" ").split())
image = meta("og:image:secure_url", "og:image", "og:image:url", "twitter:image")
card.update(title=title or url,
description=meta("og:description", "twitter:description", "description"),
image=urljoin(final, image) if image else "")
return card
THREADS_API = "https://graph.threads.net/v1.0"
THREADS_IMAGE_TYPES = {"image/jpeg", "image/png"}
THREADS_IMAGE_LIMIT = 8_000_000
THREADS_MAX_LINKS = 5
THREADS_REFRESH_EVERY = 24 * 3600 # tokens last 60 days; Meta allows a refresh once one is a day old
# Graph API error codes that are temporary (rate limits, service hiccups)
_GRAPH_TRANSIENT = {1, 2, 4, 17, 32, 341, 613}
_GRAPH_AUTH = {10, 190, 200} # bad token or missing permission: retrying won't help
def threads_length(text: str) -> int:
"""Length as Threads counts it: emoji (and, to be safe, all non-ASCII) by UTF-8 bytes"""
return sum(1 if ord(ch) < 128 else len(ch.encode()) for ch in text)
def threads_topic(tags: List[str]) -> str:
"""The first tag usable as a Threads topic (one per post; no '.' or '&', 1-50 chars)"""
for tag in tags:
topic = re.sub(r"[.&]", "", tag).strip()[:50]
if topic:
return topic
return ""
class ThreadsClient:
"""
Minimal Threads API client (Meta Graph API)
Posting is two steps: create a container, wait for it to be ready, then
publish it. Meta fetches images from their public URL on this site.
Posts can't be edited through the API, so only deletes follow.
Long-lived tokens expire after 60 days unless refreshed. `maintain()`
refreshes the token once a day and keeps it in `token_file`, so it
survives restarts. A different token in the config replaces it.
"""
can_edit = False
def __init__(self, token: str, token_file: Optional[Path] = None, api: str = THREADS_API,
http: Optional[httpx.Client] = None, sleep=time.sleep):
self.config_token = token
self.token_file = Path(token_file) if token_file else None
self.api = api.rstrip("/")
self.http = http or httpx.Client(timeout=30.0)
self.sleep = sleep
self.user_id: Optional[str] = None
self.username: Optional[str] = None
self._lock = threading.Lock()
self._token = token
self._checked_at = 0.0
saved = self._read_file()
if saved:
self._token = saved["token"]
# --- Token ---
def _seed(self) -> str:
return hashlib.sha256(self.config_token.encode()).hexdigest()
def _read_file(self) -> Optional[dict]:
"""The saved token, if it descends from the configured one"""
if not self.token_file or not self.token_file.exists():
return None
try:
data = json.loads(self.token_file.read_text())
except (OSError, ValueError):
return None
return data if data.get("seed") == self._seed() and data.get("token") else None
def _write_file(self, token: str, refreshed_at: float) -> None:
tmp = self.token_file.with_suffix(".tmp")
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as f:
json.dump({"seed": self._seed(), "token": token, "refreshed_at": refreshed_at}, f)
os.replace(tmp, self.token_file)
def maintain(self) -> None:
"""Refresh the token if a day has passed since the last try (cheap to call often)"""
now = time.time()
if now - self._checked_at < THREADS_REFRESH_EVERY:
return
self._checked_at = now
if not self.token_file:
return
# Gunicorn workers share the file: one refreshes, the others pick up its result
self.token_file.parent.mkdir(parents=True, exist_ok=True)
with open(self.token_file.with_suffix(".lock"), "w") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
saved = self._read_file()
if saved:
self._token = saved["token"]
if now - saved.get("refreshed_at", 0) < THREADS_REFRESH_EVERY:
self._checked_at = saved["refreshed_at"]
return
base = self.api.rsplit("/", 1)[0] # refresh lives outside the versioned path
try:
response = self.http.get(f"{base}/refresh_access_token", params={
"grant_type": "th_refresh_token", "access_token": self._token})
except httpx.HTTPError as e:
current_app.logger.warning(f"Threads token refresh failed: {type(e).__name__}")
self._checked_at = now - THREADS_REFRESH_EVERY + 3600 # try again in an hour
return
if response.status_code < 400:
self._token = response.json()["access_token"]
current_app.logger.info("Threads access token refreshed")
else:
# e.g. a token less than a day old: keep it, try again tomorrow
current_app.logger.warning(
f"Threads token refresh failed: HTTP {response.status_code} {response.text[:200]}")
self._write_file(self._token, now)
# --- Graph plumbing ---
def _call(self, method: str, path: str, **params) -> dict:
params["access_token"] = self._token
kwargs = {"params": params} if method in ("GET", "DELETE") else {"data": params}
try:
response = self.http.request(method, f"{self.api}/{path}", **kwargs)
except httpx.HTTPError as e:
raise SyndicationError(f"{method} {path}: {type(e).__name__}") # never echo the URL/token
try:
body = response.json()
except ValueError:
body = {}
error = body.get("error") if isinstance(body, dict) else None
if response.status_code >= 400 or error:
error = error if isinstance(error, dict) else {}
code = error.get("code")
detail = " / ".join(str(error[k]) for k in ("error_user_title", "error_user_msg")
if error.get(k))
message = (f"{method} {path}: HTTP {response.status_code} "
f"{error.get('message') or response.text[:200]}"
f" (code {code}, subcode {error.get('error_subcode')}"
f"{', ' + detail if detail else ''}, fbtrace {error.get('fbtrace_id')})")
if response.status_code == 404 or (code == 100 and error.get("error_subcode") == 33):
raise RemoteGone(message, permanent=True)
permanent = (400 <= response.status_code < 500 and response.status_code != 429
and code not in _GRAPH_TRANSIENT)
exc = SyndicationError(message, permanent=permanent)
exc.code = code
raise exc
return body
def _me(self) -> str:
with self._lock:
if not self.user_id:
me = self._call("GET", "me", fields="id,username")
self.user_id, self.username = me["id"], me.get("username")
return self.user_id
def _wait(self, container_id: str) -> None:
"""Wait until Meta has processed a container (images take a few seconds)"""
delay = 1
self.sleep(2) # Meta can report a container ready a moment too early
for _ in range(8):
status = self._call("GET", container_id, fields="status,error_message")
state = status.get("status")
if state in ("FINISHED", None):
return
if state in ("ERROR", "EXPIRED"):
raise SyndicationError(
f"Threads container {state}: {status.get('error_message') or 'no detail'}",
permanent=True)
self.sleep(delay)
delay = min(delay * 2, 15)
raise SyndicationError("Threads container still processing")
# --- Posts ---
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)
limit = post.max_chars
while True:
text = compose_text(post.note, post.permalink, [], limit, body=body)
over = threads_length(text) - post.max_chars
if over <= 0:
return text
limit -= over
def _image_container(self, uid: str, media: dict, **extra) -> str:
params = {"media_type": "IMAGE", "image_url": media["url"], **extra}
if media["description"]:
params["alt_text"] = media["description"][:1000]
return self._call("POST", f"{uid}/threads", **params)["id"]
def _repost_text(self, post: "Post") -> str:
comment = plain_text(post.note.content, links="inline", max_urls=THREADS_MAX_LINKS - 1)
limit = post.max_chars
while True:
text = compose_repost_text(post, comment, limit)
over = threads_length(text) - post.max_chars
if over <= 0:
return text
limit -= over
def _container(self, uid: str, post: "Post") -> str:
if post.kind == "repost":
# No native repost of outside content: post "🔁 title url"
return self._call("POST", f"{uid}/threads", media_type="TEXT",
text=self._repost_text(post))["id"]
common = {"text": self._text(post)}
topic = threads_topic(post.tags)
if topic:
common["topic_tag"] = topic
# Threads takes JPEG/PNG up to 8 MB; others (GIF, WebP) are left off
images = [m for m in post.media if m["mime_type"] in THREADS_IMAGE_TYPES
and Path(m["path"]).stat().st_size <= THREADS_IMAGE_LIMIT]
if not images:
# No explicit link_attachment: Meta rejects one for a page it hasn't
# seen yet ("Invalid Link Attachment"), but previews the text's
# first link by itself without failing
return self._call("POST", f"{uid}/threads", media_type="TEXT", **common)["id"]
if len(images) == 1:
return self._image_container(uid, images[0], **common)
children = [self._image_container(uid, m, is_carousel_item="true") for m in images]
for child in children:
self._wait(child)
return self._call("POST", f"{uid}/threads", media_type="CAROUSEL",
children=",".join(children), **common)["id"]
def _profile_url(self) -> str:
return f"https://www.threads.com/@{self.username}" if self.username else "https://www.threads.com/"
def _find_existing(self, uid: str, link: str) -> Optional[dict]:
"""A recent post that already has this link (an earlier send whose reply was lost)"""
listing = self._call("GET", f"{uid}/threads", fields="id,text,permalink", limit=25)
for item in listing.get("data", []):
if link in (item.get("text") or ""):
return {"id": item["id"], "url": item.get("permalink") or self._profile_url()}
return None
def create(self, post: "Post", key: str, retrying: bool = False) -> dict:
if post.kind == "like" and post.target_url:
return {"id": None, "url": None} # the API can't like things; likes stay on the site
uid = self._me()
if retrying:
marker = post.target_url if post.kind == "repost" and post.target_url else post.permalink
existing = self._find_existing(uid, marker)
if existing:
return existing
container = self._container(uid, post)
self._wait(container)
try:
media_id = self._call("POST", f"{uid}/threads_publish", creation_id=container)["id"]
except SyndicationError as e:
if getattr(e, "code", None) in _GRAPH_AUTH:
raise
# Meta's publish step fails now and then ("Fatal") and works on a
# later try; the retry checks for an existing post first
raise SyndicationError(str(e))
try:
url = self._call("GET", media_id, fields="permalink").get("permalink")
except SyndicationError:
url = None # it's published; don't fail (and post twice) over the link
return {"id": media_id, "url": url or self._profile_url()}
def update(self, remote_id: str, post: "Post") -> dict:
raise NotImplementedError("Threads posts can't be edited through the API")
def delete(self, remote_id: str) -> None:
try:
self._call("DELETE", remote_id)
except RemoteGone:
pass # already gone
@dataclass
@@ -446,6 +828,7 @@ def targets_configured(config) -> bool:
return bool(
(config.get("GOTOSOCIAL_URL") and config.get("GOTOSOCIAL_ACCESS_TOKEN"))
or (config.get("BLUESKY_HANDLE") and config.get("BLUESKY_APP_PASSWORD"))
or config.get("THREADS_ACCESS_TOKEN")
)
@@ -487,6 +870,23 @@ def get_targets() -> Dict[str, Target]:
max_chars=int(config.get("BLUESKY_MAX_CHARS", 300)),
max_media=4,
)
token = config.get("THREADS_ACCESS_TOKEN") or ""
if token:
client = _client_cache.get("threads")
if client is None or client.config_token != token:
client = ThreadsClient(token, Path(config["DATA_PATH"]) / "threads_token.json",
api=config.get("THREADS_API") or THREADS_API)
_client_cache["threads"] = client
username = (config.get("THREADS_USERNAME") or "").lstrip("@")
targets["threads"] = Target(
id="threads",
uid=f"https://www.threads.com/@{username}" if username else "https://www.threads.com/",
name=config.get("THREADS_NAME", "Threads"),
client=client,
max_chars=int(config.get("THREADS_MAX_CHARS", 500)),
max_media=int(config.get("THREADS_MAX_MEDIA", 4)),
)
return targets
@@ -609,14 +1009,75 @@ def compose_text(note, permalink: str, tags: List[str], max_chars: int,
_BLOCKS = ["p", "h1", "h2", "h3", "h4", "h5", "h6", "pre", "blockquote", "ul", "ol", "hr", "table"]
def plain_text(markdown_text: str) -> str:
"""Markdown as readable plain text (for targets without Markdown)"""
def _note_soup(markdown_text: str):
import markdown
from bs4 import BeautifulSoup
soup = BeautifulSoup(markdown.markdown(markdown_text, extensions=["fenced_code"]), "html.parser")
return BeautifulSoup(markdown.markdown(markdown_text, extensions=["fenced_code"]), "html.parser")
def _clean_url(url: str) -> str:
return url.rstrip(".,;:!?)\"'…")
def _is_web(url: str) -> bool:
return url.startswith(("http://", "https://"))
def note_links(markdown_text: str) -> List[str]:
"""Web links in a note, in reading order: Markdown links, <autolinks> and bare URLs"""
from bs4 import NavigableString
links = []
for node in _note_soup(markdown_text).descendants:
if getattr(node, "name", None) == "a" and _is_web(node.get("href", "")):
links.append(node["href"])
elif isinstance(node, NavigableString) and not node.find_parent("a"):
links.extend(_clean_url(m.group(0)) for m in _URL_RE.finditer(str(node)))
return list(dict.fromkeys(links))
def plain_text(markdown_text: str, links: str = "text", max_urls: Optional[int] = None) -> str:
"""Markdown as readable plain text (for targets without Markdown). See `plain_text_links`."""
return plain_text_links(markdown_text, links, max_urls)[0]
def plain_text_links(markdown_text: str, links: str = "text",
max_urls: Optional[int] = None) -> tuple:
"""
Markdown as plain text, and the links whose text stands in for a URL.
A Markdown link `[text](url)` becomes:
links="text" just its text
links="inline" "text (url)", for targets with no clickable link text;
after `max_urls` different URLs, just the text
links="anchor" its text, listed in the returned anchors as (text, url)
so the target can make that text clickable
A link whose text is the URL itself stays a bare URL.
"""
from bs4 import NavigableString
soup = _note_soup(markdown_text)
for img in soup.find_all("img"):
img.decompose()
anchors = []
seen = set()
for node in list(soup.descendants): # bare URLs count towards max_urls first
if isinstance(node, NavigableString) and not node.find_parent("a"):
seen.update(_clean_url(m.group(0)) for m in _URL_RE.finditer(str(node)))
for a in soup.find_all("a"):
href, label = a.get("href", ""), a.get_text()
if not _is_web(href):
continue
bare = re.sub(r"^https?://", "", href).rstrip("/")
if label.strip().rstrip("/") in (href.rstrip("/"), bare):
a.replace_with(href)
seen.add(href)
elif links == "inline" and (href in seen or max_urls is None or len(seen) < max_urls):
a.replace_with(f"{label} ({href})")
seen.add(href)
elif links == "anchor":
anchors.append((label, href))
for node in soup.find_all(string=True):
if not node.strip() and "\n" in node and node.parent.name != "pre":
node.extract() # layout newlines between tags; we add our own
@@ -629,24 +1090,41 @@ def plain_text(markdown_text: str) -> str:
block.append("\n\n")
text = soup.get_text()
text = re.sub(r"[ \t]+\n", "\n", text)
return re.sub(r"\n{3,}", "\n\n", text).strip()
return re.sub(r"\n{3,}", "\n\n", text).strip(), anchors
_URL_RE = re.compile(r"https?://[^\s<>\"]+")
_TAG_RE = re.compile(r"(?<![\w#])#(\w*[^\W\d]\w*)")
def bluesky_facets(text: str) -> List[dict]:
"""Link and hashtag facets (UTF-8 byte ranges) for a Bluesky post"""
def bluesky_facets(text: str, anchors: List[tuple] = ()) -> List[dict]:
"""
Link and hashtag facets (UTF-8 byte ranges) for a Bluesky post.
`anchors` are (text, url) pairs: that text, where it appears, links to url.
"""
def span(start: int, end: int) -> dict:
return {"byteStart": len(text[:start].encode()), "byteEnd": len(text[:end].encode())}
facets = []
for m in _URL_RE.finditer(text):
url = m.group(0).rstrip(".,;:!?)\"'…")
url = _clean_url(m.group(0))
facets.append({"index": span(m.start(), m.start() + len(url)),
"features": [{"$type": "app.bsky.richtext.facet#link", "uri": url}]})
taken = [(m.start(), m.end()) for m in _URL_RE.finditer(text)]
pos = 0
for label, url in anchors:
start = text.find(label, pos) if label.strip() else -1
if start < 0:
continue # shortened away
end = start + len(label)
if any(a < end and start < b for a, b in taken):
continue
taken.append((start, end))
pos = end
facets.append({"index": span(start, end),
"features": [{"$type": "app.bsky.richtext.facet#link", "uri": url}]})
urls = [(f["index"]["byteStart"], f["index"]["byteEnd"]) for f in facets]
facets.sort(key=lambda f: f["index"]["byteStart"])
for m in _TAG_RE.finditer(text):
index = span(m.start(), m.end())
if any(a <= index["byteStart"] < b for a, b in urls):
@@ -661,12 +1139,14 @@ def _media_files(note_id: int, limit: int) -> List[dict]:
from starpunk.media import get_note_media
media_dir = Path(current_app.config["DATA_PATH"]) / "media"
site = current_app.config["SITE_URL"].rstrip("/")
files = []
for media in get_note_media(note_id)[:limit]:
variant = (media.get("variants") or {}).get("large")
rel = variant["path"] if variant else media["path"]
files.append({
"path": media_dir / rel,
"url": f"{site}/media/{rel}", # for targets that fetch images themselves
"mime_type": media.get("mime_type") or "image/jpeg",
"description": media.get("caption") or "",
})
@@ -785,6 +1265,13 @@ def process_due(limit: int = 5) -> int:
targets = get_targets()
if not targets:
return 0
for target in targets.values():
maintain = getattr(target.client, "maintain", None)
if maintain:
try:
maintain()
except Exception as e:
current_app.logger.error(f"Syndication {target.id} upkeep failed: {e}")
db = get_db(current_app)
rows = db.execute(
"""
+120 -2
View File
@@ -92,8 +92,31 @@ def pds():
return FakePDS()
class FakeWeb:
"""Other people's pages, for link cards: url -> (status, headers, body)"""
def __init__(self):
self.pages = {}
self.fetched = []
def __call__(self, request):
url = str(request.url)
self.fetched.append(url)
status, headers, body = self.pages.get(url, (404, {}, b"nope"))
return httpx.Response(status, headers=headers, content=body)
@pytest.fixture
def app(tmp_path, pds):
def web():
return FakeWeb()
def routed(pds, web):
return httpx.MockTransport(
lambda r: pds(r) if r.url.host in ("bsky.example", "pds.example") else web(r))
@pytest.fixture
def app(tmp_path, pds, web):
data = tmp_path / "data"
app = create_app({
"TESTING": True,
@@ -108,7 +131,7 @@ def app(tmp_path, pds):
"BLUESKY_SERVICE": SERVICE,
})
syndication._client_cache[f"bluesky:{SERVICE}:phil.example"] = BlueskyClient(
SERVICE, "phil.example", "app-pass", http=httpx.Client(transport=httpx.MockTransport(pds))
SERVICE, "phil.example", "app-pass", http=httpx.Client(transport=routed(pds, web))
)
yield app
syndication._client_cache.clear()
@@ -258,6 +281,101 @@ class TestMedia:
assert image["aspectRatio"]["width"] > 0
ARTICLE = "https://news.example/story"
ARTICLE_HTML = b"""<html><head><title>Fallback title</title>
<meta property="og:title" content="A Great Story">
<meta property="og:description" content="What happened, in short.">
<meta property="og:image" content="/img/story.png">
</head><body>...</body></html>"""
def png_bytes():
buf = io.BytesIO()
Image.new("RGB", (60, 40), (10, 120, 200)).save(buf, format="PNG")
return buf.getvalue()
class TestLinkCards:
def test_note_link_gets_the_card(self, app, pds, web):
web.pages[ARTICLE] = (200, {"content-type": "text/html"}, ARTICLE_HTML)
web.pages["https://news.example/img/story.png"] = (200, {"content-type": "image/png"}, png_bytes())
note = publish(app, content=f"Read [this story]({ARTICLE}) now")
record = only_record(pds)
external = record["embed"]["external"]
assert external["uri"] == ARTICLE
assert external["title"] == "A Great Story"
assert external["description"] == "What happened, in short."
assert external["thumb"]["$type"] == "blob"
# The link text is clickable and the note's permalink is still in the text
permalink = f"https://blog.example.com/note/{note.slug}"
assert record["text"].startswith("Read this story now") and permalink in record["text"]
raw = record["text"].encode()
links = {raw[f["index"]["byteStart"]:f["index"]["byteEnd"]].decode(): f["features"][0]["uri"]
for f in record["facets"]}
assert links["this story"] == ARTICLE
assert links[permalink] == permalink
def test_bare_url_gets_the_card(self, app, pds, web):
web.pages[ARTICLE] = (200, {"content-type": "text/html"}, ARTICLE_HTML)
publish(app, content=f"See {ARTICLE}.")
assert only_record(pds)["embed"]["external"]["uri"] == ARTICLE
def test_unreachable_page_still_gets_a_card(self, app, pds, web):
note = publish(app, content=f"See {ARTICLE}")
external = only_record(pds)["embed"]["external"]
assert external == {"uri": ARTICLE, "title": ARTICLE, "description": ""}
assert row(app, note)["state"] == "synced"
def test_redirect_to_private_address_is_not_followed(self, app, pds, web, monkeypatch):
web.pages[ARTICLE] = (302, {"location": "http://internal.example/admin"}, b"")
monkeypatch.setattr("starpunk.micropub._public_address", lambda host: host != "internal.example")
app.config["TESTING"] = False
try:
publish(app, content=f"See {ARTICLE}")
finally:
app.config["TESTING"] = True
assert "http://internal.example/admin" not in web.fetched
assert only_record(pds)["embed"]["external"]["title"] == ARTICLE
def test_images_win_over_link_card(self, app, pds, web):
from starpunk.media import attach_media_to_note, save_media
with app.test_request_context():
note = create_note(content=f"Look {ARTICLE}", published=True)
media = save_media(png_bytes(), "a.png")
attach_media_to_note(note.id, [media["id"]], ["pic"])
select_targets(note.id, ["bluesky"])
process_due()
assert only_record(pds)["embed"]["$type"] == "app.bsky.embed.images"
assert web.fetched == []
class TestLinkText:
def test_note_links_in_reading_order(self):
from starpunk.syndication import note_links
md = "a [x](https://one.example) b https://two.example/p. c <https://three.example> [rel](/local)"
assert note_links(md) == ["https://one.example", "https://two.example/p", "https://three.example"]
def test_link_modes(self):
from starpunk.syndication import plain_text_links
md = "[a story](https://s.example) and [https://u.example](https://u.example)"
assert plain_text_links(md)[0] == "a story and https://u.example"
assert plain_text_links(md, "inline")[0] == "a story (https://s.example) and https://u.example"
assert plain_text_links(md, "anchor") == ("a story and https://u.example",
[("a story", "https://s.example")])
def test_inline_url_budget(self):
from starpunk.syndication import plain_text_links
md = "https://bare.example then [one](https://1.example) [two](https://2.example) [one again](https://1.example)"
text = plain_text_links(md, "inline", max_urls=2)[0]
assert text == "https://bare.example then one (https://1.example) two one again (https://1.example)"
def test_anchor_facet_byte_offsets(self):
text = "Café ☕ this story and more"
(facet,) = bluesky_facets(text, [("this story", "https://s.example")])
raw = text.encode()
assert raw[facet["index"]["byteStart"]:facet["index"]["byteEnd"]] == b"this story"
def test_both_targets_listed_for_micropub(tmp_path):
data = tmp_path / "d"
app = create_app({
+418
View File
@@ -0,0 +1,418 @@
"""
Tests for crossposting to Threads (starpunk/syndication.py, v2.6.0)
A fake Graph API (httpx.MockTransport) records what StarPunk sends.
"""
import io
import json
import time
from urllib.parse import parse_qsl
import httpx
import pytest
from PIL import Image
from starpunk import create_app, syndication
from starpunk.notes import create_note, delete_note, update_note
from starpunk.syndication import (
THREADS_REFRESH_EVERY,
ThreadsClient,
get_note_syndications,
process_due,
select_targets,
threads_length,
threads_topic,
)
API = "https://graph.threads.example/v1.0"
UID = "1789"
class FakeThreads:
def __init__(self):
self.containers = {}
self.posts = {}
self.calls = []
self.token = "tok1"
self.refreshes = 0
self.refresh_fails = False
self.pending_polls = 0
self.lose_next_publish = False
self.fail_next = None
self.fail_next_publish = False
def _json(self, code, body):
return httpx.Response(code, json=body)
def _error(self, code, message, err_code, subcode=None):
error = {"message": message, "type": "OAuthException", "code": err_code}
if subcode:
error["error_subcode"] = subcode
return self._json(code, {"error": error})
def __call__(self, request: httpx.Request) -> httpx.Response:
params = dict(request.url.params)
if request.content:
params.update(parse_qsl(request.content.decode()))
path = request.url.path
self.calls.append((request.method, path, params))
if path == "/refresh_access_token":
assert params["grant_type"] == "th_refresh_token"
if self.refresh_fails or params.get("access_token") != self.token:
return self._error(400, "token too new", 190)
self.refreshes += 1
self.token = f"tok{self.refreshes + 1}"
return self._json(200, {"access_token": self.token, "token_type": "bearer",
"expires_in": 5184000})
if params.get("access_token") != self.token:
return self._error(400, "Invalid OAuth access token", 190)
if self.fail_next:
code, err, self.fail_next = *self.fail_next, None
return self._error(code, "nope", err)
path = path.removeprefix("/v1.0/")
if path == "me":
return self._json(200, {"id": UID, "username": "phil"})
if path == f"{UID}/threads" and request.method == "POST":
cid = f"c{len(self.containers) + 1}"
self.containers[cid] = params
return self._json(200, {"id": cid})
if path == f"{UID}/threads" and request.method == "GET":
return self._json(200, {"data": [
{"id": pid, "text": p["text"], "permalink": f"https://www.threads.com/@phil/post/{pid}"}
for pid, p in self.posts.items()]})
if path == f"{UID}/threads_publish" and self.fail_next_publish:
self.fail_next_publish = False
return self._error(400, "Fatal", 24, 4279009)
if path == f"{UID}/threads_publish":
container = self.containers[params["creation_id"]]
pid = f"p{len(self.posts) + 1}"
self.posts[pid] = container
if self.lose_next_publish:
self.lose_next_publish = False
raise httpx.ReadTimeout("lost reply")
return self._json(200, {"id": pid})
if path in self.containers and request.method == "GET":
if self.pending_polls:
self.pending_polls -= 1
return self._json(200, {"status": "IN_PROGRESS"})
return self._json(200, {"status": "FINISHED"})
if path in self.posts and request.method == "GET":
return self._json(200, {"id": path, "permalink": f"https://www.threads.com/@phil/post/{path}"})
if request.method == "DELETE":
if self.posts.pop(path, None) is None:
return self._error(400, "Object does not exist", 100, 33)
return self._json(200, {"success": True, "deleted_id": path})
return self._json(500, {"error": {"message": "unknown", "code": 2}})
@pytest.fixture
def api():
return FakeThreads()
def make_client(app, api, token="tok1"):
return ThreadsClient(token, app.config["DATA_PATH"] / "threads_token.json", api=API,
http=httpx.Client(transport=httpx.MockTransport(api)), sleep=lambda s: None)
@pytest.fixture
def app(tmp_path, api):
data = tmp_path / "data"
app = create_app({
"TESTING": True,
"SITE_URL": "https://blog.example.com",
"ADMIN_ME": "https://example.com",
"SESSION_SECRET": "test-secret",
"DATA_PATH": data,
"NOTES_PATH": data / "notes",
"DATABASE_PATH": data / "starpunk.db",
"THREADS_ACCESS_TOKEN": "tok1",
"THREADS_USERNAME": "phil",
})
syndication._client_cache["threads"] = make_client(app, api)
yield app
syndication._client_cache.clear()
def publish(app, content="Hello Threads", tags=None):
with app.test_request_context():
note = create_note(content=content, published=True, tags=tags)
select_targets(note.id, ["threads"])
process_due()
return note
def only_post(api):
(post,) = api.posts.values()
return post
def row(app, note):
with app.app_context():
(r,) = get_note_syndications(note.id)
return r
def image_bytes(fmt="JPEG", size=(800, 600)):
buf = io.BytesIO()
Image.new("RGB", size, (200, 30, 30)).save(buf, format=fmt)
return buf.getvalue()
class TestText:
def test_emoji_count_as_bytes(self):
assert threads_length("abc") == 3
assert threads_length("☕") == 3
def test_topic_is_first_usable_tag(self):
assert threads_topic(["...", "Indie.Web & Co", "x"]) == "IndieWeb Co"
assert threads_topic([]) == ""
class TestLifecycle:
def test_publish_text_post(self, app, api):
note = publish(app, content="Hello **Threads**", tags=["IndieWeb", "Second"])
post = only_post(api)
permalink = f"https://blog.example.com/note/{note.slug}"
assert post["media_type"] == "TEXT"
assert post["text"] == f"Hello Threads\n\n{permalink}"
assert "link_attachment" not in post # Threads previews the first link itself
assert post["topic_tag"] == "IndieWeb"
r = row(app, note)
assert r["state"] == "synced"
assert r["remote_id"] == "p1"
assert r["remote_url"] == "https://www.threads.com/@phil/post/p1"
def test_long_note_fits_500(self, app, api):
note = publish(app, content="☕ word " * 300)
text = only_post(api)["text"]
assert threads_length(text) <= 500
assert text.endswith(f"https://blog.example.com/note/{note.slug}")
def test_waits_for_container(self, app, api):
api.pending_polls = 2
note = publish(app)
assert row(app, note)["state"] == "synced"
def test_edit_leaves_post_alone(self, app, api):
note = publish(app, content="first")
with app.test_request_context():
update_note(id=note.id, content="second")
process_due()
assert only_post(api)["text"].startswith("first")
assert row(app, note)["state"] == "synced"
def test_delete_and_unpublish_remove_post(self, app, api):
note = publish(app)
with app.test_request_context():
update_note(id=note.id, published=False)
process_due()
assert api.posts == {}
update_note(id=note.id, published=True)
process_due()
assert len(api.posts) == 1
delete_note(id=note.id)
process_due()
assert api.posts == {}
def test_post_deleted_on_threads_is_fine(self, app, api):
note = publish(app)
api.posts.clear()
with app.test_request_context():
delete_note(id=note.id)
process_due()
assert row(app, note)["state"] == "synced"
class TestErrors:
def test_lost_reply_does_not_double_post(self, app, api):
api.lose_next_publish = True
note = publish(app)
assert row(app, note)["state"] == "pending"
with app.test_request_context():
from starpunk.database import get_db
get_db(app).execute("UPDATE syndications SET next_attempt_at = datetime('now')")
get_db(app).commit()
process_due()
assert len(api.posts) == 1
assert row(app, note)["state"] == "synced"
def test_publish_fatal_is_retried(self, app, api):
api.fail_next_publish = True
note = publish(app)
r = row(app, note)
assert r["state"] == "pending" and "Fatal" in r["last_error"] and "subcode 4279009" in r["last_error"]
with app.test_request_context():
from starpunk.database import get_db
get_db(app).execute("UPDATE syndications SET next_attempt_at = datetime('now')")
get_db(app).commit()
process_due()
assert len(api.posts) == 1
assert row(app, note)["state"] == "synced"
def test_bad_token_fails_permanently(self, app, api):
api.token = "other"
note = publish(app)
r = row(app, note)
assert r["state"] == "failed" and "Invalid OAuth" in r["last_error"]
assert "tok1" not in r["last_error"]
def test_rate_limit_retries(self, app, api):
publish(app, content="warm up")
api.fail_next = (400, 4) # Graph "application request limit reached"
note = publish(app, content="later")
assert row(app, note)["state"] == "pending"
class TestLinks:
def test_markdown_link_comes_first_for_the_preview(self, app, api):
note = publish(app, content="Read [this story](https://news.example/story) now")
text = only_post(api)["text"]
assert text.startswith("Read this story (https://news.example/story) now")
assert text.index("https://news.example/story") < text.index(f"/note/{note.slug}")
def test_stays_within_five_links(self, app, api):
import re
links = " ".join(f"[l{i}](https://l{i}.example)" for i in range(7))
publish(app, content=f"Lots: {links}")
text = only_post(api)["text"]
assert len(set(re.findall(r"https?://[^\s)]+", text))) == 5
assert "l6" in text # the extra links keep their text
class TestMedia:
def _note_with(self, app, images):
from starpunk.media import attach_media_to_note, save_media
with app.test_request_context():
note = create_note(content="pics", published=True)
ids = [save_media(data, name)["id"] for data, name in images]
attach_media_to_note(note.id, ids, [f"alt {i}" for i in range(len(ids))])
select_targets(note.id, ["threads"])
process_due()
return note
def test_single_image(self, app, api):
self._note_with(app, [(image_bytes(), "a.jpg")])
post = only_post(api)
assert post["media_type"] == "IMAGE"
assert post["image_url"].startswith("https://blog.example.com/media/")
assert post["alt_text"] == "alt 0"
assert "link_attachment" not in post
def test_carousel(self, app, api):
self._note_with(app, [(image_bytes(), "a.jpg"), (image_bytes("PNG"), "b.png")])
post = only_post(api)
assert post["media_type"] == "CAROUSEL"
children = [api.containers[c] for c in post["children"].split(",")]
assert [c["is_carousel_item"] for c in children] == ["true", "true"]
assert [c["alt_text"] for c in children] == ["alt 0", "alt 1"]
def test_unsupported_format_is_left_off(self, app, api):
self._note_with(app, [(image_bytes("WEBP"), "a.webp")])
assert only_post(api)["media_type"] == "TEXT"
class TestToken:
def test_refreshes_daily_and_saves(self, app, api):
client = syndication._client_cache["threads"]
with app.app_context():
client.maintain()
assert api.refreshes == 1
client.maintain() # same day: nothing
assert api.refreshes == 1
saved = json.loads((app.config["DATA_PATH"] / "threads_token.json").read_text())
assert saved["token"] == "tok2"
# A restart picks up the saved token
assert make_client(app, api)._token == "tok2"
publish(app)
assert len(api.posts) == 1
def test_other_worker_refresh_is_reused(self, app, api):
first, second = make_client(app, api), make_client(app, api)
with app.app_context():
first.maintain()
second.maintain()
assert api.refreshes == 1
assert second._token == "tok2"
def test_refresh_due_after_a_day(self, app, api, monkeypatch):
client = syndication._client_cache["threads"]
with app.app_context():
client.maintain()
later = time.time() + THREADS_REFRESH_EVERY + 1
monkeypatch.setattr(syndication.time, "time", lambda: later)
client.maintain()
assert api.refreshes == 2
def test_failed_refresh_keeps_token(self, app, api):
api.refresh_fails = True
client = syndication._client_cache["threads"]
with app.app_context():
client.maintain()
assert client._token == "tok1"
publish(app)
assert len(api.posts) == 1
def test_new_config_token_replaces_saved_one(self, app, api):
with app.app_context():
syndication._client_cache["threads"].maintain()
api.token = "fresh"
assert make_client(app, api, token="fresh")._token == "fresh"
def test_worker_runs_upkeep(self, app, api):
with app.app_context():
process_due()
assert api.refreshes == 1
def test_all_targets_listed_for_micropub(tmp_path):
data = tmp_path / "d"
app = create_app({
"TESTING": True, "SITE_URL": "https://b.example", "ADMIN_ME": "https://e.example",
"SESSION_SECRET": "x", "DATA_PATH": data, "NOTES_PATH": data / "notes",
"DATABASE_PATH": data / "s.db",
"GOTOSOCIAL_URL": "https://social.example", "GOTOSOCIAL_ACCESS_TOKEN": "t",
"BLUESKY_HANDLE": "phil.example", "BLUESKY_APP_PASSWORD": "p",
"THREADS_ACCESS_TOKEN": "x", "THREADS_USERNAME": "@phil",
})
with app.app_context():
from starpunk.syndication import get_targets, resolve_targets
assert set(get_targets()) == {"gotosocial", "bluesky", "threads"}
assert resolve_targets(["https://www.threads.com/@phil"]) == ["threads"]
syndication._client_cache.clear()
class TestLikesReposts:
PAGE = "https://other.example/post/1"
def _post(self, app, monkeypatch, content="", **kind):
monkeypatch.setattr("starpunk.reply_context.fetch_reply_context", lambda *a, **k: None)
with app.test_request_context():
note = create_note(content=content, published=True, **kind)
select_targets(note.id, ["threads"])
process_due()
return note
def test_like_is_not_crossposted(self, app, api, monkeypatch):
note = self._post(app, monkeypatch, like_of=self.PAGE)
assert api.posts == {}
r = row(app, note)
assert r["state"] == "synced" and r["remote_id"] is None
def test_repost_posts_link(self, app, api, monkeypatch):
self._post(app, monkeypatch, repost_of=self.PAGE)
post = only_post(api)
assert post["text"].startswith("🔁") and self.PAGE in post["text"]
assert "link_attachment" not in post
def test_repost_with_comment_keeps_comment(self, app, api, monkeypatch):
note = self._post(app, monkeypatch, content="So **true**", repost_of=self.PAGE)
assert only_post(api)["text"].startswith("So true")
with app.test_request_context():
delete_note(id=note.id)
process_due()
assert api.posts == {}