Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c87de892cf | ||
|
|
615354d17e | ||
|
|
9074c9a08c | ||
|
|
964a44c95e | ||
|
|
acd6bf819d | ||
|
|
bf6e0fdc0b | ||
|
|
952ca300c0 |
No files matched your search
@@ -7,6 +7,46 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [2.21.0] - 2026-11-28
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- The homepage pages through every note: 20 per page, with "← Newer" and "Older →" links and "Page N of M" at the bottom. Before, it showed only the 20 newest notes and older ones could only be found through tags, search or the feeds. Page 1 stays at `/`; later pages are `/?page=2` and on (`/?page=1` redirects to `/`), and their title starts "Page N ·". The links carry `rel="prev"`/`rel="next"`, so IndieWeb readers can page back through the h-feed
|
||||||
|
- The Likes page pages the same way, 50 per page (it showed only the 50 newest likes)
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- The admin dashboard only ever listed the 50 newest notes ("Page 1 of 2" whatever the real count), because it paged the default 50-note result of `list_notes()`. It now counts all notes and fetches just the requested page. A bad `?page=` no longer raises a server error; it goes to the nearest valid page
|
||||||
|
- Public list pages answer a page number that isn't a positive whole number, or is past the last page, with 404
|
||||||
|
|
||||||
|
## [2.20.3] - 2026-11-27
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- On an article's page the summary looked like the first paragraph of the body. It is now set as a subtitle under the title: sans font, a little larger, muted colour, with a line before the body. The homepage teaser is unchanged
|
||||||
|
|
||||||
|
## [2.20.2] - 2026-11-13
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Replies to replies on crossposts were never captured. Backfeed read only the first level of replies (Threads `/replies`, GoToSocial's direct replies, Bluesky at depth 1). It now reads the whole conversation (Threads `/conversation`, every GoToSocial descendant, Bluesky ten levels deep)
|
||||||
|
- Your own replies in those conversations were skipped, so the other side of a back-and-forth was missing. They are now kept when they answer someone's reply (a reply to your own crosspost is the thread continuing, and is still left out). They don't send you notifications
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Replies are shown nested under the reply they answer, as comments of comments (`u-comment` inside the parent `h-cite`). Migration 026 adds `webmentions.parent_remote_id`. Existing crossposts pick up their threads at their next backfeed check
|
||||||
|
|
||||||
|
## [2.20.1] - 2026-11-13
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- A reply to a Mastodon post with a GIF showed a still image. Mastodon turns GIFs into short silent looping MP4s ("gifv"), and only their first frame was kept. The MP4 is now saved on this site and plays muted and looping, as on Mastodon, with the still image as its poster
|
||||||
|
- Animated GIFs (and animated WebP/PNG) from other sites stay animated in reply contexts instead of being cut to their first frame
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Migration 025 adds `video` to `reply_contexts`, and has fediverse contexts with an image fetched again once, so existing replies pick up their gifv
|
||||||
|
|
||||||
## [2.20.0] - 2026-11-13
|
## [2.20.0] - 2026-11-13
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# v2.20.1: Moving pictures in reply contexts
|
||||||
|
|
||||||
|
## Why
|
||||||
|
|
||||||
|
The reply https://starpunk.thesatelliteoflove.com/note/20261114032356 answers
|
||||||
|
an infosec.exchange post with a GIF, but the card showed a still. Mastodon
|
||||||
|
converts uploaded GIFs to a silent looping MP4 (`media_attachments[].type ==
|
||||||
|
"gifv"`, here 320×240, 5.3 s, ~140 KB). Its `preview_url` is a PNG of the
|
||||||
|
first frame, which is all v2.19.0 kept.
|
||||||
|
|
||||||
|
## Changes
|
||||||
|
|
||||||
|
| Area | Change |
|
||||||
|
|---|---|
|
||||||
|
| `reply_context._from_status` | A `gifv` attachment's `url` goes into the new `video` field (the preview stays in `photo`, used as the poster) |
|
||||||
|
| Migration 025 | `reply_contexts.video`; fediverse rows with a photo get `source = NULL`, so the worker's `refresh_stale` fetches them once more |
|
||||||
|
| `avatars.fetch_video` | Saves the MP4 as `DATA_PATH/previews/<sha256>.mp4` (8 MB cap, must have an `ftyp` box); `fill_missing`/`remove_unused` cover it |
|
||||||
|
| `avatars._save` | Animated GIF/WebP/PNG previews are saved as animated WebP (frames narrowed to 640 px, at most 300 frames) instead of their first frame |
|
||||||
|
| `/previews/<name>` | Also serves `<sha256>.mp4` as `video/mp4` |
|
||||||
|
| Template | `<video autoplay loop muted playsinline poster=…>` with the alt text as `aria-label`, when there is a saved MP4 |
|
||||||
|
|
||||||
|
The MP4 is stored as it is: re-encoding would need ffmpeg in the image, and
|
||||||
|
gifvs are small. Like the images, it has to be served from this site
|
||||||
|
(`default-src 'self'` covers media).
|
||||||
|
|
||||||
|
Real videos (`type == "video"`) and Bluesky videos still show their
|
||||||
|
thumbnail: they can be long and have sound.
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# v2.20.2: Backfeed whole reply threads
|
||||||
|
|
||||||
|
## Why
|
||||||
|
|
||||||
|
https://starpunk.thesatelliteoflove.com/note/20261110191424 showed one reply
|
||||||
|
(curiouskatej, via Threads). The Threads conversation had three:
|
||||||
|
|
||||||
|
```
|
||||||
|
curiouskatej: "It keeps coming up on music compilations…" (kept)
|
||||||
|
└ philskents: "That is terrifying..." (missed)
|
||||||
|
└ curiouskatej: "To be fair it's just as bad as…" (missed)
|
||||||
|
```
|
||||||
|
|
||||||
|
Each client read only the first level of replies: Threads `/{id}/replies`,
|
||||||
|
GoToSocial descendants with `in_reply_to_id == our id`, and Bluesky
|
||||||
|
`getPostThread` at depth 1. All of them also dropped the owner's own replies,
|
||||||
|
which lost one side of the conversation.
|
||||||
|
|
||||||
|
## Changes
|
||||||
|
|
||||||
|
| Area | Change |
|
||||||
|
|---|---|
|
||||||
|
| `backfeed.thread_members(posts, root)` | Decides which replies to keep, and what each answers. Kept: others' replies to our copy, plus any reply (ours too) to a kept reply. Our own replies to our copy are the thread continuing, so they and their replies are left out, as before |
|
||||||
|
| `Response.parent_id`, `.own` | The silo id of the reply this one answers (None for our copy itself), and whether we wrote it |
|
||||||
|
| Threads | `/{id}/conversation` (every depth, newest first) with `replied_to` in the fields |
|
||||||
|
| GoToSocial | All public descendants from `/context` |
|
||||||
|
| Bluesky | `getPostThread` depth `BLUESKY_THREAD_DEPTH` (10), walked recursively; blocked or deleted posts drop their subtree |
|
||||||
|
| Migration 026 | `webmentions.parent_remote_id` |
|
||||||
|
| `backfeed.store` | Stores the parent; own replies are stored as already notified |
|
||||||
|
| `webmention_queries.reply_threads` | Nests replies under their parent (same origin and remote id). A reply whose parent isn't shown goes to the top level |
|
||||||
|
| Templates/CSS | `responses.reply` renders children in `.webmention-thread`, indented with a side rule, as `u-comment h-cite` inside the parent's h-cite |
|
||||||
|
|
||||||
|
The heading still counts every reply ("3 Replies"), and so does the count
|
||||||
|
line under the note.
|
||||||
|
|
||||||
|
Existing crossposts get their threads at their next scheduled check. The
|
||||||
|
check schedule slows with the note's age (ADR-073), and notes past the
|
||||||
|
cutoff aren't checked.
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# v2.21.0: Paging for the homepage, likes and admin dashboard
|
||||||
|
|
||||||
|
## Why
|
||||||
|
|
||||||
|
The production site has 141 notes (140 published), but:
|
||||||
|
|
||||||
|
| Page | Showed | Cause |
|
||||||
|
|---|---|---|
|
||||||
|
| Homepage `/` | the 20 newest | `list_notes(..., limit=20)`, no paging |
|
||||||
|
| `/likes` | the 50 newest likes | `list_notes(..., limit=50)`, no paging |
|
||||||
|
| Admin dashboard | the 50 newest, as "Page 1 of 2" | it paged the result of `list_notes()`, whose default `limit` is 50 (since v1.6.0) |
|
||||||
|
|
||||||
|
So 120 published notes couldn't be reached from the homepage, and 91 notes
|
||||||
|
couldn't be reached from the admin list.
|
||||||
|
|
||||||
|
## How the homepage displays it
|
||||||
|
|
||||||
|
- The same note previews as before, 20 per page, newest first. Likes stay on
|
||||||
|
`/likes`, drafts are never shown.
|
||||||
|
- Below the last note: `← Newer` · `Page 2 of 7` · `Older →`. Page 1 has no
|
||||||
|
"Newer" link, the last page has no "Older" link, and a site with one page
|
||||||
|
of notes shows no pager at all.
|
||||||
|
- URLs: page 1 is `/` (and `/?page=1` redirects there with a 301). Later
|
||||||
|
pages are `/?page=N`. Their browser title is `Page N · <site name>`.
|
||||||
|
- `/likes` works the same way with 50 per page (`Likes · Page N · …`).
|
||||||
|
- The links are `<a rel="prev">` / `<a rel="next">` inside the h-feed, so
|
||||||
|
IndieWeb readers and Microsub clients can page back through the feed.
|
||||||
|
- A page number that isn't a positive whole number, or is past the last
|
||||||
|
page, is a 404.
|
||||||
|
|
||||||
|
## Changes
|
||||||
|
|
||||||
|
| Area | Change |
|
||||||
|
|---|---|
|
||||||
|
| `notes.count_notes(published_only, likes)` | New. `SELECT COUNT(*)` with the same filters as `list_notes()` (shared `_list_filters()`) |
|
||||||
|
| `routes/public.py` | `_paged_notes()` parses `?page=`, counts, and fetches one page with `limit`/`offset`. `_prepare_for_listing()` attaches media, tags, contexts and response counts (was duplicated in `index` and `likes`). `HOME_PER_PAGE = 20`, `LIKES_PER_PAGE = 50` |
|
||||||
|
| `templates/partials/pager.html` | `pager(endpoint, page, total_pages)` macro, used by `index.html` and `likes.html` |
|
||||||
|
| `routes/admin.py` dashboard | Counts with `count_notes()` and fetches only the requested 25. A bad or out-of-range `?page=` goes to the nearest valid page (admin only, so no 404) |
|
||||||
|
| `static/css/style.css` | `.pager` row: newer on the left, position in the middle, older on the right |
|
||||||
|
|
||||||
|
Feeds (RSS, Atom, JSON) are unchanged: they list the newest items only.
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
`tests/test_paging.py`:
|
||||||
|
- `count_notes` filters;
|
||||||
|
- homepage first, middle and last pages, with `rel` links and titles;
|
||||||
|
- every published note reachable exactly once;
|
||||||
|
- drafts and likes never listed;
|
||||||
|
- the `?page=1` redirect;
|
||||||
|
- 404 for bad and out-of-range pages;
|
||||||
|
- no pager when there's a single page, and an empty site;
|
||||||
|
- likes page 2;
|
||||||
|
- the admin dashboard past 50 notes, including drafts, with bad-page
|
||||||
|
fallback.
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
-- Migration 025: Looping videos in reply contexts (v2.20.1)
|
||||||
|
-- Mastodon turns GIFs into silent looping MP4s ("gifv"); video holds its URL,
|
||||||
|
-- shown instead of the still preview. Fediverse contexts with an image are
|
||||||
|
-- fetched again once (no source) so their gifv is picked up.
|
||||||
|
ALTER TABLE reply_contexts ADD COLUMN video TEXT;
|
||||||
|
UPDATE reply_contexts SET source = NULL WHERE source = 'fediverse' AND photo IS NOT NULL;
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
-- Migration 026: Threads of backfed replies (v2.20.2)
|
||||||
|
-- parent_remote_id: the silo id of the response a reply answers; NULL when it
|
||||||
|
-- answers our crosspost itself. Replies are shown nested under their parent.
|
||||||
|
ALTER TABLE webmentions ADD COLUMN parent_remote_id TEXT;
|
||||||
+10
-2
@@ -233,6 +233,14 @@ def create_app(config=None):
|
|||||||
name = cached_preview(app.config.get('DATA_PATH', 'data'), url)
|
name = cached_preview(app.config.get('DATA_PATH', 'data'), url)
|
||||||
return url_for('public.preview', name=name) if name else None
|
return url_for('public.preview', name=name) if name else None
|
||||||
|
|
||||||
|
# Template filter - local copy of a replied-to post's gifv, or None (v2.20.1)
|
||||||
|
@app.template_filter('local_video')
|
||||||
|
def local_video_filter(url):
|
||||||
|
from flask import url_for
|
||||||
|
from starpunk.avatars import cached_video
|
||||||
|
name = cached_video(app.config.get('DATA_PATH', 'data'), url)
|
||||||
|
return url_for('public.preview', name=name) if name else None
|
||||||
|
|
||||||
# Template filter - URL to color for facepile (v1.6.0)
|
# Template filter - URL to color for facepile (v1.6.0)
|
||||||
@app.template_filter('url_to_color')
|
@app.template_filter('url_to_color')
|
||||||
def url_to_color_filter(url):
|
def url_to_color_filter(url):
|
||||||
@@ -476,5 +484,5 @@ def create_app(config=None):
|
|||||||
|
|
||||||
# Package version (Semantic Versioning 2.0.0)
|
# Package version (Semantic Versioning 2.0.0)
|
||||||
# See docs/standards/versioning-strategy.md for details
|
# See docs/standards/versioning-strategy.md for details
|
||||||
__version__ = "2.20.0"
|
__version__ = "2.21.0"
|
||||||
__version_info__ = (2, 20, 0)
|
__version_info__ = (2, 21, 0)
|
||||||
+65
-9
@@ -29,6 +29,10 @@ SIZE = 96
|
|||||||
MAX_BYTES = 1024 * 1024
|
MAX_BYTES = 1024 * 1024
|
||||||
PREVIEW_WIDTH = 640
|
PREVIEW_WIDTH = 640
|
||||||
PREVIEW_MAX_BYTES = 8 * 1024 * 1024
|
PREVIEW_MAX_BYTES = 8 * 1024 * 1024
|
||||||
|
MAX_FRAMES = 300
|
||||||
|
# Mastodon's "GIFs" are silent looping MP4s (gifv); kept as they are (v2.20.1)
|
||||||
|
VIDEO_MAX_BYTES = 8 * 1024 * 1024
|
||||||
|
VIDEO_NAME_RE = re.compile(r"^[0-9a-f]{64}\.mp4$")
|
||||||
# Bluesky avatar on its CDN: .../img/<kind>/plain/<did>/<cid>[@jpeg]
|
# Bluesky avatar on its CDN: .../img/<kind>/plain/<did>/<cid>[@jpeg]
|
||||||
BSKY_CDN_RE = re.compile(
|
BSKY_CDN_RE = re.compile(
|
||||||
r"^https://cdn\.bsky\.app/img/[a-z_]+/plain/(did:(?:plc|web):[A-Za-z0-9._:%-]+)/([a-z2-7]+)(?:@\w+)?$")
|
r"^https://cdn\.bsky\.app/img/[a-z_]+/plain/(did:(?:plc|web):[A-Za-z0-9._:%-]+)/([a-z2-7]+)(?:@\w+)?$")
|
||||||
@@ -65,6 +69,39 @@ def cached_preview(data_path, url: Optional[str]) -> Optional[str]:
|
|||||||
return _cached(preview_folder(data_path), url)
|
return _cached(preview_folder(data_path), url)
|
||||||
|
|
||||||
|
|
||||||
|
def video_name_for(url: str) -> str:
|
||||||
|
return hashlib.sha256(url.encode()).hexdigest() + ".mp4"
|
||||||
|
|
||||||
|
|
||||||
|
def cached_video(data_path, url: Optional[str]) -> Optional[str]:
|
||||||
|
"""File name of the saved copy of a replied-to post's looping video, if there is one"""
|
||||||
|
if not url or not url.startswith(("http://", "https://")):
|
||||||
|
return None
|
||||||
|
name = video_name_for(url)
|
||||||
|
return name if (preview_folder(data_path) / name).is_file() else None
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_video(data_path, url: Optional[str], site_url: str) -> bool:
|
||||||
|
"""Save a copy of a replied-to post's gifv (a short silent MP4) unless there is one"""
|
||||||
|
if not url or not url.startswith(("http://", "https://")):
|
||||||
|
return False
|
||||||
|
path = preview_folder(data_path) / video_name_for(url)
|
||||||
|
if path.is_file():
|
||||||
|
return True
|
||||||
|
try:
|
||||||
|
data = _download(url, site_url, VIDEO_MAX_BYTES)
|
||||||
|
if data[4:8] != b"ftyp":
|
||||||
|
raise ValueError("not an MP4")
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
tmp = path.with_suffix(".tmp")
|
||||||
|
tmp.write_bytes(data)
|
||||||
|
tmp.replace(path)
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
logger.info(f"Could not save video {url}: {type(e).__name__}: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def _square(image):
|
def _square(image):
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
side = min(image.size)
|
side = min(image.size)
|
||||||
@@ -81,6 +118,19 @@ def _narrow(image):
|
|||||||
return image.resize((PREVIEW_WIDTH, height), Image.LANCZOS)
|
return image.resize((PREVIEW_WIDTH, height), Image.LANCZOS)
|
||||||
|
|
||||||
|
|
||||||
|
def _save_animated(image, tmp: Path) -> None:
|
||||||
|
"""An animated GIF/WebP/PNG as an animated WebP, frames narrowed (v2.20.1)"""
|
||||||
|
from PIL import ImageSequence
|
||||||
|
frames, durations = [], []
|
||||||
|
for frame in ImageSequence.Iterator(image):
|
||||||
|
if len(frames) >= MAX_FRAMES:
|
||||||
|
break
|
||||||
|
frames.append(_narrow(frame.convert("RGBA")))
|
||||||
|
durations.append(frame.info.get("duration") or image.info.get("duration") or 100)
|
||||||
|
frames[0].save(tmp, "WEBP", save_all=True, append_images=frames[1:], duration=durations,
|
||||||
|
loop=0, quality=80)
|
||||||
|
|
||||||
|
|
||||||
def _save(path: Path, url: Optional[str], site_url: str, shape, max_bytes: int,
|
def _save(path: Path, url: Optional[str], site_url: str, shape, max_bytes: int,
|
||||||
what: str) -> bool:
|
what: str) -> bool:
|
||||||
if not url or not url.startswith(("http://", "https://")):
|
if not url or not url.startswith(("http://", "https://")):
|
||||||
@@ -91,11 +141,14 @@ def _save(path: Path, url: Optional[str], site_url: str, shape, max_bytes: int,
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
with Image.open(io.BytesIO(_download(url, site_url, max_bytes))) as image:
|
with Image.open(io.BytesIO(_download(url, site_url, max_bytes))) as image:
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
tmp = path.with_suffix(".tmp")
|
||||||
|
if shape is _narrow and getattr(image, "n_frames", 1) > 1:
|
||||||
|
_save_animated(image, tmp)
|
||||||
|
else:
|
||||||
image.load()
|
image.load()
|
||||||
image = image.convert("RGBA" if "A" in image.getbands() else "RGB")
|
image = image.convert("RGBA" if "A" in image.getbands() else "RGB")
|
||||||
image = shape(image)
|
image = shape(image)
|
||||||
path.parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
tmp = path.with_suffix(".tmp")
|
|
||||||
image.save(tmp, "WEBP", quality=80)
|
image.save(tmp, "WEBP", quality=80)
|
||||||
tmp.replace(path)
|
tmp.replace(path)
|
||||||
return True
|
return True
|
||||||
@@ -199,18 +252,19 @@ def _download(url: str, site_url: str, max_bytes: int = MAX_BYTES) -> bytes:
|
|||||||
return _get(url, headers, max_bytes)
|
return _get(url, headers, max_bytes)
|
||||||
|
|
||||||
|
|
||||||
def _context_images(conn) -> tuple[list, list]:
|
def _context_images(conn) -> tuple[list, list, list]:
|
||||||
"""Avatars and post images of reply contexts that notes use (v2.19.0)"""
|
"""Avatars, post images and gifvs of reply contexts that notes use (v2.19.0)"""
|
||||||
rows = conn.execute(
|
rows = conn.execute(
|
||||||
"""
|
"""
|
||||||
SELECT rc.author_photo, rc.photo FROM reply_contexts rc
|
SELECT rc.author_photo, rc.photo, rc.video FROM reply_contexts rc
|
||||||
WHERE rc.fetch_status = 'fetched' AND EXISTS (
|
WHERE rc.fetch_status = 'fetched' AND EXISTS (
|
||||||
SELECT 1 FROM notes n WHERE n.deleted_at IS NULL AND rc.url IN
|
SELECT 1 FROM notes n WHERE n.deleted_at IS NULL AND rc.url IN
|
||||||
(n.in_reply_to, n.like_of, n.repost_of, n.bookmark_of))
|
(n.in_reply_to, n.like_of, n.repost_of, n.bookmark_of))
|
||||||
ORDER BY rc.id DESC
|
ORDER BY rc.id DESC
|
||||||
"""
|
"""
|
||||||
).fetchall()
|
).fetchall()
|
||||||
return [r[0] for r in rows if r[0]], [r[1] for r in rows if r[1]]
|
return ([r[0] for r in rows if r[0]], [r[1] for r in rows if r[1]],
|
||||||
|
[r[2] for r in rows if r[2]])
|
||||||
|
|
||||||
|
|
||||||
def fill_missing(db_path, data_path, site_url: str, limit: int = 20) -> int:
|
def fill_missing(db_path, data_path, site_url: str, limit: int = 20) -> int:
|
||||||
@@ -226,11 +280,12 @@ def fill_missing(db_path, data_path, site_url: str, limit: int = 20) -> int:
|
|||||||
ORDER BY id DESC
|
ORDER BY id DESC
|
||||||
"""
|
"""
|
||||||
)]
|
)]
|
||||||
context_avatars, context_photos = _context_images(conn)
|
context_avatars, context_photos, context_videos = _context_images(conn)
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
wanted = [(url, cached_name, fetch) for url in dict.fromkeys(urls + context_avatars)]
|
wanted = [(url, cached_name, fetch) for url in dict.fromkeys(urls + context_avatars)]
|
||||||
wanted += [(url, cached_preview, fetch_preview) for url in dict.fromkeys(context_photos)]
|
wanted += [(url, cached_preview, fetch_preview) for url in dict.fromkeys(context_photos)]
|
||||||
|
wanted += [(url, cached_video, fetch_video) for url in dict.fromkeys(context_videos)]
|
||||||
tried = 0
|
tried = 0
|
||||||
for url, cached, save in wanted:
|
for url, cached, save in wanted:
|
||||||
if tried >= limit:
|
if tried >= limit:
|
||||||
@@ -248,17 +303,18 @@ def remove_unused(db_path, data_path) -> int:
|
|||||||
try:
|
try:
|
||||||
used = {name_for(row[0]) for row in conn.execute(
|
used = {name_for(row[0]) for row in conn.execute(
|
||||||
"SELECT DISTINCT author_photo FROM webmentions WHERE author_photo IS NOT NULL")}
|
"SELECT DISTINCT author_photo FROM webmentions WHERE author_photo IS NOT NULL")}
|
||||||
context_avatars, context_photos = _context_images(conn)
|
context_avatars, context_photos, context_videos = _context_images(conn)
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
used |= {name_for(url) for url in context_avatars}
|
used |= {name_for(url) for url in context_avatars}
|
||||||
used_previews = {name_for(url) for url in context_photos}
|
used_previews = {name_for(url) for url in context_photos}
|
||||||
|
used_previews |= {video_name_for(url) for url in context_videos}
|
||||||
removed = 0
|
removed = 0
|
||||||
for directory, keep in ((folder(data_path), used), (preview_folder(data_path), used_previews)):
|
for directory, keep in ((folder(data_path), used), (preview_folder(data_path), used_previews)):
|
||||||
if not directory.is_dir():
|
if not directory.is_dir():
|
||||||
continue
|
continue
|
||||||
for path in directory.iterdir():
|
for path in directory.iterdir():
|
||||||
if NAME_RE.match(path.name) and path.name not in keep:
|
if (NAME_RE.match(path.name) or VIDEO_NAME_RE.match(path.name)) and path.name not in keep:
|
||||||
path.unlink(missing_ok=True)
|
path.unlink(missing_ok=True)
|
||||||
removed += 1
|
removed += 1
|
||||||
return removed
|
return removed
|
||||||
|
|||||||
+33
-3
@@ -58,6 +58,34 @@ class Response:
|
|||||||
opted_out: bool = False # set by the client from silo-specific signals
|
opted_out: bool = False # set by the client from silo-specific signals
|
||||||
content_html: Optional[str] = None
|
content_html: Optional[str] = None
|
||||||
published: Optional[str] = None
|
published: Optional[str] = None
|
||||||
|
# Replies in a thread (v2.20.2): the silo id of the response this one
|
||||||
|
# answers (None: our copy itself), and whether we wrote it
|
||||||
|
parent_id: Optional[str] = None
|
||||||
|
own: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
def thread_members(posts: List[dict], root: str) -> Dict[str, Optional[str]]:
|
||||||
|
"""
|
||||||
|
Which replies under one of our copies to keep, and what each answers
|
||||||
|
(v2.20.2). `posts` are {'id', 'parent', 'own'} for every reply in the
|
||||||
|
conversation, in any order. Kept: others' replies to our copy, and any
|
||||||
|
reply (ours too) to a kept reply. Our own replies to our copy are the
|
||||||
|
thread continuing, not responses. Returns {id: parent id or None}.
|
||||||
|
"""
|
||||||
|
kept: Dict[str, Optional[str]] = {}
|
||||||
|
pending = list(posts)
|
||||||
|
while True:
|
||||||
|
rest = []
|
||||||
|
for post in pending:
|
||||||
|
if post["parent"] == root and not post["own"]:
|
||||||
|
kept[post["id"]] = None
|
||||||
|
elif post["parent"] in kept and post["parent"] != post["id"]:
|
||||||
|
kept[post["id"]] = post["parent"]
|
||||||
|
else:
|
||||||
|
rest.append(post)
|
||||||
|
if len(rest) == len(pending):
|
||||||
|
return kept
|
||||||
|
pending = rest
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@@ -292,9 +320,9 @@ def store(db, note_id: int, target_url: str, origin: str, harvest: Harvest,
|
|||||||
INSERT INTO webmentions (
|
INSERT INTO webmentions (
|
||||||
source_url, target_url, target_note_id, mention_type, author_name, author_url,
|
source_url, target_url, target_note_id, mention_type, author_name, author_url,
|
||||||
author_photo, content_snippet, validation_status, moderation_status,
|
author_photo, content_snippet, validation_status, moderation_status,
|
||||||
validated_at, source_published, origin, remote_id, notified_at)
|
validated_at, source_published, origin, remote_id, notified_at, parent_remote_id)
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'valid', ?, CURRENT_TIMESTAMP, ?, ?, ?,
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'valid', ?, CURRENT_TIMESTAMP, ?, ?, ?,
|
||||||
CASE WHEN ? THEN CURRENT_TIMESTAMP END)
|
CASE WHEN ? THEN CURRENT_TIMESTAMP END, ?)
|
||||||
ON CONFLICT(source_url, target_url) DO UPDATE SET
|
ON CONFLICT(source_url, target_url) DO UPDATE SET
|
||||||
target_note_id = excluded.target_note_id,
|
target_note_id = excluded.target_note_id,
|
||||||
mention_type = excluded.mention_type,
|
mention_type = excluded.mention_type,
|
||||||
@@ -305,6 +333,7 @@ def store(db, note_id: int, target_url: str, origin: str, harvest: Harvest,
|
|||||||
source_published = COALESCE(excluded.source_published, webmentions.source_published),
|
source_published = COALESCE(excluded.source_published, webmentions.source_published),
|
||||||
origin = excluded.origin,
|
origin = excluded.origin,
|
||||||
remote_id = excluded.remote_id,
|
remote_id = excluded.remote_id,
|
||||||
|
parent_remote_id = excluded.parent_remote_id,
|
||||||
validation_status = 'valid',
|
validation_status = 'valid',
|
||||||
validation_error = NULL,
|
validation_error = NULL,
|
||||||
validated_at = CURRENT_TIMESTAMP,
|
validated_at = CURRENT_TIMESTAMP,
|
||||||
@@ -312,7 +341,8 @@ def store(db, note_id: int, target_url: str, origin: str, harvest: Harvest,
|
|||||||
""",
|
""",
|
||||||
(r.source_url, target_url, note_id, r.kind, r.author_name or None, r.author_url or None,
|
(r.source_url, target_url, note_id, r.kind, r.author_name or None, r.author_url or None,
|
||||||
r.author_photo or None, snippet, moderation, r.published, origin, r.remote_id,
|
r.author_photo or None, snippet, moderation, r.published, origin, r.remote_id,
|
||||||
1 if quiet else 0),
|
# Our own replies in a thread are no news to us
|
||||||
|
1 if quiet or r.own else 0, r.parent_id),
|
||||||
)
|
)
|
||||||
if dropped:
|
if dropped:
|
||||||
marks = ",".join("?" * len(dropped))
|
marks = ",".join("?" * len(dropped))
|
||||||
|
|||||||
+26
-12
@@ -519,6 +519,30 @@ def get_note(
|
|||||||
return note
|
return note
|
||||||
|
|
||||||
|
|
||||||
|
def _list_filters(published_only: bool, likes: Optional[bool]) -> tuple[str, list]:
|
||||||
|
"""WHERE clause shared by list_notes() and count_notes()"""
|
||||||
|
where = "deleted_at IS NULL"
|
||||||
|
if published_only:
|
||||||
|
where += " AND published = 1"
|
||||||
|
# likes: None = all notes, False = leave likes out, True = only likes (v2.5.0)
|
||||||
|
if likes is True:
|
||||||
|
where += " AND like_of IS NOT NULL"
|
||||||
|
elif likes is False:
|
||||||
|
where += " AND like_of IS NULL"
|
||||||
|
return where, []
|
||||||
|
|
||||||
|
|
||||||
|
def count_notes(published_only: bool = False, likes: Optional[bool] = None) -> int:
|
||||||
|
"""
|
||||||
|
Number of notes list_notes() would return with no limit (v2.21.0)
|
||||||
|
|
||||||
|
Same filters as list_notes(); used to work out page counts.
|
||||||
|
"""
|
||||||
|
where, params = _list_filters(published_only, likes)
|
||||||
|
db = get_db(current_app)
|
||||||
|
return db.execute(f"SELECT COUNT(*) FROM notes WHERE {where}", params).fetchone()[0]
|
||||||
|
|
||||||
|
|
||||||
def list_notes(
|
def list_notes(
|
||||||
published_only: bool = False,
|
published_only: bool = False,
|
||||||
limit: int = 50,
|
limit: int = 50,
|
||||||
@@ -611,18 +635,8 @@ def list_notes(
|
|||||||
raise ValueError("Offset must be >= 0")
|
raise ValueError("Offset must be >= 0")
|
||||||
|
|
||||||
# 2. BUILD QUERY
|
# 2. BUILD QUERY
|
||||||
# Start with base query
|
where, params = _list_filters(published_only, likes)
|
||||||
query = "SELECT * FROM notes WHERE deleted_at IS NULL"
|
query = f"SELECT * FROM notes WHERE {where}"
|
||||||
|
|
||||||
# Add filters
|
|
||||||
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)
|
# Add ordering (safe because order_by validated above)
|
||||||
query += f" ORDER BY {order_by} {order_dir}"
|
query += f" ORDER BY {order_by} {order_dir}"
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ FEDIVERSE_PATH_RE = re.compile(
|
|||||||
FEDI_TITLE_RE = re.compile(r"^(.*?)\s*\((@[^)\s]+)\)\s*$")
|
FEDI_TITLE_RE = re.compile(r"^(.*?)\s*\((@[^)\s]+)\)\s*$")
|
||||||
|
|
||||||
FIELDS = ('title', 'content_snippet', 'published_at', 'author_name', 'author_handle',
|
FIELDS = ('title', 'content_snippet', 'published_at', 'author_name', 'author_handle',
|
||||||
'author_url', 'author_photo', 'site_name', 'photo', 'photo_alt')
|
'author_url', 'author_photo', 'site_name', 'photo', 'photo_alt', 'video')
|
||||||
|
|
||||||
|
|
||||||
def fetch_reply_context(
|
def fetch_reply_context(
|
||||||
@@ -300,11 +300,14 @@ def _from_status(status: dict, url: str) -> Dict[str, Any]:
|
|||||||
snippet = _text_snippet(f"CW: {spoiler}")
|
snippet = _text_snippet(f"CW: {spoiler}")
|
||||||
else:
|
else:
|
||||||
snippet = _snippet(status.get('content') or '') or None
|
snippet = _snippet(status.get('content') or '') or None
|
||||||
photo = photo_alt = None
|
photo = photo_alt = video = None
|
||||||
if not status.get('sensitive'):
|
if not status.get('sensitive'):
|
||||||
for media in status.get('media_attachments') or []:
|
for media in status.get('media_attachments') or []:
|
||||||
if media.get('type') in ('image', 'gifv', 'video') and _is_http_url(media.get('preview_url')):
|
if media.get('type') in ('image', 'gifv', 'video') and _is_http_url(media.get('preview_url')):
|
||||||
photo, photo_alt = media['preview_url'], media.get('description') or None
|
photo, photo_alt = media['preview_url'], media.get('description') or None
|
||||||
|
# A "GIF" on Mastodon is a silent looping MP4; the preview is its first frame
|
||||||
|
if media['type'] == 'gifv' and _is_http_url(media.get('url')):
|
||||||
|
video = media['url']
|
||||||
break
|
break
|
||||||
avatar = account.get('avatar_static') or account.get('avatar')
|
avatar = account.get('avatar_static') or account.get('avatar')
|
||||||
return {
|
return {
|
||||||
@@ -319,6 +322,7 @@ def _from_status(status: dict, url: str) -> Dict[str, Any]:
|
|||||||
'site_name': urlparse(url).hostname,
|
'site_name': urlparse(url).hostname,
|
||||||
'photo': photo,
|
'photo': photo,
|
||||||
'photo_alt': photo_alt,
|
'photo_alt': photo_alt,
|
||||||
|
'video': video,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -482,6 +486,7 @@ def _save_images(context: Dict[str, Any], site_url: str) -> None:
|
|||||||
data_path = current_app.config['DATA_PATH']
|
data_path = current_app.config['DATA_PATH']
|
||||||
avatars.fetch(data_path, context.get('author_photo'), site_url)
|
avatars.fetch(data_path, context.get('author_photo'), site_url)
|
||||||
avatars.fetch_preview(data_path, context.get('photo'), site_url)
|
avatars.fetch_preview(data_path, context.get('photo'), site_url)
|
||||||
|
avatars.fetch_video(data_path, context.get('video'), site_url)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.info(f"Could not save reply context images: {e}")
|
logger.info(f"Could not save reply context images: {e}")
|
||||||
|
|
||||||
|
|||||||
+10
-12
@@ -14,6 +14,7 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
from starpunk.auth import require_auth
|
from starpunk.auth import require_auth
|
||||||
from starpunk.notes import (
|
from starpunk.notes import (
|
||||||
|
count_notes,
|
||||||
create_note,
|
create_note,
|
||||||
delete_note,
|
delete_note,
|
||||||
list_notes,
|
list_notes,
|
||||||
@@ -60,21 +61,18 @@ def dashboard():
|
|||||||
from flask import current_app
|
from flask import current_app
|
||||||
import math
|
import math
|
||||||
|
|
||||||
# Get pagination params (v1.6.0)
|
# Pagination (v1.6.0). Until v2.21.0 this paged list_notes()'s default
|
||||||
page = int(request.args.get('page', 1))
|
# 50 newest notes, so older notes never showed; now it counts all notes
|
||||||
|
# and fetches only the requested page. A bad ?page= falls back to the
|
||||||
|
# nearest valid page instead of a server error.
|
||||||
per_page = 25
|
per_page = 25
|
||||||
|
total_notes = count_notes()
|
||||||
# Get all notes (published and drafts)
|
|
||||||
all_notes = list_notes()
|
|
||||||
|
|
||||||
# Calculate pagination
|
|
||||||
total_notes = len(all_notes)
|
|
||||||
total_pages = math.ceil(total_notes / per_page) if total_notes > 0 else 1
|
total_pages = math.ceil(total_notes / per_page) if total_notes > 0 else 1
|
||||||
|
raw_page = request.args.get('page', '1')
|
||||||
|
page = int(raw_page) if raw_page.isdigit() else 1
|
||||||
|
page = min(max(page, 1), total_pages)
|
||||||
|
|
||||||
# Slice for current page
|
notes = list_notes(limit=per_page, offset=(page - 1) * per_page)
|
||||||
start_idx = (page - 1) * per_page
|
|
||||||
end_idx = start_idx + per_page
|
|
||||||
notes = all_notes[start_idx:end_idx]
|
|
||||||
|
|
||||||
# Get pending webmention count (v1.6.0)
|
# Get pending webmention count (v1.6.0)
|
||||||
webmention_pending_count = 0
|
webmention_pending_count = 0
|
||||||
|
|||||||
+64
-38
@@ -10,7 +10,7 @@ from datetime import datetime, timedelta, timezone
|
|||||||
|
|
||||||
from flask import Blueprint, abort, redirect, render_template, Response, current_app, request, send_from_directory, url_for
|
from flask import Blueprint, abort, redirect, render_template, Response, current_app, request, send_from_directory, url_for
|
||||||
|
|
||||||
from starpunk.notes import list_notes, get_note
|
from starpunk.notes import count_notes, list_notes, get_note
|
||||||
from starpunk.websub import embed_hub
|
from starpunk.websub import embed_hub
|
||||||
from starpunk.feed import generate_feed_streaming # Legacy RSS
|
from starpunk.feed import generate_feed_streaming # Legacy RSS
|
||||||
from starpunk.feeds import (
|
from starpunk.feeds import (
|
||||||
@@ -268,46 +268,76 @@ def avatar(name: str):
|
|||||||
def preview(name: str):
|
def preview(name: str):
|
||||||
"""A saved copy of a replied-to post's image (v2.19.0)"""
|
"""A saved copy of a replied-to post's image (v2.19.0)"""
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from starpunk.avatars import NAME_RE, preview_folder
|
from starpunk.avatars import NAME_RE, VIDEO_NAME_RE, preview_folder
|
||||||
|
|
||||||
if not NAME_RE.match(name):
|
if not (NAME_RE.match(name) or VIDEO_NAME_RE.match(name)):
|
||||||
abort(404)
|
abort(404)
|
||||||
response = send_from_directory(
|
response = send_from_directory(
|
||||||
preview_folder(Path(current_app.config.get('DATA_PATH', 'data'))), name)
|
preview_folder(Path(current_app.config.get('DATA_PATH', 'data'))), name,
|
||||||
|
mimetype='video/mp4' if name.endswith('.mp4') else None)
|
||||||
response.headers['Cache-Control'] = 'public, max-age=604800'
|
response.headers['Cache-Control'] = 'public, max-age=604800'
|
||||||
return response
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
HOME_PER_PAGE = 20
|
||||||
|
LIKES_PER_PAGE = 50
|
||||||
|
|
||||||
|
|
||||||
|
def _paged_notes(endpoint: str, per_page: int, likes: bool):
|
||||||
|
"""
|
||||||
|
Published notes for the requested ?page= of a public list (v2.21.0)
|
||||||
|
|
||||||
|
Returns (notes, page, total_pages), or a redirect Response for ?page=1
|
||||||
|
(page 1 lives at the bare URL). A page that isn't a positive whole
|
||||||
|
number, or is past the last page, is a 404.
|
||||||
|
"""
|
||||||
|
raw = request.args.get("page")
|
||||||
|
if raw is None:
|
||||||
|
page = 1
|
||||||
|
elif not raw.isdigit() or int(raw) < 1:
|
||||||
|
abort(404)
|
||||||
|
else:
|
||||||
|
page = int(raw)
|
||||||
|
if page == 1:
|
||||||
|
return redirect(url_for(endpoint), code=301)
|
||||||
|
total = count_notes(published_only=True, likes=likes)
|
||||||
|
total_pages = max(1, -(-total // per_page))
|
||||||
|
if page > total_pages:
|
||||||
|
abort(404)
|
||||||
|
notes = list_notes(published_only=True, limit=per_page,
|
||||||
|
offset=(page - 1) * per_page, likes=likes)
|
||||||
|
return notes, page, total_pages
|
||||||
|
|
||||||
|
|
||||||
|
def _prepare_for_listing(notes) -> None:
|
||||||
|
"""Media, tags, contexts and response counts for listed notes"""
|
||||||
|
from starpunk.media import get_note_media
|
||||||
|
from starpunk.tags import get_note_tags
|
||||||
|
|
||||||
|
for note in notes:
|
||||||
|
# Use object.__setattr__ since Note is frozen dataclass
|
||||||
|
object.__setattr__(note, 'media', get_note_media(note.id))
|
||||||
|
object.__setattr__(note, '_cached_tags', get_note_tags(note.id))
|
||||||
|
attach_contexts(notes)
|
||||||
|
attach_response_counts(notes)
|
||||||
|
|
||||||
|
|
||||||
@bp.route("/")
|
@bp.route("/")
|
||||||
def index():
|
def index():
|
||||||
"""
|
"""
|
||||||
Homepage displaying recent published notes with media
|
Homepage: published notes, newest first, 20 per page (paged in v2.21.0)
|
||||||
|
|
||||||
Returns:
|
Likes have their own page (v2.5.0). Older notes are at /?page=2 and on.
|
||||||
Rendered homepage template with note list including media
|
|
||||||
|
|
||||||
Template: templates/index.html
|
Template: templates/index.html
|
||||||
Microformats: h-feed containing h-entry items with u-photo
|
Microformats: h-feed containing h-entry items, with rel=prev/next paging
|
||||||
"""
|
"""
|
||||||
from starpunk.media import get_note_media
|
result = _paged_notes("public.index", HOME_PER_PAGE, likes=False)
|
||||||
from starpunk.tags import get_note_tags
|
if not isinstance(result, tuple): # redirect for ?page=1
|
||||||
|
return result
|
||||||
# Get recent published notes (limit 20); likes have their own page (v2.5.0)
|
notes, page, total_pages = result
|
||||||
notes = list_notes(published_only=True, limit=20, likes=False)
|
_prepare_for_listing(notes)
|
||||||
|
return render_template("index.html", notes=notes, page=page, total_pages=total_pages)
|
||||||
# Attach media and tags to each note for display
|
|
||||||
for note in notes:
|
|
||||||
media = get_note_media(note.id)
|
|
||||||
# Use object.__setattr__ since Note is frozen dataclass
|
|
||||||
object.__setattr__(note, 'media', media)
|
|
||||||
|
|
||||||
# Attach tags (v1.3.0 Phase 3)
|
|
||||||
tags = get_note_tags(note.id)
|
|
||||||
object.__setattr__(note, '_cached_tags', tags)
|
|
||||||
|
|
||||||
attach_contexts(notes)
|
|
||||||
attach_response_counts(notes)
|
|
||||||
return render_template("index.html", notes=notes)
|
|
||||||
|
|
||||||
|
|
||||||
def attach_response_counts(notes) -> None:
|
def attach_response_counts(notes) -> None:
|
||||||
@@ -340,17 +370,13 @@ def attach_contexts(notes) -> None:
|
|||||||
|
|
||||||
@bp.route("/likes")
|
@bp.route("/likes")
|
||||||
def likes():
|
def likes():
|
||||||
"""Likes, kept off the home page and feeds (v2.5.0)"""
|
"""Likes, kept off the home page and feeds (v2.5.0); paged in v2.21.0"""
|
||||||
from starpunk.media import get_note_media
|
result = _paged_notes("public.likes", LIKES_PER_PAGE, likes=True)
|
||||||
from starpunk.tags import get_note_tags
|
if not isinstance(result, tuple): # redirect for ?page=1
|
||||||
|
return result
|
||||||
notes = list_notes(published_only=True, limit=50, likes=True)
|
notes, page, total_pages = result
|
||||||
for note in notes:
|
_prepare_for_listing(notes)
|
||||||
object.__setattr__(note, 'media', get_note_media(note.id))
|
return render_template("likes.html", notes=notes, page=page, total_pages=total_pages)
|
||||||
object.__setattr__(note, '_cached_tags', get_note_tags(note.id))
|
|
||||||
attach_contexts(notes)
|
|
||||||
attach_response_counts(notes)
|
|
||||||
return render_template("likes.html", notes=notes)
|
|
||||||
|
|
||||||
|
|
||||||
def _note_was_deleted(slug: str) -> bool:
|
def _note_was_deleted(slug: str) -> bool:
|
||||||
|
|||||||
+53
-24
@@ -240,8 +240,9 @@ class MastodonClient:
|
|||||||
}
|
}
|
||||||
|
|
||||||
def responses(self, remote_id: str, remote_url: str, cap: int = 1000):
|
def responses(self, remote_id: str, remote_url: str, cap: int = 1000):
|
||||||
"""Likes, boosts and public direct replies of one of our statuses"""
|
"""Likes, boosts and public replies of one of our statuses, with the
|
||||||
from starpunk.backfeed import Harvest, Response
|
replies to those replies (v2.20.2)"""
|
||||||
|
from starpunk.backfeed import Harvest, Response, thread_members
|
||||||
|
|
||||||
me = self._account_id()
|
me = self._account_id()
|
||||||
found, complete = [], True
|
found, complete = [], True
|
||||||
@@ -255,14 +256,18 @@ class MastodonClient:
|
|||||||
found.append(Response(kind=kind, source_url=f"{remote_url}#{fragment}-{account['id']}",
|
found.append(Response(kind=kind, source_url=f"{remote_url}#{fragment}-{account['id']}",
|
||||||
remote_id=account["id"], **self._author(account)))
|
remote_id=account["id"], **self._author(account)))
|
||||||
context = self._call("GET", f"/api/v1/statuses/{remote_id}/context").json() or {}
|
context = self._call("GET", f"/api/v1/statuses/{remote_id}/context").json() or {}
|
||||||
for status in context.get("descendants") or []:
|
public = [st for st in context.get("descendants") or [] if st.get("visibility") == "public"]
|
||||||
account = status.get("account") or {}
|
kept = thread_members([{"id": st["id"], "parent": st.get("in_reply_to_id"),
|
||||||
if (status.get("in_reply_to_id") != remote_id or status.get("visibility") != "public"
|
"own": (st.get("account") or {}).get("id") == me} for st in public],
|
||||||
or account.get("id") == me):
|
remote_id)
|
||||||
|
for status in public:
|
||||||
|
if status["id"] not in kept:
|
||||||
continue
|
continue
|
||||||
|
account = status.get("account") or {}
|
||||||
found.append(Response(kind="reply", source_url=status.get("url") or status["uri"],
|
found.append(Response(kind="reply", source_url=status.get("url") or status["uri"],
|
||||||
remote_id=status["id"], content_html=status.get("content") or "",
|
remote_id=status["id"], content_html=status.get("content") or "",
|
||||||
published=status.get("created_at"), **self._author(account)))
|
published=status.get("created_at"), parent_id=kept[status["id"]],
|
||||||
|
own=account.get("id") == me, **self._author(account)))
|
||||||
return Harvest(found, complete)
|
return Harvest(found, complete)
|
||||||
|
|
||||||
def delete(self, remote_id: str) -> None:
|
def delete(self, remote_id: str) -> None:
|
||||||
@@ -277,6 +282,7 @@ class MastodonClient:
|
|||||||
|
|
||||||
|
|
||||||
BLUESKY_BLOB_LIMIT = 1_000_000 # app.bsky.embed.images maxSize
|
BLUESKY_BLOB_LIMIT = 1_000_000 # app.bsky.embed.images maxSize
|
||||||
|
BLUESKY_THREAD_DEPTH = 10 # how deep backfeed follows replies to replies
|
||||||
_TID_CHARS = "234567abcdefghijklmnopqrstuvwxyz"
|
_TID_CHARS = "234567abcdefghijklmnopqrstuvwxyz"
|
||||||
|
|
||||||
|
|
||||||
@@ -588,8 +594,9 @@ class BlueskyClient:
|
|||||||
)
|
)
|
||||||
|
|
||||||
def responses(self, remote_id: str, remote_url: str, cap: int = 1000):
|
def responses(self, remote_id: str, remote_url: str, cap: int = 1000):
|
||||||
"""Likes, reposts, quotes and direct replies of one of our posts"""
|
"""Likes, reposts, quotes and replies of one of our posts, with the
|
||||||
from starpunk.backfeed import Harvest, Response
|
replies to those replies (v2.20.2)"""
|
||||||
|
from starpunk.backfeed import Harvest, Response, thread_members
|
||||||
|
|
||||||
if not self.did:
|
if not self.did:
|
||||||
with self._lock:
|
with self._lock:
|
||||||
@@ -612,10 +619,26 @@ class BlueskyClient:
|
|||||||
complete = complete and done
|
complete = complete and done
|
||||||
posts = [self._post_response("quote", view) for view in quotes]
|
posts = [self._post_response("quote", view) for view in quotes]
|
||||||
thread = self._call("GET", "app.bsky.feed.getPostThread",
|
thread = self._call("GET", "app.bsky.feed.getPostThread",
|
||||||
params={"uri": remote_id, "depth": 1, "parentHeight": 0}).json()
|
params={"uri": remote_id, "depth": BLUESKY_THREAD_DEPTH,
|
||||||
for item in (thread.get("thread") or {}).get("replies") or []:
|
"parentHeight": 0}).json()
|
||||||
if item.get("post"): # skips blocked and deleted replies
|
# The whole conversation under our post (v2.20.2)
|
||||||
posts.append(self._post_response("reply", item["post"]))
|
views, stack = {}, [(remote_id, item) for item in (thread.get("thread") or {}).get("replies") or []]
|
||||||
|
while stack:
|
||||||
|
parent, item = stack.pop()
|
||||||
|
post = item.get("post")
|
||||||
|
if not post: # blocked or deleted: its replies go with it
|
||||||
|
continue
|
||||||
|
views[post["uri"]] = (parent, post)
|
||||||
|
stack.extend((post["uri"], child) for child in item.get("replies") or [])
|
||||||
|
kept = thread_members([{"id": uri, "parent": parent,
|
||||||
|
"own": (post.get("author") or {}).get("did") == self.did}
|
||||||
|
for uri, (parent, post) in views.items()], remote_id)
|
||||||
|
for uri, (_, post) in sorted(views.items(), key=lambda v: v[1][1].get("indexedAt") or ""):
|
||||||
|
if uri in kept:
|
||||||
|
response = self._post_response("reply", post)
|
||||||
|
response.parent_id = kept[uri]
|
||||||
|
response.own = response.author_id == self.did
|
||||||
|
posts.append(response)
|
||||||
# Post views carry no bio; fetch them to honour #nobridge
|
# Post views carry no bio; fetch them to honour #nobridge
|
||||||
dids = list({p.author_id for p in posts if p.author_id})
|
dids = list({p.author_id for p in posts if p.author_id})
|
||||||
bios = {}
|
bios = {}
|
||||||
@@ -626,7 +649,7 @@ class BlueskyClient:
|
|||||||
for post in posts:
|
for post in posts:
|
||||||
post.author_bio = bios.get(post.author_id, "")
|
post.author_bio = bios.get(post.author_id, "")
|
||||||
found.extend(posts)
|
found.extend(posts)
|
||||||
return Harvest([r for r in found if r.author_id != self.did], complete)
|
return Harvest([r for r in found if r.author_id != self.did or r.own], complete)
|
||||||
|
|
||||||
def delete(self, remote_id: str) -> None:
|
def delete(self, remote_id: str) -> None:
|
||||||
# at://<did>/app.bsky.feed.post/<rkey>; deleting a missing record succeeds
|
# at://<did>/app.bsky.feed.post/<rkey>; deleting a missing record succeeds
|
||||||
@@ -1013,15 +1036,17 @@ class ThreadsClient:
|
|||||||
|
|
||||||
# --- Backfeed (v2.13.0, ADR-073) ---
|
# --- Backfeed (v2.13.0, ADR-073) ---
|
||||||
|
|
||||||
REPLY_FIELDS = "id,text,username,permalink,timestamp,profile_picture_url,hide_status"
|
REPLY_FIELDS = "id,text,username,permalink,timestamp,profile_picture_url,hide_status,replied_to"
|
||||||
SHOWN = (None, "NOT_HUSHED", "UNHUSHED") # hide_status values of replies nobody hid
|
SHOWN = (None, "NOT_HUSHED", "UNHUSHED") # hide_status values of replies nobody hid
|
||||||
|
|
||||||
def responses(self, remote_id: str, remote_url: str, cap: int = 1000):
|
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.
|
Replies to one of our posts, with the replies to those replies
|
||||||
The API doesn't say who liked, reposted or quoted (ADR-073 Decision 7).
|
(/conversation, v2.20.2; /replies only has the first level), 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
|
from starpunk.backfeed import Harvest, Response, text_html, thread_members
|
||||||
|
|
||||||
self._me()
|
self._me()
|
||||||
replies, after, complete = [], None, True
|
replies, after, complete = [], None, True
|
||||||
@@ -1029,7 +1054,7 @@ class ThreadsClient:
|
|||||||
params = {"fields": self.REPLY_FIELDS}
|
params = {"fields": self.REPLY_FIELDS}
|
||||||
if after:
|
if after:
|
||||||
params["after"] = after
|
params["after"] = after
|
||||||
data = self._call("GET", f"{remote_id}/replies", **params)
|
data = self._call("GET", f"{remote_id}/conversation", **params)
|
||||||
page = data.get("data") or []
|
page = data.get("data") or []
|
||||||
replies.extend(page)
|
replies.extend(page)
|
||||||
if len(replies) >= cap:
|
if len(replies) >= cap:
|
||||||
@@ -1039,14 +1064,18 @@ class ThreadsClient:
|
|||||||
after = (paging.get("cursors") or {}).get("after")
|
after = (paging.get("cursors") or {}).get("after")
|
||||||
if not page or not after or not paging.get("next"):
|
if not page or not after or not paging.get("next"):
|
||||||
break
|
break
|
||||||
found = []
|
|
||||||
for reply in replies:
|
|
||||||
username = reply.get("username")
|
|
||||||
# Private accounts have no username or permalink: nothing public to show
|
# Private accounts have no username or permalink: nothing public to show
|
||||||
if (not username or not reply.get("permalink") or username == self.username
|
shown = [r for r in replies if r.get("username") and r.get("permalink")
|
||||||
or reply.get("hide_status") not in self.SHOWN):
|
and r.get("hide_status") in self.SHOWN]
|
||||||
|
kept = thread_members([{"id": r["id"], "parent": (r.get("replied_to") or {}).get("id"),
|
||||||
|
"own": r["username"] == self.username} for r in shown], remote_id)
|
||||||
|
found = []
|
||||||
|
for reply in sorted(shown, key=lambda r: r.get("timestamp") or ""):
|
||||||
|
if reply["id"] not in kept:
|
||||||
continue
|
continue
|
||||||
|
username = reply["username"]
|
||||||
found.append(Response(
|
found.append(Response(
|
||||||
|
parent_id=kept[reply["id"]], own=username == self.username,
|
||||||
kind="reply", source_url=reply["permalink"], remote_id=reply["id"],
|
kind="reply", source_url=reply["permalink"], remote_id=reply["id"],
|
||||||
author_id=username, author_name=username,
|
author_id=username, author_name=username,
|
||||||
author_url=f"https://www.threads.com/@{username}",
|
author_url=f"https://www.threads.com/@{username}",
|
||||||
|
|||||||
@@ -107,9 +107,32 @@ def get_webmentions_for_note(note_id: int) -> Dict[str, List[Dict[str, Any]]]:
|
|||||||
else:
|
else:
|
||||||
grouped['mentions'].append(wm)
|
grouped['mentions'].append(wm)
|
||||||
|
|
||||||
|
grouped['reply_threads'] = reply_threads(grouped['replies'])
|
||||||
return grouped
|
return grouped
|
||||||
|
|
||||||
|
|
||||||
|
def reply_threads(replies: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
Replies nested under the replies they answer (v2.20.2): each gets
|
||||||
|
'children'; the top-level ones are returned. A reply whose parent isn't
|
||||||
|
shown (hidden, removed) is shown at the top level.
|
||||||
|
"""
|
||||||
|
by_id = {}
|
||||||
|
for wm in replies:
|
||||||
|
wm['children'] = []
|
||||||
|
if wm.get('remote_id'):
|
||||||
|
by_id[(wm.get('origin'), wm['remote_id'])] = wm
|
||||||
|
top = []
|
||||||
|
for wm in replies:
|
||||||
|
parent = by_id.get((wm.get('origin'), wm.get('parent_remote_id'))) \
|
||||||
|
if wm.get('parent_remote_id') else None
|
||||||
|
if parent is not None and parent is not wm:
|
||||||
|
parent['children'].append(wm)
|
||||||
|
else:
|
||||||
|
top.append(wm)
|
||||||
|
return top
|
||||||
|
|
||||||
|
|
||||||
def response_counts(note_ids: List[int]) -> Dict[int, Dict[str, int]]:
|
def response_counts(note_ids: List[int]) -> Dict[int, Dict[str, int]]:
|
||||||
"""
|
"""
|
||||||
Likes, reposts, replies and quotes per note, for lists of notes
|
Likes, reposts, replies and quotes per note, for lists of notes
|
||||||
|
|||||||
@@ -89,6 +89,10 @@ main { flex: 1; margin-bottom: var(--spacing-xl); }
|
|||||||
.h-entry > .p-name a:hover { color: var(--color-link); }
|
.h-entry > .p-name a:hover { color: var(--color-link); }
|
||||||
.e-content, .p-summary { font-family: var(--font-reading); font-size: 1.125rem; line-height: 1.65; overflow-wrap: anywhere; }
|
.e-content, .p-summary { font-family: var(--font-reading); font-size: 1.125rem; line-height: 1.65; overflow-wrap: anywhere; }
|
||||||
.e-content > :last-child, .p-summary > :last-child { margin-bottom: 0; }
|
.e-content > :last-child, .p-summary > :last-child { margin-bottom: 0; }
|
||||||
|
/* Article summary (v2.20.3): a subtitle under the title, not a first paragraph.
|
||||||
|
The homepage teaser keeps the reading style above, where it stands in for the body. */
|
||||||
|
.p-summary.dek { font-family: var(--font-body); font-size: 1.25rem; line-height: 1.45; color: var(--color-text-light);
|
||||||
|
margin: calc(-1 * var(--spacing-sm)) 0 var(--spacing-lg); padding-bottom: var(--spacing-md); border-bottom: 1px solid var(--color-border); }
|
||||||
.e-content a { text-decoration: underline; text-decoration-thickness: 1px; text-underline-offset: 2px; text-decoration-color: color-mix(in srgb, currentColor 40%, transparent); }
|
.e-content a { text-decoration: underline; text-decoration-thickness: 1px; text-underline-offset: 2px; text-decoration-color: color-mix(in srgb, currentColor 40%, transparent); }
|
||||||
.e-content a:hover { text-decoration-color: currentColor; }
|
.e-content a:hover { text-decoration-color: currentColor; }
|
||||||
.e-content blockquote { margin: 0 0 var(--spacing-md); padding-left: var(--spacing-md); border-left: 3px solid var(--color-border); color: var(--color-text-light); }
|
.e-content blockquote { margin: 0 0 var(--spacing-md); padding-left: var(--spacing-md); border-left: 3px solid var(--color-border); color: var(--color-text-light); }
|
||||||
@@ -126,6 +130,10 @@ main { flex: 1; margin-bottom: var(--spacing-xl); }
|
|||||||
.note-tags .p-category::before { content: "#"; opacity: 0.7; }
|
.note-tags .p-category::before { content: "#"; opacity: 0.7; }
|
||||||
.h-entry:not(.note-preview) .note-meta { margin-top: var(--spacing-md); }
|
.h-entry:not(.note-preview) .note-meta { margin-top: var(--spacing-md); }
|
||||||
.note-nav { margin-top: var(--spacing-lg); font-size: 0.9375rem; }
|
.note-nav { margin-top: var(--spacing-lg); font-size: 0.9375rem; }
|
||||||
|
.pager { display: flex; justify-content: space-between; align-items: center; gap: var(--spacing-md); margin-top: var(--spacing-lg); font-size: 0.9375rem; }
|
||||||
|
.pager-position { color: var(--color-text-light); margin: 0 auto; }
|
||||||
|
.pager [rel="next"] { margin-left: auto; }
|
||||||
|
.pager [rel="prev"] + .pager-position { margin-left: auto; }
|
||||||
.empty-state { text-align: center; padding: var(--spacing-xl); color: var(--color-text-light); }
|
.empty-state { text-align: center; padding: var(--spacing-xl); color: var(--color-text-light); }
|
||||||
|
|
||||||
.form-group { margin-bottom: var(--spacing-md); }
|
.form-group { margin-bottom: var(--spacing-md); }
|
||||||
@@ -391,6 +399,10 @@ small { display: block; margin-top: var(--spacing-xs); color: var(--color-text-l
|
|||||||
.webmention-reply .webmention-date::after { content: ""; position: absolute; inset: 0; }
|
.webmention-reply .webmention-date::after { content: ""; position: absolute; inset: 0; }
|
||||||
.webmention-reply .webmention-author a, .webmention-reply .e-content a { position: relative; z-index: 1; }
|
.webmention-reply .webmention-author a, .webmention-reply .e-content a { position: relative; z-index: 1; }
|
||||||
.webmention-reply:hover { cursor: pointer; }
|
.webmention-reply:hover { cursor: pointer; }
|
||||||
|
/* Replies to replies (v2.20.2): nested, with a line down the side */
|
||||||
|
.webmention-thread { position: relative; z-index: 1; margin-top: var(--spacing-sm); padding-left: var(--spacing-md); border-left: 2px solid var(--color-border); }
|
||||||
|
.webmention-thread .webmention-reply { margin-bottom: var(--spacing-sm); padding: var(--spacing-xs) 0 var(--spacing-xs) var(--spacing-xs); background: none; }
|
||||||
|
.webmention-thread .webmention-reply:last-child { margin-bottom: 0; }
|
||||||
|
|
||||||
/* Counts in lists of notes (v2.13.4) */
|
/* Counts in lists of notes (v2.13.4) */
|
||||||
.list-counts { display: inline-flex; gap: 0.6rem; color: var(--color-text-light); }
|
.list-counts { display: inline-flex; gap: 0.6rem; color: var(--color-text-light); }
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
{% extends "base.html" %}
|
{% extends "base.html" %}
|
||||||
{% from "partials/note_preview.html" import note_preview %}
|
{% from "partials/note_preview.html" import note_preview %}
|
||||||
|
{% from "partials/pager.html" import pager %}
|
||||||
|
|
||||||
{% block title %}{{ config.SITE_NAME }}{% endblock %}
|
{% block title %}{% if page and page > 1 %}Page {{ page }} · {% endif %}{{ config.SITE_NAME }}{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<div class="h-feed">
|
<div class="h-feed">
|
||||||
@@ -39,5 +40,7 @@
|
|||||||
{% else %}
|
{% else %}
|
||||||
<p class="empty-state">No notes published yet. Check back soon!</p>
|
<p class="empty-state">No notes published yet. Check back soon!</p>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
|
{{ pager('public.index', page, total_pages) }}
|
||||||
</div>
|
</div>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
{% extends "base.html" %}
|
{% extends "base.html" %}
|
||||||
{% from "partials/note_preview.html" import note_preview %}
|
{% from "partials/note_preview.html" import note_preview %}
|
||||||
|
{% from "partials/pager.html" import pager %}
|
||||||
|
|
||||||
{% block title %}Likes · {{ config.SITE_NAME }}{% endblock %}
|
{% block title %}Likes · {% if page and page > 1 %}Page {{ page }} · {% endif %}{{ config.SITE_NAME }}{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<div class="h-feed">
|
<div class="h-feed">
|
||||||
@@ -21,6 +22,8 @@
|
|||||||
<p class="empty-state">Nothing liked yet.</p>
|
<p class="empty-state">Nothing liked yet.</p>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
|
{{ pager('public.likes', page, total_pages) }}
|
||||||
|
|
||||||
<nav class="note-nav">
|
<nav class="note-nav">
|
||||||
<a href="/">← All notes</a>
|
<a href="/">← All notes</a>
|
||||||
</nav>
|
</nav>
|
||||||
|
|||||||
+2
-2
@@ -13,7 +13,7 @@
|
|||||||
<h1 class="p-name">{{ note.title }}</h1>
|
<h1 class="p-name">{{ note.title }}</h1>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% if note.summary %}
|
{% if note.summary %}
|
||||||
<p class="p-summary">{{ note.summary }}</p>
|
<p class="p-summary dek">{{ note.summary }}</p>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
{# Reply context (v1.6.0 Phase 4; card v2.19.0) - displayed if this is a reply post #}
|
{# Reply context (v1.6.0 Phase 4; card v2.19.0) - displayed if this is a reply post #}
|
||||||
@@ -74,7 +74,7 @@
|
|||||||
{% if replies %}
|
{% if replies %}
|
||||||
<div class="webmention-group webmention-replies">
|
<div class="webmention-group webmention-replies">
|
||||||
<h3>{{ replies|length }} {{ 'Reply' if replies|length == 1 else 'Replies' }}</h3>
|
<h3>{{ replies|length }} {{ 'Reply' if replies|length == 1 else 'Replies' }}</h3>
|
||||||
{% for wm in replies %}{{ responses.reply(wm) }}{% endfor %}
|
{% for wm in reply_threads or replies %}{{ responses.reply(wm) }}{% endfor %}
|
||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{# Newer/older links for paged public lists (v2.21.0). Page 1 is the bare
|
||||||
|
URL. rel=prev/next let IndieWeb readers page through the h-feed. #}
|
||||||
|
{% macro pager(endpoint, page, total_pages) %}
|
||||||
|
{% if total_pages > 1 %}
|
||||||
|
<nav class="pager" aria-label="More notes">
|
||||||
|
{% if page > 1 %}
|
||||||
|
<a rel="prev" href="{{ url_for(endpoint, page=page - 1) if page > 2 else url_for(endpoint) }}">← Newer</a>
|
||||||
|
{% endif %}
|
||||||
|
<span class="pager-position">Page {{ page }} of {{ total_pages }}</span>
|
||||||
|
{% if page < total_pages %}
|
||||||
|
<a rel="next" href="{{ url_for(endpoint, page=page + 1) }}">Older →</a>
|
||||||
|
{% endif %}
|
||||||
|
</nav>
|
||||||
|
{% endif %}
|
||||||
|
{% endmacro %}
|
||||||
@@ -34,7 +34,11 @@
|
|||||||
{% if ctx.title %}<p class="p-name reply-title">{{ ctx.title }}</p>{% endif %}
|
{% if ctx.title %}<p class="p-name reply-title">{{ ctx.title }}</p>{% endif %}
|
||||||
{% if ctx.content_snippet %}<div class="e-content reply-content">{{ ctx.content_snippet|safe }}</div>{% endif %}
|
{% if ctx.content_snippet %}<div class="e-content reply-content">{{ ctx.content_snippet|safe }}</div>{% endif %}
|
||||||
{% set image = ctx.photo|local_preview %}
|
{% set image = ctx.photo|local_preview %}
|
||||||
{% if image %}<img class="reply-photo" src="{{ image }}" alt="{{ ctx.photo_alt or '' }}" loading="lazy">{% endif %}
|
{% set video = ctx.video|local_video if ctx.video is defined else None %}
|
||||||
|
{% if video %}
|
||||||
|
{# Mastodon "GIFs" are silent looping MP4s: shown as Mastodon shows them (v2.20.1) #}
|
||||||
|
<video class="reply-photo" src="{{ video }}"{% if image %} poster="{{ image }}"{% endif %} autoplay loop muted playsinline{% if ctx.photo_alt %} aria-label="{{ ctx.photo_alt }}" title="{{ ctx.photo_alt }}"{% endif %}></video>
|
||||||
|
{% elif image %}<img class="reply-photo" src="{{ image }}" alt="{{ ctx.photo_alt or '' }}" loading="lazy">{% endif %}
|
||||||
<footer class="reply-source">
|
<footer class="reply-source">
|
||||||
<a class="u-url" href="{{ url }}">{{ _when(ctx, '%B %-d, %Y · %-I:%M %p') }}{% if ctx.published_at and ctx.published_at.strftime is defined %} · {% endif %}{{ ctx.site_name or url.split('/')[2] }} ↗</a>
|
<a class="u-url" href="{{ url }}">{{ _when(ctx, '%B %-d, %Y · %-I:%M %p') }}{% if ctx.published_at and ctx.published_at.strftime is defined %} · {% endif %}{{ ctx.site_name or url.split('/')[2] }} ↗</a>
|
||||||
</footer>
|
</footer>
|
||||||
|
|||||||
@@ -30,7 +30,8 @@
|
|||||||
</a></span>
|
</a></span>
|
||||||
{%- endmacro %}
|
{%- endmacro %}
|
||||||
|
|
||||||
{# A reply, shown as a comment #}
|
{# A reply, shown as a comment; replies to it are nested inside, as
|
||||||
|
comments of the comment (v2.20.2) #}
|
||||||
{% macro reply(wm) %}
|
{% macro reply(wm) %}
|
||||||
<article class="webmention webmention-reply u-comment h-cite">
|
<article class="webmention webmention-reply u-comment h-cite">
|
||||||
<div class="webmention-author">{{ author_card(wm) }}</div>
|
<div class="webmention-author">{{ author_card(wm) }}</div>
|
||||||
@@ -38,6 +39,11 @@
|
|||||||
<div class="e-content">{{ wm.content_snippet|safe }}</div>
|
<div class="e-content">{{ wm.content_snippet|safe }}</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
<a class="u-url webmention-date" href="{{ response_url(wm) }}">{{ response_time(wm) }}</a> {{ via(wm) }}
|
<a class="u-url webmention-date" href="{{ response_url(wm) }}">{{ response_time(wm) }}</a> {{ via(wm) }}
|
||||||
|
{% if wm.children %}
|
||||||
|
<div class="webmention-thread">
|
||||||
|
{% for child in wm.children %}{{ reply(child) }}{% endfor %}
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
</article>
|
</article>
|
||||||
{%- endmacro %}
|
{%- endmacro %}
|
||||||
|
|
||||||
|
|||||||
@@ -76,6 +76,11 @@ class TestPages:
|
|||||||
assert props["summary"] == ["The gist."]
|
assert props["summary"] == ["The gist."]
|
||||||
assert not props["content"][0]["value"].startswith("An Article")
|
assert not props["content"][0]["value"].startswith("An Article")
|
||||||
|
|
||||||
|
def test_summary_is_a_subtitle_only_on_the_article_page(self, app, client):
|
||||||
|
article, _ = make_both(app)
|
||||||
|
assert 'class="p-summary dek"' in client.get(f"/article/{article.slug}").data.decode()
|
||||||
|
assert "dek" not in client.get("/").data.decode()
|
||||||
|
|
||||||
def test_homepage_and_tag_page(self, app, client, h):
|
def test_homepage_and_tag_page(self, app, client, h):
|
||||||
photo = upload(client, h)
|
photo = upload(client, h)
|
||||||
url = micropub(client, h, name=["Trip"], content=["Day one of the trip."], photo=[photo],
|
url = micropub(client, h, name=["Trip"], content=["Day one of the trip."], photo=[photo],
|
||||||
|
|||||||
+107
-11
@@ -392,18 +392,25 @@ def mastodon_api(request):
|
|||||||
"account": who or account("r" + n)}
|
"account": who or account("r" + n)}
|
||||||
return httpx.Response(200, json={"ancestors": [], "descendants": [
|
return httpx.Response(200, json={"ancestors": [], "descendants": [
|
||||||
status("10"), status("11", vis="unlisted"), status("12", parent="10"),
|
status("10"), status("11", vis="unlisted"), status("12", parent="10"),
|
||||||
status("13", who=account("me"))]})
|
status("13", who=account("me")), status("14", parent="12", who=account("me")),
|
||||||
|
status("15", parent="13")]})
|
||||||
return httpx.Response(404)
|
return httpx.Response(404)
|
||||||
|
|
||||||
|
|
||||||
def test_mastodon_client_reads_likes_boosts_and_public_direct_replies():
|
def test_mastodon_client_reads_likes_boosts_and_public_reply_threads():
|
||||||
gts = MastodonClient(GTS, "t", http=httpx.Client(transport=httpx.MockTransport(mastodon_api)))
|
gts = MastodonClient(GTS, "t", http=httpx.Client(transport=httpx.MockTransport(mastodon_api)))
|
||||||
harvest = gts.responses("01COPY", COPY)
|
harvest = gts.responses("01COPY", COPY)
|
||||||
assert harvest.complete
|
assert harvest.complete
|
||||||
got = [(r.kind, r.source_url) for r in harvest.responses]
|
got = [(r.kind, r.source_url) for r in harvest.responses]
|
||||||
|
# 11 isn't public; 13 is our own thread continuing, so 15 under it is left out too.
|
||||||
|
# 12 answers 10, and our 14 answers 12 (v2.20.2)
|
||||||
assert got == [("like", f"{COPY}#liked-by-1"), ("like", f"{COPY}#liked-by-3"),
|
assert got == [("like", f"{COPY}#liked-by-1"), ("like", f"{COPY}#liked-by-3"),
|
||||||
("repost", f"{COPY}#reposted-by-2"), ("reply", f"{GTS}/@u/statuses/10")]
|
("repost", f"{COPY}#reposted-by-2"), ("reply", f"{GTS}/@u/statuses/10"),
|
||||||
assert harvest.responses[-1].content_html == "<p>reply 10</p>"
|
("reply", f"{GTS}/@u/statuses/12"), ("reply", f"{GTS}/@u/statuses/14")]
|
||||||
|
replies = {r.remote_id: r for r in harvest.responses if r.kind == "reply"}
|
||||||
|
assert replies["10"].content_html == "<p>reply 10</p>"
|
||||||
|
assert [(replies[i].parent_id, replies[i].own) for i in ("10", "12", "14")] == \
|
||||||
|
[(None, False), ("10", False), ("12", True)]
|
||||||
assert gts.responses("01COPY", COPY, cap=1).complete is False
|
assert gts.responses("01COPY", COPY, cap=1).complete is False
|
||||||
|
|
||||||
|
|
||||||
@@ -457,14 +464,22 @@ def test_threads_client_reads_replies_and_counts():
|
|||||||
params = parse_qs(request.url.query.decode())
|
params = parse_qs(request.url.query.decode())
|
||||||
if path.endswith("/me"):
|
if path.endswith("/me"):
|
||||||
return httpx.Response(200, json={"id": "42", "username": "me"})
|
return httpx.Response(200, json={"id": "42", "username": "me"})
|
||||||
if path.endswith("/111/replies"):
|
if path.endswith("/111/conversation"):
|
||||||
assert "profile_picture_url" in params["fields"][0]
|
# The whole conversation, newest first, as Meta returns it (v2.20.2)
|
||||||
|
assert "profile_picture_url" in params["fields"][0] and "replied_to" in params["fields"][0]
|
||||||
|
to = lambda i: {"replied_to": {"id": i}}
|
||||||
return httpx.Response(200, json={"data": [
|
return httpx.Response(200, json={"data": [
|
||||||
|
{"id": "6", "text": "Ha", "username": "ann", "permalink": "https://www.threads.com/@ann/post/C",
|
||||||
|
"timestamp": "2026-11-10T02:00:00+0000", "hide_status": "NOT_HUSHED", **to("5")},
|
||||||
|
{"id": "5", "text": "Yes", "username": "me", "permalink": "https://www.threads.com/@me/post/B",
|
||||||
|
"timestamp": "2026-11-10T01:00:00+0000", **to("1")},
|
||||||
|
{"id": "7", "text": "under mine", "username": "bo", "permalink": "p", "hide_status": "NOT_HUSHED",
|
||||||
|
**to("4")},
|
||||||
{"id": "1", "text": "Hi", "username": "ann", "permalink": "https://www.threads.com/@ann/post/A",
|
{"id": "1", "text": "Hi", "username": "ann", "permalink": "https://www.threads.com/@ann/post/A",
|
||||||
"timestamp": "2026-11-10T00:00:00+0000", "hide_status": "NOT_HUSHED"},
|
"timestamp": "2026-11-10T00:00:00+0000", "hide_status": "NOT_HUSHED", **to("111")},
|
||||||
{"id": "2", "text": "private"},
|
{"id": "2", "text": "private", **to("111")},
|
||||||
{"id": "3", "text": "hidden", "username": "x", "permalink": "p", "hide_status": "HIDDEN"},
|
{"id": "3", "text": "hidden", "username": "x", "permalink": "p", "hide_status": "HIDDEN", **to("111")},
|
||||||
{"id": "4", "text": "mine", "username": "me", "permalink": "p"}]})
|
{"id": "4", "text": "mine", "username": "me", "permalink": "p", **to("111")}]})
|
||||||
if path.endswith("/111/insights"):
|
if path.endswith("/111/insights"):
|
||||||
assert params["metric"] == ["likes,reposts,quotes"]
|
assert params["metric"] == ["likes,reposts,quotes"]
|
||||||
return httpx.Response(200, json={"data": [
|
return httpx.Response(200, json={"data": [
|
||||||
@@ -474,7 +489,10 @@ def test_threads_client_reads_replies_and_counts():
|
|||||||
|
|
||||||
threads = ThreadsClient("tok", http=httpx.Client(transport=httpx.MockTransport(api)))
|
threads = ThreadsClient("tok", http=httpx.Client(transport=httpx.MockTransport(api)))
|
||||||
harvest = threads.responses("111", "https://www.threads.com/@me/post/X")
|
harvest = threads.responses("111", "https://www.threads.com/@me/post/X")
|
||||||
assert [(r.kind, r.author_name, r.content_html) for r in harvest.responses] == [("reply", "ann", "<p>Hi</p>")]
|
# Our own reply to our post continues the thread (4, and 7 under it, are left out);
|
||||||
|
# our reply to ann (5) and her answer (6) are kept, oldest first
|
||||||
|
assert [(r.author_name, r.content_html, r.parent_id, r.own) for r in harvest.responses] == [
|
||||||
|
("ann", "<p>Hi</p>", None, False), ("me", "<p>Yes</p>", "1", True), ("ann", "<p>Ha</p>", "5", False)]
|
||||||
assert harvest.counts == {"likes": 12, "reposts": 3, "quotes": 0}
|
assert harvest.counts == {"likes": 12, "reposts": 3, "quotes": 0}
|
||||||
|
|
||||||
|
|
||||||
@@ -658,3 +676,81 @@ def test_quote_counts_include_anonymous_ones(app, client):
|
|||||||
assert "Quoter" in page, "the named quote is listed under Responses"
|
assert "Quoter" in page, "the named quote is listed under Responses"
|
||||||
home = app.test_client().get("/").get_data(as_text=True)
|
home = app.test_client().get("/").get_data(as_text=True)
|
||||||
assert 'title="3 quotes"' in home
|
assert 'title="3 quotes"' in home
|
||||||
|
|
||||||
|
|
||||||
|
# --- Reply threads (v2.20.2) ------------------------------------------------------
|
||||||
|
|
||||||
|
def test_thread_members_follow_replies_to_replies():
|
||||||
|
from starpunk.backfeed import thread_members
|
||||||
|
posts = [ # newest first, as Threads lists them
|
||||||
|
{"id": "c", "parent": "b", "own": False},
|
||||||
|
{"id": "b", "parent": "a", "own": True},
|
||||||
|
{"id": "x", "parent": "self", "own": False},
|
||||||
|
{"id": "self", "parent": "COPY", "own": True},
|
||||||
|
{"id": "a", "parent": "COPY", "own": False},
|
||||||
|
{"id": "loop", "parent": "loop", "own": False},
|
||||||
|
]
|
||||||
|
assert thread_members(posts, "COPY") == {"a": None, "b": "a", "c": "b"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_bluesky_client_reads_nested_replies():
|
||||||
|
me, post = "did:plc:me", "at://did:plc:me/app.bsky.feed.post/abc"
|
||||||
|
|
||||||
|
def view(did, rkey, text, at):
|
||||||
|
return {"uri": f"at://{did}/app.bsky.feed.post/{rkey}", "indexedAt": at,
|
||||||
|
"author": {"did": did, "handle": did.rsplit(":", 1)[1] + ".example"},
|
||||||
|
"record": {"text": text, "createdAt": at}}
|
||||||
|
|
||||||
|
def api(request):
|
||||||
|
nsid = request.url.path.removeprefix("/xrpc/")
|
||||||
|
if nsid == "com.atproto.server.createSession":
|
||||||
|
return httpx.Response(200, json={"did": me, "handle": "me.example", "accessJwt": "a",
|
||||||
|
"refreshJwt": "r"})
|
||||||
|
if nsid in ("app.bsky.feed.getLikes", "app.bsky.feed.getRepostedBy", "app.bsky.feed.getQuotes"):
|
||||||
|
return httpx.Response(200, json={"likes": [], "repostedBy": [], "posts": []})
|
||||||
|
if nsid == "app.bsky.feed.getPostThread":
|
||||||
|
assert int(dict(request.url.params)["depth"]) > 1
|
||||||
|
return httpx.Response(200, json={"thread": {"post": {}, "replies": [
|
||||||
|
{"post": view("did:plc:eve", "r1", "First", "2026-11-10T01:00:00Z"), "replies": [
|
||||||
|
{"post": view(me, "r2", "Thanks", "2026-11-10T02:00:00Z"), "replies": [
|
||||||
|
{"post": view("did:plc:eve", "r3", "Anytime", "2026-11-10T03:00:00Z")}]}]},
|
||||||
|
{"post": view(me, "self", "More from me", "2026-11-10T00:30:00Z")}]}})
|
||||||
|
if nsid == "app.bsky.actor.getProfiles":
|
||||||
|
return httpx.Response(200, json={"profiles": []})
|
||||||
|
return httpx.Response(400, json={"error": "Unknown"})
|
||||||
|
|
||||||
|
bsky = BlueskyClient("https://bsky.example", "me.example", "pw",
|
||||||
|
http=httpx.Client(transport=httpx.MockTransport(api)))
|
||||||
|
replies = [(r.remote_id.rsplit("/", 1)[1], r.parent_id and r.parent_id.rsplit("/", 1)[1], r.own)
|
||||||
|
for r in bsky.responses(post, "https://bsky.app/profile/me.example/post/abc").responses]
|
||||||
|
assert replies == [("r1", None, False), ("r2", "r1", True), ("r3", "r2", False)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_reply_threads_are_stored_and_shown_nested(app, client):
|
||||||
|
app.config["WEBMENTION_ENABLED"] = True
|
||||||
|
note, _ = crossposted(app)
|
||||||
|
first, mine, answer = reply(1, "It keeps coming up"), reply(2, "That is terrifying"), reply(3, "To be fair")
|
||||||
|
mine.parent_id, mine.own, mine.author_name = "1", True, "philskents"
|
||||||
|
answer.parent_id = "2"
|
||||||
|
client.harvest = Harvest([first, mine, answer])
|
||||||
|
run(app)
|
||||||
|
|
||||||
|
stored = {r["remote_id"]: r for r in rows(app, note.id)}
|
||||||
|
assert [stored[i]["parent_remote_id"] for i in "123"] == [None, "1", "2"]
|
||||||
|
assert stored["2"]["notified_at"], "our own reply is no news to us"
|
||||||
|
assert not stored["1"]["notified_at"]
|
||||||
|
|
||||||
|
page = app.test_client().get(f"/note/{note.slug}").data.decode()
|
||||||
|
assert "3 Replies" in page
|
||||||
|
# Each answer sits inside the reply it answers
|
||||||
|
outer = page.index("It keeps coming up")
|
||||||
|
assert outer < page.index('class="webmention-thread"') < page.index("That is terrifying") \
|
||||||
|
< page.index("To be fair")
|
||||||
|
assert page.count('class="webmention-thread"') == 2
|
||||||
|
|
||||||
|
import mf2py
|
||||||
|
items = mf2py.parse(doc=page, url=f"{SITE}/note/{note.slug}")["items"]
|
||||||
|
entry = next(i for i in items if "h-entry" in i["type"])
|
||||||
|
(comment,) = entry["properties"]["comment"]
|
||||||
|
(nested,) = comment["properties"]["comment"]
|
||||||
|
assert "terrifying" in json.dumps(nested) and "To be fair" in json.dumps(nested["properties"]["comment"])
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
"""
|
||||||
|
Paging of the homepage, likes page and admin dashboard (v2.21.0)
|
||||||
|
|
||||||
|
Before v2.21.0 the homepage showed only the 20 newest notes, the likes page
|
||||||
|
the 50 newest likes, and the admin dashboard paged list_notes()'s default
|
||||||
|
50 newest notes, so older notes were unreachable from all three.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import re
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from starpunk import create_app
|
||||||
|
from starpunk.auth import create_session
|
||||||
|
from starpunk.notes import count_notes, create_note
|
||||||
|
|
||||||
|
START = datetime(2026, 1, 1, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def app(tmp_path):
|
||||||
|
data = tmp_path / "data"
|
||||||
|
data.mkdir(parents=True, exist_ok=True)
|
||||||
|
return create_app(config={
|
||||||
|
"TESTING": True,
|
||||||
|
"DATABASE_PATH": data / "starpunk.db",
|
||||||
|
"DATA_PATH": data,
|
||||||
|
"NOTES_PATH": data / "notes",
|
||||||
|
"SESSION_SECRET": "test-secret-key",
|
||||||
|
"ADMIN_ME": "https://test.example.com",
|
||||||
|
"SITE_URL": "http://localhost:5000",
|
||||||
|
"SITE_NAME": "Test Site",
|
||||||
|
"DEV_MODE": False,
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client(app):
|
||||||
|
return app.test_client()
|
||||||
|
|
||||||
|
|
||||||
|
def make_notes(app, published=0, drafts=0, likes=0):
|
||||||
|
"""Notes one minute apart, oldest first; content says which is which"""
|
||||||
|
n = 0
|
||||||
|
with app.app_context():
|
||||||
|
for i in range(published):
|
||||||
|
create_note(content=f"Published note {i:03d}", published=True,
|
||||||
|
created_at=START + timedelta(minutes=n))
|
||||||
|
n += 1
|
||||||
|
for i in range(drafts):
|
||||||
|
create_note(content=f"Draft note {i:03d}", published=False,
|
||||||
|
created_at=START + timedelta(minutes=n))
|
||||||
|
n += 1
|
||||||
|
for i in range(likes):
|
||||||
|
create_note(content=f"Liked thing {i:03d}", published=True,
|
||||||
|
like_of=f"https://example.com/liked/{i}",
|
||||||
|
created_at=START + timedelta(minutes=n))
|
||||||
|
n += 1
|
||||||
|
|
||||||
|
|
||||||
|
def shown(html, prefix):
|
||||||
|
return sorted(set(re.findall(rf"{prefix} (\d{{3}})", html)))
|
||||||
|
|
||||||
|
|
||||||
|
def rel_link(html, rel):
|
||||||
|
m = re.search(rf'<a rel="{rel}" href="([^"]+)"', html)
|
||||||
|
return m.group(1) if m else None
|
||||||
|
|
||||||
|
|
||||||
|
class TestCountNotes:
|
||||||
|
def test_count_matches_filters(self, app):
|
||||||
|
make_notes(app, published=7, drafts=3, likes=4)
|
||||||
|
with app.app_context():
|
||||||
|
assert count_notes() == 14
|
||||||
|
assert count_notes(published_only=True) == 11
|
||||||
|
assert count_notes(published_only=True, likes=False) == 7
|
||||||
|
assert count_notes(published_only=True, likes=True) == 4
|
||||||
|
|
||||||
|
|
||||||
|
class TestHomepagePaging:
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def notes(self, app):
|
||||||
|
# 45 published notes = 3 pages of 20; drafts and likes stay off
|
||||||
|
make_notes(app, published=45, drafts=2, likes=3)
|
||||||
|
|
||||||
|
def test_first_page_is_newest_20(self, client):
|
||||||
|
html = client.get("/").get_data(as_text=True)
|
||||||
|
assert shown(html, "Published note") == [f"{i:03d}" for i in range(25, 45)]
|
||||||
|
assert "Page 1 of 3" in html
|
||||||
|
assert rel_link(html, "prev") is None
|
||||||
|
assert rel_link(html, "next") == "/?page=2"
|
||||||
|
|
||||||
|
def test_middle_page_links_both_ways(self, client):
|
||||||
|
html = client.get("/?page=2").get_data(as_text=True)
|
||||||
|
assert shown(html, "Published note") == [f"{i:03d}" for i in range(5, 25)]
|
||||||
|
# page 1 is the bare URL
|
||||||
|
assert rel_link(html, "prev") == "/"
|
||||||
|
assert rel_link(html, "next") == "/?page=3"
|
||||||
|
assert "<title>Page 2 · Test Site</title>" in html
|
||||||
|
|
||||||
|
def test_last_page_has_the_oldest(self, client):
|
||||||
|
html = client.get("/?page=3").get_data(as_text=True)
|
||||||
|
assert shown(html, "Published note") == [f"{i:03d}" for i in range(0, 5)]
|
||||||
|
assert rel_link(html, "next") is None
|
||||||
|
assert rel_link(html, "prev") == "/?page=2"
|
||||||
|
|
||||||
|
def test_every_published_note_reachable_once(self, client):
|
||||||
|
seen = []
|
||||||
|
for p in ("/", "/?page=2", "/?page=3"):
|
||||||
|
seen += re.findall(r"Published note (\d{3})", client.get(p).get_data(as_text=True))
|
||||||
|
assert sorted(set(seen)) == [f"{i:03d}" for i in range(45)]
|
||||||
|
|
||||||
|
def test_drafts_and_likes_never_listed(self, client):
|
||||||
|
for p in ("/", "/?page=2", "/?page=3"):
|
||||||
|
html = client.get(p).get_data(as_text=True)
|
||||||
|
assert "Draft note" not in html
|
||||||
|
assert "Liked thing" not in html
|
||||||
|
|
||||||
|
def test_page_one_redirects_to_bare_url(self, client):
|
||||||
|
r = client.get("/?page=1")
|
||||||
|
assert r.status_code == 301
|
||||||
|
assert r.headers["Location"].endswith("/")
|
||||||
|
assert "page=" not in r.headers["Location"]
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("page", ["4", "0", "-1", "abc", "2.5", ""])
|
||||||
|
def test_bad_or_out_of_range_page_is_404(self, client, page):
|
||||||
|
assert client.get(f"/?page={page}").status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
class TestHomepageSmall:
|
||||||
|
def test_no_pager_when_one_page(self, app, client):
|
||||||
|
make_notes(app, published=5)
|
||||||
|
html = client.get("/").get_data(as_text=True)
|
||||||
|
assert 'class="pager"' not in html
|
||||||
|
assert "<title>Test Site</title>" in html
|
||||||
|
|
||||||
|
def test_empty_site_still_renders(self, client):
|
||||||
|
r = client.get("/")
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert "No notes published yet" in r.get_data(as_text=True)
|
||||||
|
|
||||||
|
|
||||||
|
class TestLikesPaging:
|
||||||
|
def test_likes_page_two(self, app, client):
|
||||||
|
make_notes(app, published=2, likes=55) # 50 per page
|
||||||
|
first = client.get("/likes").get_data(as_text=True)
|
||||||
|
assert len(shown(first, "Liked thing")) == 50
|
||||||
|
assert rel_link(first, "next") == "/likes?page=2"
|
||||||
|
second = client.get("/likes?page=2").get_data(as_text=True)
|
||||||
|
assert shown(second, "Liked thing") == [f"{i:03d}" for i in range(0, 5)]
|
||||||
|
assert rel_link(second, "prev") == "/likes"
|
||||||
|
assert "Published note" not in first + second
|
||||||
|
assert client.get("/likes?page=3").status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
class TestAdminDashboardPaging:
|
||||||
|
@pytest.fixture
|
||||||
|
def admin(self, app, client):
|
||||||
|
with app.test_request_context():
|
||||||
|
token = create_session("https://test.example.com")
|
||||||
|
client.set_cookie("starpunk_session", token)
|
||||||
|
return client
|
||||||
|
|
||||||
|
def test_all_notes_reachable_past_fifty(self, app, admin):
|
||||||
|
# 60 published + 5 drafts = 65 notes = 3 pages of 25
|
||||||
|
make_notes(app, published=60, drafts=5)
|
||||||
|
html = admin.get("/admin/").get_data(as_text=True)
|
||||||
|
assert "Page 1 of 3" in html
|
||||||
|
last = admin.get("/admin/?page=3").get_data(as_text=True)
|
||||||
|
# the 15 oldest notes, which the old 50-note cap hid
|
||||||
|
assert shown(last, "Published note") == [f"{i:03d}" for i in range(0, 15)]
|
||||||
|
|
||||||
|
def test_drafts_listed(self, app, admin):
|
||||||
|
make_notes(app, published=3, drafts=2)
|
||||||
|
assert "Draft note 000" in admin.get("/admin/").get_data(as_text=True)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("page,expected", [("99", "Page 3 of 3"), ("abc", "Page 1 of 3"),
|
||||||
|
("0", "Page 1 of 3")])
|
||||||
|
def test_bad_page_falls_back(self, app, admin, page, expected):
|
||||||
|
make_notes(app, published=60)
|
||||||
|
r = admin.get(f"/admin/?page={page}")
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert expected in r.get_data(as_text=True)
|
||||||
@@ -268,3 +268,59 @@ def test_reply_page_and_home_page_show_the_context(app, web):
|
|||||||
reply_to = entry["properties"]["in-reply-to"][0]
|
reply_to = entry["properties"]["in-reply-to"][0]
|
||||||
assert (reply_to if isinstance(reply_to, str) else reply_to["properties"]["url"][0]) == TOOT
|
assert (reply_to if isinstance(reply_to, str) else reply_to["properties"]["url"][0]) == TOOT
|
||||||
assert "Ada Lovelace" not in json.dumps(entry["properties"].get("author", ""))
|
assert "Ada Lovelace" not in json.dumps(entry["properties"].get("author", ""))
|
||||||
|
|
||||||
|
|
||||||
|
# --- Moving pictures (v2.20.1) --------------------------------------------------
|
||||||
|
|
||||||
|
MP4 = b"\x00\x00\x00\x18ftypmp42" + b"\x00" * 64
|
||||||
|
|
||||||
|
|
||||||
|
def animated_gif():
|
||||||
|
buffer = io.BytesIO()
|
||||||
|
frames = [Image.new("RGB", (800, 400), color) for color in ("red", "green", "blue")]
|
||||||
|
frames[0].save(buffer, "GIF", save_all=True, append_images=frames[1:], duration=80, loop=0)
|
||||||
|
return buffer.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def test_mastodon_gifv_is_kept_as_a_looping_video(app, web, monkeypatch):
|
||||||
|
status = {**STATUS, "media_attachments": [{
|
||||||
|
"type": "gifv", "url": "https://masto.example/media/original.mp4",
|
||||||
|
"preview_url": "https://masto.example/media/small.png", "description": "Engineering report"}]}
|
||||||
|
web.routes["https://masto.example/api/v1/statuses/117611186265622833"] = \
|
||||||
|
lambda r: httpx.Response(200, json=status)
|
||||||
|
web.routes["https://masto.example/media/original.mp4"] = \
|
||||||
|
lambda r: httpx.Response(200, content=MP4, headers={"Content-Type": "video/mp4"})
|
||||||
|
|
||||||
|
note = _reply(app, TOOT, "Same here")
|
||||||
|
context = fetch(app, TOOT)
|
||||||
|
assert context["video"] == "https://masto.example/media/original.mp4"
|
||||||
|
assert avatars.cached_video(app.config["DATA_PATH"], context["video"])
|
||||||
|
|
||||||
|
client = app.test_client()
|
||||||
|
page = client.get(f"/note/{note.slug}").data.decode()
|
||||||
|
assert "<video" in page and "autoplay loop muted playsinline" in page
|
||||||
|
assert 'aria-label="Engineering report"' in page
|
||||||
|
src = page.split('<video class="reply-photo" src="', 1)[1].split('"', 1)[0]
|
||||||
|
response = client.get(src)
|
||||||
|
assert response.status_code == 200 and response.mimetype == "video/mp4"
|
||||||
|
|
||||||
|
|
||||||
|
def test_animated_gif_stays_animated(app, web):
|
||||||
|
web.routes[ARTICLE] = lambda r: httpx.Response(200, html=ARTICLE_PAGE.replace("/img/lead.png", "/img/lead.gif"))
|
||||||
|
web.routes["https://news.example/img/lead.gif"] = \
|
||||||
|
lambda r: httpx.Response(200, content=animated_gif(), headers={"Content-Type": "image/gif"})
|
||||||
|
context = fetch(app, ARTICLE)
|
||||||
|
data = app.config["DATA_PATH"]
|
||||||
|
with Image.open(avatars.preview_folder(data) / avatars.cached_preview(data, context["photo"])) as image:
|
||||||
|
assert image.n_frames == 3
|
||||||
|
assert image.width == avatars.PREVIEW_WIDTH
|
||||||
|
|
||||||
|
|
||||||
|
def test_unused_videos_are_removed(app, web):
|
||||||
|
data = app.config["DATA_PATH"]
|
||||||
|
folder = avatars.preview_folder(data)
|
||||||
|
folder.mkdir(parents=True, exist_ok=True)
|
||||||
|
stray = folder / avatars.video_name_for("https://gone.example/x.mp4")
|
||||||
|
stray.write_bytes(MP4)
|
||||||
|
avatars.remove_unused(app.config["DATABASE_PATH"], data)
|
||||||
|
assert not stray.exists()
|
||||||
Reference in new issue
Block a user