Merge branch 'feat/v2.17.0-article-urls' for v2.17.0 release
Build Container / build (push) Failing after 9m31s
Build Container / build (push) Failing after 9m31s
This commit is contained in:
commit
191c99b59b
26 files changed
+308
-60
No files matched your search
@@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [2.17.0] - 2026-11-12
|
||||
|
||||
Articles get URLs of their own (ADR-077).
|
||||
|
||||
### Changed
|
||||
|
||||
- Articles live at `/article/<slug>` instead of `/note/<slug>`. The other address redirects (301), so links keep working when a note gains or loses a title. Feeds, pages, Micropub, crossposts, webmentions, notifications, search and the MCP tools all give the new URLs
|
||||
- A new article's slug comes from its title (`Why I Left Twitter` → `why-i-left-twitter`; `-2` if taken). An `mp-slug` still wins, notes keep timestamp slugs, and slugs don't change when a title is edited later
|
||||
- A Micropub update that adds or removes a title answers 201 with the post's new URL in `Location`, as the spec requires
|
||||
|
||||
## [2.16.0] - 2026-11-11
|
||||
|
||||
Articles as the IndieWeb defines them: titles and summaries stored apart from the text (ADR-076).
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# ADR-062: Timestamp-Based Slug Format
|
||||
|
||||
## Status
|
||||
Accepted (Supersedes ADR-007)
|
||||
Accepted (Supersedes ADR-007). Articles take their slug from the title since v2.17.0 ([ADR-077](ADR-077-article-urls-and-title-slugs.md)).
|
||||
|
||||
## Context
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
|
||||
Accepted (v2.16.0, 2026-11-11)
|
||||
|
||||
Article URLs (`/article/<slug>`) and title slugs: [ADR-077](ADR-077-article-urls-and-title-slugs.md) (v2.17.0).
|
||||
|
||||
Supersedes the v2.3.3 design ([micropub-title-and-source-url](../design/v2.3.3/2026-10-31-micropub-title-and-source-url.md))
|
||||
and Q22's "a note has a title when its content starts with `#`". Amends
|
||||
ADR-014 (feed item titles) and ADR-040 (`p-name` and `p-summary`).
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
# ADR-077: Article URLs and slugs from titles
|
||||
|
||||
## Status
|
||||
|
||||
Accepted (v2.17.0, 2026-11-12)
|
||||
|
||||
Amends ADR-062 (default slugs) for articles and ADR-076 (articles).
|
||||
|
||||
## Context
|
||||
|
||||
ADR-076 (v2.16.0) made a note with a title an article, but articles still got
|
||||
a `/note/<timestamp>` URL like any other note. An article is not a note, and
|
||||
its URL should say so. ADR-062 chose timestamp slugs because short notes have
|
||||
no good words for a URL and their text may be private; an article has a title
|
||||
written to be read, and that is the usual source of its slug on the IndieWeb.
|
||||
|
||||
## Decision
|
||||
|
||||
- **URLs.** Articles live at `/article/<slug>`, other notes at `/note/<slug>`.
|
||||
`Note.permalink`, `Note.url`, `Note.endpoint` and `utils.post_path` /
|
||||
`post_url` build them; nothing else writes `/note/` by hand. Slugs stay
|
||||
unique across both, so a slug still names one post.
|
||||
- **One URL each, the other redirects.** `/note/<slug>` for an article and
|
||||
`/article/<slug>` for a note answer 301 to the right one. Adding or removing
|
||||
a title changes the URL, and links made before (webmentions sent, crossposts,
|
||||
bookmarks) keep working. A deleted post is 410 at either.
|
||||
- **Slug from the title.** When a post is created with a title and no
|
||||
`mp-slug`, the slug is the title made URL-safe (`sanitize_slug`: accents
|
||||
folded, lowercase, hyphens), cut at a word boundary to 80 characters, `-2`,
|
||||
`-3`… if taken, `-article` if reserved. A title with nothing usable (only
|
||||
emoji, say) falls back to the timestamp slug. Notes keep timestamp slugs.
|
||||
- **Slugs don't follow later title changes.** Editing an article's title, or
|
||||
making a note an article, keeps its slug: a slug is the stable part of the
|
||||
URL.
|
||||
- **Micropub.** `Location` and `q=source` give the new URLs. Updates accept
|
||||
either URL. An update that adds or removes a title answers 201 with the new
|
||||
URL in `Location`, as the Micropub spec requires when a post's URL changes;
|
||||
other updates are still 204.
|
||||
- **Incoming webmentions** to either URL find the post.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Production had no articles when this shipped, so no published URL changed.
|
||||
- A note given a title later keeps its timestamp slug under `/article/`.
|
||||
- Stored URLs (webmention sources, crosspost records) are not rewritten; the
|
||||
redirects cover them.
|
||||
@@ -5,8 +5,8 @@ records one decision: its context, what was decided, and the consequences.
|
||||
Superseded ADRs are kept as history; their Status line names the ADR that
|
||||
replaced them.
|
||||
|
||||
**Total ADR files**: 72 (71 numbers: ADR-001 to ADR-044 and ADR-050 to
|
||||
ADR-076, with two files numbered ADR-012). See [Numbering](#numbering).
|
||||
**Total ADR files**: 73 (72 numbers: ADR-001 to ADR-044 and ADR-050 to
|
||||
ADR-077, with two files numbered ADR-012). See [Numbering](#numbering).
|
||||
|
||||
Status values: **Accepted** (in force), **Superseded** (replaced by a later
|
||||
ADR), **Deprecated** (withdrawn, nothing replaces it; none at present),
|
||||
@@ -48,7 +48,7 @@ See also [database architecture](../architecture/database.md).
|
||||
|
||||
| ADR | Title | Status | Summary |
|
||||
|---|---|---|---|
|
||||
| [062](ADR-062-timestamp-based-slug-format.md) | Timestamp-Based Slug Format | Accepted | Default slugs are `YYYYMMDDHHMMSS` timestamps (v1.5.0); replaces ADR-007. |
|
||||
| [062](ADR-062-timestamp-based-slug-format.md) | Timestamp-Based Slug Format | Accepted* | Default slugs are `YYYYMMDDHHMMSS` timestamps (v1.5.0); replaces ADR-007. Articles take theirs from the title (ADR-077). |
|
||||
| [035](ADR-035-custom-slugs.md) | Custom Slugs in Micropub | Accepted* | Honour `mp-slug`, sanitized, with reserved names protected (v1.1.0). |
|
||||
| [034](ADR-034-full-text-search.md) | Full-Text Search with SQLite FTS5 | Accepted | FTS5 search over note content (v1.1.0). |
|
||||
| [057](ADR-057-media-attachment-model.md) | Media Attachment Model | Accepted | Social-media-style image attachments: up to 4 per note, ordered, with captions. |
|
||||
@@ -69,6 +69,7 @@ See also [database architecture](../architecture/database.md).
|
||||
|---|---|---|---|
|
||||
| [040](ADR-040-microformats2-compliance.md) | Strict Microformats2 Compliance | Accepted* | Full h-entry, h-card and h-feed markup (v1.3.0, reviewed v2.8.0); `p-name`/`p-summary` per ADR-076. |
|
||||
| [076](ADR-076-note-title-and-summary-columns.md) | Article titles and summaries stored apart from the text | Accepted | `notes.title`/`summary` columns; feeds title only articles; article previews and crossposts are title + summary (v2.16.0). |
|
||||
| [077](ADR-077-article-urls-and-title-slugs.md) | Article URLs and slugs from titles | Accepted | Articles at `/article/<slug>` with slugs from their titles; the other prefix redirects (v2.17.0). |
|
||||
| [061](ADR-061-author-discovery.md) | Author Profile Discovery from IndieAuth | Accepted | The author h-card is read from `ADMIN_ME` and cached. |
|
||||
| [063](ADR-063-webmention-implementation.md) | Webmention Implementation | Accepted | Async receiving (202) and sending via a background worker, SSRF guard, rate limits, moderation (v1.6.0, revised up to v2.10.1). *Reconstructed.* |
|
||||
| [028](ADR-028-micropub-implementation.md) | Micropub Implementation Strategy | Accepted* | `/micropub` endpoint for creating posts (v1.0.0-rc.1); tokens now per ADR-064. |
|
||||
@@ -171,7 +172,7 @@ was carried out and is not itself superseded.
|
||||
|
||||
## How to create a new ADR
|
||||
|
||||
1. Use the next number after the highest existing one (currently ADR-076).
|
||||
1. Use the next number after the highest existing one (currently ADR-077).
|
||||
2. Name it `ADR-NNN-brief-descriptive-title.md`.
|
||||
3. Follow the format of recent ADRs (e.g. ADR-070, ADR-071):
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
# v2.17.0: Article URLs and title slugs
|
||||
|
||||
Implements ADR-077. Follow-up to v2.16.0 (ADR-076): articles had `/note/`
|
||||
URLs and timestamp slugs.
|
||||
|
||||
## What changed
|
||||
|
||||
| Area | Change |
|
||||
|---|---|
|
||||
| URL helpers | `utils.post_path(slug, title)` and `post_url(slug, title)`; `Note.permalink` uses them, `Note.endpoint` (`public.article`/`public.note`) and `Note.url` (absolute) are new |
|
||||
| Routes | `public.article` at `/article/<slug>`; `note` and `article` share `_permalink(slug, endpoint)`, which 301s to the other route when the post's type doesn't match. `_note_was_deleted` checks both URLs for hard-deleted posts |
|
||||
| Slugs | `slug_utils.generate_title_slug(title, existing)`; `create_note` uses it for titled posts without `custom_slug`, else the timestamp slug |
|
||||
| Micropub | `Location`, `q=source` url via `note.url`; `_note_from_url` accepts `/article/`; update answers 201 + `Location` when a title is added or removed |
|
||||
| Other URL builders | Templates (`note.url`), webmention sending (`post_url`/`note.url`), crosspost permalink, backfeed target, notification links, search results (`article_title` from `notes.title`), MCP tools |
|
||||
| Webmention receiving | `resolve_target_note` accepts `/note/` and `/article/` |
|
||||
|
||||
## Tests
|
||||
|
||||
`tests/test_articles.py::TestArticleUrls`: Micropub URL and slug, timestamp
|
||||
slugs for notes, redirects both ways, updates via the old URL, slug rules
|
||||
(accents, duplicates, reserved, `mp-slug`, emoji, long titles), 201 on
|
||||
adding/removing a title, 410 for a deleted article, webmention targets and
|
||||
homepage links, search result URLs.
|
||||
@@ -468,5 +468,5 @@ def create_app(config=None):
|
||||
|
||||
# Package version (Semantic Versioning 2.0.0)
|
||||
# See docs/standards/versioning-strategy.md for details
|
||||
__version__ = "2.16.0"
|
||||
__version_info__ = (2, 16, 0)
|
||||
__version__ = "2.17.0"
|
||||
__version_info__ = (2, 17, 0)
|
||||
@@ -25,6 +25,7 @@ from typing import Dict, List, Optional
|
||||
from flask import current_app
|
||||
|
||||
from starpunk.database import get_db
|
||||
from starpunk.utils import post_path
|
||||
|
||||
DAY = 24 * 3600
|
||||
SCHEDULE = [ # (note younger than, check every), in seconds
|
||||
@@ -164,7 +165,7 @@ def _due(db, limit: int) -> list:
|
||||
lease = "(s.backfeed_claimed_until IS NULL OR s.backfeed_claimed_until < datetime('now'))"
|
||||
rows = db.execute(
|
||||
f"""
|
||||
SELECT s.*, n.created_at AS note_created, n.slug AS note_slug {_ELIGIBLE}
|
||||
SELECT s.*, n.created_at AS note_created, n.slug AS note_slug, n.title AS note_title {_ELIGIBLE}
|
||||
AND {lease}
|
||||
AND n.created_at >= datetime('now', ?)
|
||||
AND (s.backfeed_next_at IS NULL OR s.backfeed_next_at <= datetime('now'))
|
||||
@@ -176,7 +177,7 @@ def _due(db, limit: int) -> list:
|
||||
return rows
|
||||
backfill = db.execute(
|
||||
f"""
|
||||
SELECT s.*, n.created_at AS note_created, n.slug AS note_slug {_ELIGIBLE}
|
||||
SELECT s.*, n.created_at AS note_created, n.slug AS note_slug, n.title AS note_title {_ELIGIBLE}
|
||||
AND {lease} AND s.backfeed_backfill = 1
|
||||
AND (s.backfeed_next_at IS NULL OR s.backfeed_next_at <= datetime('now'))
|
||||
ORDER BY s.id LIMIT 1
|
||||
@@ -381,7 +382,7 @@ def check(row, target) -> None:
|
||||
# older note (e.g. one linked after the fact). ADR-074 Decision 5.
|
||||
quiet = bool(row["backfeed_backfill"]) or (
|
||||
row["backfeed_checked_at"] is None and _age_seconds(row["note_created"]) > DAY)
|
||||
store(db, row["note_id"], f"{site}/note/{row['note_slug']}", row["target"], harvest, quiet=quiet)
|
||||
store(db, row["note_id"], site + post_path(row["note_slug"], row["note_title"]), row["target"], harvest, quiet=quiet)
|
||||
_store_counts(db, row["id"], hidden_counts(harvest))
|
||||
|
||||
|
||||
|
||||
@@ -60,17 +60,17 @@ def _clamp(limit: int) -> int:
|
||||
return max(1, min(int(limit), MAX_LIMIT))
|
||||
|
||||
|
||||
def _note_url(slug: str) -> str:
|
||||
from starpunk.utils import absolute_url_for
|
||||
def _note_url(slug: str, title=None) -> str:
|
||||
from starpunk.utils import post_url
|
||||
|
||||
return absolute_url_for("public.note", slug=slug)
|
||||
return post_url(slug, title)
|
||||
|
||||
|
||||
def _summary(note) -> dict:
|
||||
from starpunk.utils import iso_utc
|
||||
|
||||
return {
|
||||
"url": _note_url(note.slug),
|
||||
"url": note.url,
|
||||
"slug": note.slug,
|
||||
"title": note.title,
|
||||
"summary": note.summary,
|
||||
@@ -139,7 +139,7 @@ def register_tools(server: MCPServer, app: Flask) -> None:
|
||||
results = fts(query=query, db_path=db_path, published_only=not include_drafts, limit=_clamp(limit))
|
||||
return {
|
||||
"results": [
|
||||
{"url": _note_url(r["slug"]), "slug": r["slug"], "title": r.get("title"),
|
||||
{"url": _note_url(r["slug"], r.get("article_title")), "slug": r["slug"], "title": r.get("title"),
|
||||
"snippet": r.get("snippet")}
|
||||
for r in results
|
||||
]
|
||||
@@ -176,7 +176,7 @@ def register_tools(server: MCPServer, app: Flask) -> None:
|
||||
note = _find_note(url_or_slug)
|
||||
if not note.published and not _sees_drafts(info):
|
||||
raise ToolError("Note not found")
|
||||
return {"url": _note_url(note.slug), "slug": note.slug,
|
||||
return {"url": note.url, "slug": note.slug,
|
||||
"properties": note_to_mf2(note)["properties"]}
|
||||
|
||||
return await run(one)
|
||||
@@ -314,7 +314,7 @@ def register_tools(server: MCPServer, app: Flask) -> None:
|
||||
from starpunk.micropub import handle_update
|
||||
|
||||
note = _find_note(url)
|
||||
data["url"] = _note_url(note.slug)
|
||||
data["url"] = note.url
|
||||
handle_update(data, info)
|
||||
return _status_after(data["url"])
|
||||
|
||||
@@ -329,7 +329,7 @@ def register_tools(server: MCPServer, app: Flask) -> None:
|
||||
def delete():
|
||||
from starpunk.micropub import handle_delete
|
||||
|
||||
note_url = _note_url(_find_note(url).slug)
|
||||
note_url = _find_note(url).url
|
||||
handle_delete({"url": note_url}, info)
|
||||
return {"url": note_url, "status": "deleted"}
|
||||
|
||||
|
||||
@@ -549,7 +549,7 @@ def _check_type(data: dict) -> None:
|
||||
|
||||
|
||||
def _note_from_url(url: Optional[str], deleted: bool = False):
|
||||
"""Find the note a URL points at (/note/<slug> on this site)"""
|
||||
"""Find the note a URL points at (/note/<slug> or /article/<slug> on this site)"""
|
||||
from urllib.parse import urlparse
|
||||
from starpunk.database import get_db
|
||||
|
||||
@@ -560,7 +560,7 @@ def _note_from_url(url: Optional[str], deleted: bool = False):
|
||||
if parsed.netloc and site.netloc and parsed.netloc != site.netloc:
|
||||
raise MicropubValidationError("URL is not on this site")
|
||||
parts = [p for p in parsed.path.split("/") if p]
|
||||
if len(parts) != 2 or parts[0] not in ("note", "notes"):
|
||||
if len(parts) != 2 or parts[0] not in ("note", "notes", "article", "articles"):
|
||||
raise MicropubValidationError("URL is not a post on this site")
|
||||
slug = parts[1]
|
||||
if deleted:
|
||||
@@ -678,7 +678,7 @@ def handle_create(data: dict, token_info: dict, files=None):
|
||||
from starpunk.syndication import resolve_targets, select_targets
|
||||
select_targets(note.id, resolve_targets(requested_targets))
|
||||
|
||||
return "", 201, {"Location": absolute_url_for("public.note", slug=note.slug)}
|
||||
return "", 201, {"Location": note.url}
|
||||
|
||||
except InvalidNoteDataError as e:
|
||||
raise MicropubValidationError(str(e))
|
||||
@@ -820,6 +820,11 @@ def handle_update(data: dict, token_info: dict):
|
||||
current_app.logger.error(f"Failed to update note via Micropub: {e}")
|
||||
raise MicropubError("server_error", "Failed to update post", status_code=500)
|
||||
|
||||
# Adding or removing a title moves the post between /note/ and /article/:
|
||||
# the spec says to answer 201 with the new URL (v2.17.0)
|
||||
if bool(title) != bool(note.title):
|
||||
from starpunk.utils import post_url
|
||||
return "", 201, {"Location": post_url(note.slug, title)}
|
||||
return "", 204
|
||||
|
||||
|
||||
@@ -860,7 +865,7 @@ def note_to_mf2(note, wanted: Optional[list] = None) -> dict:
|
||||
# HTML-authored content comes back as HTML (3.7.2, v2.9.0)
|
||||
"content": [{"html": content} if note.content_format == "html" else content],
|
||||
"published": [iso_utc(note.created_at)],
|
||||
"url": [absolute_url_for("public.note", slug=note.slug)],
|
||||
"url": [note.url],
|
||||
"post-status": ["published" if note.published else "draft"],
|
||||
}
|
||||
if note.title:
|
||||
|
||||
+19
-6
@@ -383,14 +383,27 @@ class Note:
|
||||
"""
|
||||
Generate permalink (public URL path)
|
||||
|
||||
Returns:
|
||||
URL path string (e.g., '/note/my-first-note')
|
||||
Articles (notes with a title) live under /article/, other notes
|
||||
under /note/ (v2.17.0).
|
||||
|
||||
Examples:
|
||||
>>> note.permalink
|
||||
'/note/my-first-note'
|
||||
Returns:
|
||||
URL path string (e.g., '/note/my-first-note', '/article/my-essay')
|
||||
"""
|
||||
return f"/note/{self.slug}"
|
||||
from starpunk.utils import post_path
|
||||
|
||||
return post_path(self.slug, self.title)
|
||||
|
||||
@property
|
||||
def endpoint(self) -> str:
|
||||
"""The route that shows this note: public.article or public.note (v2.17.0)"""
|
||||
return "public.article" if self.title else "public.note"
|
||||
|
||||
@property
|
||||
def url(self) -> str:
|
||||
"""Absolute permalink, built from SITE_URL (needs an app context)"""
|
||||
from starpunk.utils import post_url
|
||||
|
||||
return post_url(self.slug, self.title)
|
||||
|
||||
@property
|
||||
def is_published(self) -> bool:
|
||||
|
||||
+8
-5
@@ -40,6 +40,7 @@ from starpunk.utils import (
|
||||
calculate_content_hash,
|
||||
validate_note_path,
|
||||
validate_slug,
|
||||
post_url,
|
||||
)
|
||||
|
||||
|
||||
@@ -250,9 +251,11 @@ def create_note(
|
||||
if not success:
|
||||
raise InvalidNoteDataError("slug", custom_slug, error)
|
||||
else:
|
||||
# Generate timestamp-based slug (ADR-062)
|
||||
from starpunk.slug_utils import generate_timestamp_slug
|
||||
slug = generate_timestamp_slug(created_at, existing_slugs)
|
||||
# Articles take their slug from the title (v2.17.0); other notes, or a
|
||||
# title with nothing usable in it, get a timestamp slug (ADR-062)
|
||||
from starpunk.slug_utils import generate_timestamp_slug, generate_title_slug
|
||||
slug = (generate_title_slug(title, existing_slugs) if title else None) \
|
||||
or generate_timestamp_slug(created_at, existing_slugs)
|
||||
|
||||
# 4. GENERATE FILE PATH
|
||||
note_path = generate_note_path(slug, created_at, data_dir)
|
||||
@@ -348,7 +351,7 @@ def create_note(
|
||||
db_path = Path(current_app.config["DATABASE_PATH"])
|
||||
site_url = current_app.config["SITE_URL"]
|
||||
from starpunk.utils import absolute_url_for
|
||||
note_url = absolute_url_for("public.note", slug=slug)
|
||||
note_url = post_url(slug, title)
|
||||
|
||||
# Get rendered HTML from note
|
||||
html_content = note.html
|
||||
@@ -903,7 +906,7 @@ def update_note(
|
||||
db_path = Path(current_app.config["DATABASE_PATH"])
|
||||
site_url = current_app.config["SITE_URL"]
|
||||
from starpunk.utils import absolute_url_for
|
||||
note_url = absolute_url_for("public.note", slug=updated_note.slug)
|
||||
note_url = updated_note.url
|
||||
|
||||
# Get rendered HTML from updated note (if published)
|
||||
html_content = updated_note.html if updated_note.published else None
|
||||
|
||||
@@ -24,6 +24,8 @@ import time
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
from urllib.parse import parse_qsl, urlsplit
|
||||
|
||||
from starpunk.utils import post_path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
RESPONSE_EVENTS = ("reply", "mention", "quote", "like", "repost", "bookmark")
|
||||
@@ -158,7 +160,7 @@ def _messages(rows, site_url: str, conn) -> List[Tuple[str, str, List[int]]]:
|
||||
who = (row["author_name"] or "someone") + (f" via {via}" if via else "")
|
||||
pending = row["moderation_status"] == "pending"
|
||||
link = (f"{site}/admin/webmentions/{row['id']}" if pending
|
||||
else f"{site}/note/{row['slug']}#responses")
|
||||
else f"{site}{post_path(row['slug'], row['note_title'])}#responses")
|
||||
if row["mention_type"] in GROUPED:
|
||||
groups.setdefault((row["target_note_id"], row["mention_type"], row["slug"], pending), []).append(
|
||||
(row["id"], row["author_name"] or "someone", link))
|
||||
@@ -206,7 +208,7 @@ class Sweeper:
|
||||
logger.warning(f"Dropped {dropped} notification(s) older than {DROP_AFTER_HOURS} hours")
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT w.*, n.slug FROM webmentions w JOIN notes n ON n.id = w.target_note_id
|
||||
SELECT w.*, n.slug, n.title AS note_title FROM webmentions w JOIN notes n ON n.id = w.target_note_id
|
||||
WHERE w.notified_at IS NULL AND w.validation_status = 'valid'
|
||||
AND w.moderation_status IN ('approved', 'pending')
|
||||
ORDER BY w.id LIMIT 100
|
||||
|
||||
@@ -8,7 +8,7 @@ No authentication required for these routes.
|
||||
import hashlib
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from flask import Blueprint, abort, render_template, Response, current_app, request, send_from_directory
|
||||
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.websub import embed_hub
|
||||
@@ -354,18 +354,30 @@ def _note_was_deleted(slug: str) -> bool:
|
||||
).fetchone():
|
||||
return True
|
||||
return db.execute(
|
||||
"SELECT 1 FROM webmention_queue WHERE source_url = ? AND source_note_id IS NULL",
|
||||
(absolute_url_for("public.note", slug=slug),),
|
||||
"SELECT 1 FROM webmention_queue WHERE source_url IN (?, ?) AND source_note_id IS NULL",
|
||||
(absolute_url_for("public.note", slug=slug), absolute_url_for("public.article", slug=slug)),
|
||||
).fetchone() is not None
|
||||
|
||||
|
||||
@bp.route("/note/<slug>")
|
||||
def note(slug: str):
|
||||
"""A note's permalink page; an article's /note/ URL redirects to /article/"""
|
||||
return _permalink(slug, "public.note")
|
||||
|
||||
|
||||
@bp.route("/article/<slug>")
|
||||
def article(slug: str):
|
||||
"""An article's permalink page (v2.17.0); a note's /article/ URL redirects to /note/"""
|
||||
return _permalink(slug, "public.article")
|
||||
|
||||
|
||||
def _permalink(slug: str, endpoint: str):
|
||||
"""
|
||||
Individual note permalink page
|
||||
Individual note or article permalink page
|
||||
|
||||
Args:
|
||||
slug: URL-safe note identifier
|
||||
endpoint: The route the request came in on
|
||||
|
||||
Returns:
|
||||
Rendered note template with full content
|
||||
@@ -390,6 +402,12 @@ def note(slug: str):
|
||||
abort(410)
|
||||
abort(404)
|
||||
|
||||
# Each post has one URL: /article/ for articles, /note/ for notes (v2.17.0).
|
||||
# The other one redirects, so links made before a title was added or
|
||||
# removed keep working.
|
||||
if note_obj.endpoint != endpoint:
|
||||
return redirect(url_for(note_obj.endpoint, slug=slug), code=301)
|
||||
|
||||
# Get media for note (v1.2.0 Phase 3)
|
||||
media = get_note_media(note_obj.id)
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ from pathlib import Path
|
||||
from flask import Blueprint, current_app, g, jsonify, render_template, request
|
||||
|
||||
from starpunk.search import has_fts_table, search_notes
|
||||
from starpunk.utils import post_path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -108,7 +109,7 @@ def api_search():
|
||||
"title": r["title"] or f"Note from {r['created_at'][:10]}",
|
||||
"excerpt": r["snippet"], # Already has <mark> tags
|
||||
"published_at": r["created_at"],
|
||||
"url": f"/note/{r['slug']}",
|
||||
"url": post_path(r["slug"], r.get("article_title")),
|
||||
}
|
||||
for r in results
|
||||
],
|
||||
@@ -176,7 +177,7 @@ def search_page():
|
||||
"title": r["title"] or f"Note from {r['created_at'][:10]}",
|
||||
"excerpt": Markup(safe_snippet), # Mark as safe since we've escaped it ourselves
|
||||
"published_at": r["created_at"],
|
||||
"url": f"/note/{r['slug']}",
|
||||
"url": post_path(r["slug"], r.get("article_title")),
|
||||
})
|
||||
results = formatted_results
|
||||
except Exception as e:
|
||||
|
||||
@@ -139,9 +139,10 @@ def resolve_target_note(target_url: str) -> int | None:
|
||||
# Strip query params and fragments for matching
|
||||
target_path = target_parsed.path.rstrip('/')
|
||||
|
||||
# Check if it's a note URL pattern: /note/{slug}
|
||||
if target_path.startswith('/note/'):
|
||||
slug = target_path[6:] # Remove '/note/' prefix
|
||||
# A note or article URL: /note/{slug} or /article/{slug} (v2.17.0).
|
||||
# Either prefix finds the post, as the page redirects to the right one.
|
||||
prefix, _, slug = target_path.lstrip('/').partition('/')
|
||||
if prefix in ('note', 'article') and '/' not in slug:
|
||||
if slug:
|
||||
try:
|
||||
note = get_note(slug=slug)
|
||||
|
||||
@@ -330,6 +330,7 @@ def search_notes_fts5(
|
||||
notes.id,
|
||||
notes.slug,
|
||||
notes_fts.title,
|
||||
notes.title AS article_title,
|
||||
notes.published,
|
||||
notes.created_at,
|
||||
rank AS relevance,
|
||||
@@ -356,6 +357,7 @@ def search_notes_fts5(
|
||||
'id': row['id'],
|
||||
'slug': row['slug'],
|
||||
'title': row['title'],
|
||||
'article_title': row['article_title'],
|
||||
'snippet': row['snippet'], # Plain string - route must escape HTML while preserving <mark> tags
|
||||
'relevance': row['relevance'],
|
||||
'published': bool(row['published']),
|
||||
@@ -466,6 +468,7 @@ def search_notes_fallback(
|
||||
'id': row['id'],
|
||||
'slug': row['slug'],
|
||||
'title': title,
|
||||
'article_title': row['title'],
|
||||
'snippet': generate_snippet(content, query),
|
||||
'relevance': 0.0, # No ranking in fallback mode
|
||||
'published': bool(row['published']),
|
||||
|
||||
@@ -288,6 +288,35 @@ def generate_timestamp_slug(
|
||||
return f"{base_slug}-{suffix}"
|
||||
|
||||
|
||||
TITLE_SLUG_LENGTH = 80
|
||||
|
||||
|
||||
def generate_title_slug(title: str, existing_slugs: Set[str]) -> Optional[str]:
|
||||
"""
|
||||
A slug made from an article's title (v2.17.0)
|
||||
|
||||
"Why I Left Twitter" becomes 'why-i-left-twitter'; long titles are cut at
|
||||
a word boundary, and a taken slug gets -2, -3, ...
|
||||
|
||||
Returns:
|
||||
The slug, or None when the title has nothing usable (e.g. only emoji),
|
||||
so the caller falls back to a timestamp slug.
|
||||
"""
|
||||
slug = sanitize_slug(title or "")
|
||||
if len(slug) > TITLE_SLUG_LENGTH:
|
||||
cut = slug[:TITLE_SLUG_LENGTH + 1]
|
||||
slug = cut.rsplit("-", 1)[0] if "-" in cut else slug[:TITLE_SLUG_LENGTH]
|
||||
slug = slug.strip("-")
|
||||
if not slug:
|
||||
return None
|
||||
if is_reserved_slug(slug):
|
||||
slug = f"{slug}-article"
|
||||
try:
|
||||
return make_slug_unique_with_suffix(slug, existing_slugs)
|
||||
except ValueError: # 99 articles with this title
|
||||
return None
|
||||
|
||||
|
||||
def validate_and_sanitize_custom_slug(custom_slug: str, existing_slugs: Set[str]) -> tuple[bool, Optional[str], Optional[str]]:
|
||||
"""
|
||||
Validate and sanitize a custom slug from Micropub
|
||||
|
||||
@@ -1524,7 +1524,7 @@ def _reconcile(row, target: Target) -> tuple:
|
||||
site = current_app.config["SITE_URL"].rstrip("/")
|
||||
post = Post(
|
||||
note=note,
|
||||
permalink=f"{site}/note/{note.slug}",
|
||||
permalink=note.url,
|
||||
tags=[t["display_name"] for t in get_note_tags(note.id, entered_order=True)],
|
||||
max_chars=target.max_chars,
|
||||
# Articles are posted as a teaser without images (v2.16.0)
|
||||
|
||||
@@ -716,6 +716,16 @@ def absolute_url_for(endpoint: str, **values) -> str:
|
||||
return current_app.config["SITE_URL"].rstrip("/") + url_for(endpoint, **values)
|
||||
|
||||
|
||||
def post_path(slug: str, title: Optional[str] = None) -> str:
|
||||
"""A post's URL path: /article/<slug> when it has a title, else /note/<slug> (v2.17.0)"""
|
||||
return f"/{'article' if title else 'note'}/{slug}"
|
||||
|
||||
|
||||
def post_url(slug: str, title: Optional[str] = None) -> str:
|
||||
"""A post's absolute URL (see post_path)"""
|
||||
return absolute_url_for("public.article" if title else "public.note", slug=slug)
|
||||
|
||||
|
||||
def iso_utc(value) -> str:
|
||||
"""
|
||||
Format a timestamp as RFC 3339 UTC for dt-* and Micropub (v2.8.0)
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</td>
|
||||
<td class="note-actions">
|
||||
{% if note.published %}
|
||||
<a href="{{ url_for('public.note', slug=note.slug) }}" class="button button-small" target="_blank">
|
||||
<a href="{{ note.url }}" class="button button-small" target="_blank">
|
||||
View
|
||||
</a>
|
||||
{% endif %}
|
||||
|
||||
+2
-2
@@ -54,7 +54,7 @@
|
||||
|
||||
<footer class="note-meta">
|
||||
{# u-url and u-uid same for notes (per Q23) #}
|
||||
<a class="u-url u-uid" href="{{ absolute_url_for('public.note', slug=note.slug) }}"><time class="dt-published" datetime="{{ note.created_at|iso_utc }}">{{ note.created_at.strftime('%B %-d, %Y · %-I:%M %p') }}</time></a>
|
||||
<a class="u-url u-uid" href="{{ note.url }}"><time class="dt-published" datetime="{{ note.created_at|iso_utc }}">{{ note.created_at.strftime('%B %-d, %Y · %-I:%M %p') }}</time></a>
|
||||
{% if note.updated_at and note.updated_at != note.created_at %}
|
||||
<span class="updated">Updated <time class="dt-updated" datetime="{{ note.updated_at|iso_utc }}">{{ note.updated_at.strftime('%b %-d, %Y') }}</time></span>
|
||||
{% endif %}
|
||||
@@ -79,7 +79,7 @@
|
||||
</footer>
|
||||
|
||||
<div id="responses"></div>
|
||||
{{ responses.reactions(likes, reposts, replies, bookmarks, syndications, absolute_url_for('public.note', slug=note.slug), quotes) }}
|
||||
{{ responses.reactions(likes, reposts, replies, bookmarks, syndications, note.url, quotes) }}
|
||||
|
||||
<nav class="note-nav">
|
||||
<a href="/">← All notes</a>
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<article class="h-entry note-preview">
|
||||
{# Titled notes are articles (ADR-076) #}
|
||||
{% if note.title %}
|
||||
<h2 class="p-name"><a href="{{ absolute_url_for('public.note', slug=note.slug) }}">{{ note.title }}</a></h2>
|
||||
<h2 class="p-name"><a href="{{ note.url }}">{{ note.title }}</a></h2>
|
||||
{% endif %}
|
||||
|
||||
{% if note.in_reply_to %}
|
||||
@@ -25,7 +25,7 @@
|
||||
<p>{{ summary }}</p>
|
||||
</div>
|
||||
{% endif %}
|
||||
<p class="read-more"><a href="{{ absolute_url_for('public.note', slug=note.slug) }}">Read more →</a></p>
|
||||
<p class="read-more"><a href="{{ note.url }}">Read more →</a></p>
|
||||
{% else %}
|
||||
{{ display_media(note.media, note.excerpt|truncate(150)) }}
|
||||
{# Always present, even empty: without it a text-free photo post gets an implied name (mf2) #}
|
||||
@@ -35,13 +35,13 @@
|
||||
{% endif %}
|
||||
|
||||
<footer class="note-meta">
|
||||
<a class="u-url u-uid" href="{{ absolute_url_for('public.note', slug=note.slug) }}"><time class="dt-published" datetime="{{ note.created_at|iso_utc }}">{{ note.created_at.strftime('%b %-d, %Y') }}</time></a>
|
||||
<a class="u-url u-uid" href="{{ note.url }}"><time class="dt-published" datetime="{{ note.created_at|iso_utc }}">{{ note.created_at.strftime('%b %-d, %Y') }}</time></a>
|
||||
{% if note.tags %}
|
||||
<span class="note-tags">
|
||||
{% for tag in note.tags %}<a class="p-category" rel="tag" href="{{ url_for('public.tag', tag=tag.name) }}">{{ tag.display_name }}</a>{% endfor %}
|
||||
</span>
|
||||
{% endif %}
|
||||
{{ list_counts(note.response_counts if note.response_counts is defined else None, absolute_url_for('public.note', slug=note.slug)) }}
|
||||
{{ list_counts(note.response_counts if note.response_counts is defined else None, note.url) }}
|
||||
{% if author %}
|
||||
{# Single-author site: keep the h-card for parsers, hide it from readers #}
|
||||
<span class="p-author h-card visually-hidden"><a class="p-name u-url" href="{{ author.url or author.me }}">{{ author.name or author.url or author.me }}</a></span>
|
||||
|
||||
+85
-5
@@ -38,7 +38,7 @@ class TestFeeds:
|
||||
def test_rss_title_only_for_articles(self, app, client):
|
||||
article, note = make_both(app)
|
||||
items = {i.find("link").text: i for i in ET.fromstring(client.get("/feed.rss").data).iter("item")}
|
||||
a, n = items[f"{SITE}/note/{article.slug}"], items[f"{SITE}/note/{note.slug}"]
|
||||
a, n = items[f"{SITE}/article/{article.slug}"], items[f"{SITE}/note/{note.slug}"]
|
||||
assert a.find("title").text == "An Article"
|
||||
assert "An Article" not in a.find("description").text # not repeated in the body
|
||||
assert n.find("title") is None
|
||||
@@ -48,7 +48,7 @@ class TestFeeds:
|
||||
article, note = make_both(app)
|
||||
entries = {e.find("a:id", ATOM).text: e
|
||||
for e in ET.fromstring(client.get("/feed.atom").data).findall("a:entry", ATOM)}
|
||||
a, n = entries[f"{SITE}/note/{article.slug}"], entries[f"{SITE}/note/{note.slug}"]
|
||||
a, n = entries[f"{SITE}/article/{article.slug}"], entries[f"{SITE}/note/{note.slug}"]
|
||||
assert a.find("a:title", ATOM).text == "An Article"
|
||||
assert a.find("a:summary", ATOM).text == "The gist."
|
||||
assert "An Article" not in a.find("a:content", ATOM).text
|
||||
@@ -58,7 +58,7 @@ class TestFeeds:
|
||||
def test_json_feed(self, app, client):
|
||||
article, note = make_both(app)
|
||||
items = {i["url"]: i for i in json.loads(client.get("/feed.json").data)["items"]}
|
||||
a, n = items[f"{SITE}/note/{article.slug}"], items[f"{SITE}/note/{note.slug}"]
|
||||
a, n = items[f"{SITE}/article/{article.slug}"], items[f"{SITE}/note/{note.slug}"]
|
||||
assert (a["title"], a["summary"]) == ("An Article", "The gist.")
|
||||
assert "An Article" not in a["content_html"]
|
||||
assert "title" not in n and "summary" not in n
|
||||
@@ -68,8 +68,8 @@ class TestFeeds:
|
||||
class TestPages:
|
||||
def test_article_page(self, app, client):
|
||||
article, _ = make_both(app)
|
||||
(entry,) = [i for i in mf2py.parse(doc=client.get(f"/note/{article.slug}").data.decode(),
|
||||
url=f"{SITE}/note/{article.slug}")["items"]
|
||||
(entry,) = [i for i in mf2py.parse(doc=client.get(f"/article/{article.slug}").data.decode(),
|
||||
url=f"{SITE}/article/{article.slug}")["items"]
|
||||
if "h-entry" in i["type"]]
|
||||
props = entry["properties"]
|
||||
assert props["name"] == ["An Article"]
|
||||
@@ -193,3 +193,83 @@ class TestInlineImages:
|
||||
"replace": {"content": [""]}}, headers=h)
|
||||
with app.app_context():
|
||||
assert f"]({SITE}/media/" in get_note(slug=url.rsplit("/", 1)[1]).content
|
||||
|
||||
|
||||
class TestArticleUrls:
|
||||
"""Articles live at /article/<title-slug>, notes at /note/<slug> (v2.17.0)"""
|
||||
|
||||
def test_micropub_article_gets_article_url_from_title(self, app, client, h):
|
||||
url = micropub(client, h, name=["Why I Left Twitter!"], content=["Long story."])
|
||||
assert url == f"{SITE}/article/why-i-left-twitter"
|
||||
assert source(client, h, url)["properties"]["url"] == [url]
|
||||
assert client.get("/article/why-i-left-twitter").status_code == 200
|
||||
|
||||
def test_note_keeps_note_url_and_timestamp_slug(self, app, client, h):
|
||||
url = micropub(client, h, content=["Just a note"])
|
||||
assert url.startswith(f"{SITE}/note/") and url.rsplit("/", 1)[1][:8].isdigit()
|
||||
|
||||
def test_wrong_prefix_redirects(self, app, client, h):
|
||||
article = micropub(client, h, name=["Moved"], content=["Body"])
|
||||
note = micropub(client, h, content=["Plain"])
|
||||
slug, note_slug = article.rsplit("/", 1)[1], note.rsplit("/", 1)[1]
|
||||
response = client.get(f"/note/{slug}")
|
||||
assert (response.status_code, response.location) == (301, f"/article/{slug}")
|
||||
response = client.get(f"/article/{note_slug}")
|
||||
assert (response.status_code, response.location) == (301, f"/note/{note_slug}")
|
||||
assert client.get("/article/no-such-post").status_code == 404
|
||||
|
||||
def test_micropub_accepts_either_url(self, app, client, h):
|
||||
url = micropub(client, h, name=["Either"], content=["Body"])
|
||||
old_style = url.replace("/article/", "/note/")
|
||||
response = client.post("/micropub", json={"action": "update", "url": old_style,
|
||||
"replace": {"summary": ["S"]}}, headers=h)
|
||||
assert response.status_code == 204
|
||||
assert source(client, h, url)["properties"]["summary"] == ["S"]
|
||||
|
||||
def test_title_slugs(self, app):
|
||||
with app.test_request_context():
|
||||
def slug(title, **kw):
|
||||
return create_note(content="Body", title=title, published=True, **kw).slug
|
||||
|
||||
assert slug("Café Culture") == "cafe-culture"
|
||||
assert slug("Café Culture") == "cafe-culture-2"
|
||||
assert slug("Search") == "search-article" # reserved
|
||||
assert slug("Mine", custom_slug="chosen") == "chosen" # mp-slug wins
|
||||
assert slug("🎉🎉").isdigit() # nothing usable: timestamp
|
||||
long = slug("word " * 40)
|
||||
assert len(long) <= 80 and long.endswith("word") and "--" not in long
|
||||
|
||||
def test_update_that_adds_or_removes_title_returns_new_url(self, app, client, h):
|
||||
note = micropub(client, h, content=["Starts as a note"])
|
||||
slug = note.rsplit("/", 1)[1]
|
||||
response = client.post("/micropub", json={"action": "update", "url": note,
|
||||
"replace": {"name": ["Now an Article"]}}, headers=h)
|
||||
assert (response.status_code, response.headers["Location"]) == (201, f"{SITE}/article/{slug}")
|
||||
response = client.post("/micropub", json={"action": "update", "url": f"{SITE}/article/{slug}",
|
||||
"replace": {"content": ["Edited"]}}, headers=h)
|
||||
assert response.status_code == 204 # URL unchanged
|
||||
response = client.post("/micropub", json={"action": "update", "url": f"{SITE}/article/{slug}",
|
||||
"delete": ["name"]}, headers=h)
|
||||
assert (response.status_code, response.headers["Location"]) == (201, f"{SITE}/note/{slug}")
|
||||
|
||||
def test_deleted_article_is_gone(self, app, client, h):
|
||||
url = micropub(client, h, name=["Short-lived"], content=["Body"])
|
||||
assert client.post("/micropub", data={"action": "delete", "url": url}, headers=h).status_code == 204
|
||||
assert client.get("/article/short-lived").status_code == 410
|
||||
|
||||
def test_webmention_target_and_links(self, app, client):
|
||||
article, note = make_both(app)
|
||||
from starpunk.routes.webmention import resolve_target_note
|
||||
with app.test_request_context():
|
||||
assert resolve_target_note(f"{SITE}/article/{article.slug}") == article.id
|
||||
assert resolve_target_note(f"{SITE}/note/{article.slug}") == article.id
|
||||
assert resolve_target_note(f"{SITE}/article/{article.slug}/x") is None
|
||||
html = client.get("/").data.decode()
|
||||
assert f'href="{SITE}/article/{article.slug}"' in html
|
||||
assert f'href="{SITE}/note/{note.slug}"' in html
|
||||
assert f"/note/{article.slug}" not in html
|
||||
|
||||
def test_search_links_to_article(self, app, client):
|
||||
article, _ = make_both(app)
|
||||
results = client.get("/api/search?q=body").get_json()["results"]
|
||||
assert [r["url"] for r in results if r["slug"] == article.slug] == [f"/article/{article.slug}"]
|
||||
@@ -69,9 +69,9 @@ class TestNoteHEntry:
|
||||
published=True
|
||||
)
|
||||
|
||||
response = client.get('/note/note-with-title')
|
||||
response = client.get('/article/note-with-title')
|
||||
assert response.status_code == 200, f"Failed to get note: {response.status_code}"
|
||||
parsed = mf2py.parse(doc=response.data.decode(), url='http://localhost/note/note-with-title')
|
||||
parsed = mf2py.parse(doc=response.data.decode(), url='http://localhost/article/note-with-title')
|
||||
|
||||
entries = [item for item in parsed['items'] if 'h-entry' in item.get('type', [])]
|
||||
assert len(entries) > 0, "No h-entry found in parsed HTML"
|
||||
|
||||
@@ -198,7 +198,7 @@ class TestLifecycle:
|
||||
select_targets(note.id, ["bluesky"])
|
||||
process_due()
|
||||
record = only_record(pds)
|
||||
permalink = f"https://blog.example.com/note/{note.slug}"
|
||||
permalink = f"https://blog.example.com/article/{note.slug}"
|
||||
assert record["text"] == f"My Article\n\nThe gist.\n\n{permalink}"
|
||||
assert record["embed"]["external"] == {
|
||||
"uri": permalink, "title": "My Article", "description": "The gist."}
|
||||
|
||||
Reference in new issue
Block a user