From b7f8e1612c0a3daa038cc7af8500a444d5017cac Mon Sep 17 00:00:00 2001 From: Phil Date: Thu, 12 Nov 2026 12:27:31 -0700 Subject: [PATCH] feat: articles at /article/ with slugs from their titles (v2.17.0, ADR-077) Articles (notes with a title) move from /note/ to /article/; the other prefix 301-redirects. New articles take their slug from the title (mp-slug still wins; notes keep timestamp slugs). A Micropub update that adds or removes a title answers 201 with the new Location. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 10 +++ .../ADR-062-timestamp-based-slug-format.md | 2 +- .../ADR-076-note-title-and-summary-columns.md | 2 + .../ADR-077-article-urls-and-title-slugs.md | 46 ++++++++++ docs/decisions/INDEX.md | 9 +- .../design/v2.17.0/2026-11-12-article-urls.md | 23 +++++ starpunk/__init__.py | 4 +- starpunk/backfeed.py | 7 +- starpunk/mcp_server/tools.py | 16 ++-- starpunk/micropub.py | 13 ++- starpunk/models.py | 25 ++++-- starpunk/notes.py | 13 +-- starpunk/notifications.py | 6 +- starpunk/routes/public.py | 26 +++++- starpunk/routes/search.py | 5 +- starpunk/routes/webmention.py | 7 +- starpunk/search.py | 3 + starpunk/slug_utils.py | 29 ++++++ starpunk/syndication.py | 2 +- starpunk/utils.py | 10 +++ templates/admin/dashboard.html | 2 +- templates/note.html | 4 +- templates/partials/note_preview.html | 8 +- tests/test_articles.py | 90 +++++++++++++++++-- tests/test_microformats.py | 4 +- tests/test_syndication_bluesky.py | 2 +- 26 files changed, 308 insertions(+), 60 deletions(-) create mode 100644 docs/decisions/ADR-077-article-urls-and-title-slugs.md create mode 100644 docs/design/v2.17.0/2026-11-12-article-urls.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b97e62..ec7276a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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/` instead of `/note/`. 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). diff --git a/docs/decisions/ADR-062-timestamp-based-slug-format.md b/docs/decisions/ADR-062-timestamp-based-slug-format.md index 13672cf..2f220ab 100644 --- a/docs/decisions/ADR-062-timestamp-based-slug-format.md +++ b/docs/decisions/ADR-062-timestamp-based-slug-format.md @@ -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 diff --git a/docs/decisions/ADR-076-note-title-and-summary-columns.md b/docs/decisions/ADR-076-note-title-and-summary-columns.md index bcf6f47..858a9d6 100644 --- a/docs/decisions/ADR-076-note-title-and-summary-columns.md +++ b/docs/decisions/ADR-076-note-title-and-summary-columns.md @@ -4,6 +4,8 @@ Accepted (v2.16.0, 2026-11-11) +Article URLs (`/article/`) 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`). diff --git a/docs/decisions/ADR-077-article-urls-and-title-slugs.md b/docs/decisions/ADR-077-article-urls-and-title-slugs.md new file mode 100644 index 0000000..57771b8 --- /dev/null +++ b/docs/decisions/ADR-077-article-urls-and-title-slugs.md @@ -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/` 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/`, other notes at `/note/`. + `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/` for an article and + `/article/` 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. diff --git a/docs/decisions/INDEX.md b/docs/decisions/INDEX.md index fcebdc8..885da74 100644 --- a/docs/decisions/INDEX.md +++ b/docs/decisions/INDEX.md @@ -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/` 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): diff --git a/docs/design/v2.17.0/2026-11-12-article-urls.md b/docs/design/v2.17.0/2026-11-12-article-urls.md new file mode 100644 index 0000000..5d5ad3d --- /dev/null +++ b/docs/design/v2.17.0/2026-11-12-article-urls.md @@ -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/`; `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. diff --git a/starpunk/__init__.py b/starpunk/__init__.py index 4596854..f6180fc 100644 --- a/starpunk/__init__.py +++ b/starpunk/__init__.py @@ -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) diff --git a/starpunk/backfeed.py b/starpunk/backfeed.py index 83cd924..5aef907 100644 --- a/starpunk/backfeed.py +++ b/starpunk/backfeed.py @@ -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)) diff --git a/starpunk/mcp_server/tools.py b/starpunk/mcp_server/tools.py index 71c2d3e..3180c94 100644 --- a/starpunk/mcp_server/tools.py +++ b/starpunk/mcp_server/tools.py @@ -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"} diff --git a/starpunk/micropub.py b/starpunk/micropub.py index 73df389..8407334 100644 --- a/starpunk/micropub.py +++ b/starpunk/micropub.py @@ -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/ on this site)""" + """Find the note a URL points at (/note/ or /article/ 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: diff --git a/starpunk/models.py b/starpunk/models.py index e8f1fb8..7e30374 100644 --- a/starpunk/models.py +++ b/starpunk/models.py @@ -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: diff --git a/starpunk/notes.py b/starpunk/notes.py index 2e16416..4c8cdf3 100644 --- a/starpunk/notes.py +++ b/starpunk/notes.py @@ -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 diff --git a/starpunk/notifications.py b/starpunk/notifications.py index 77d4587..5d35d52 100644 --- a/starpunk/notifications.py +++ b/starpunk/notifications.py @@ -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 diff --git a/starpunk/routes/public.py b/starpunk/routes/public.py index 68f3fe2..ea7d79f 100644 --- a/starpunk/routes/public.py +++ b/starpunk/routes/public.py @@ -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/") 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/") +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) diff --git a/starpunk/routes/search.py b/starpunk/routes/search.py index 7d9963b..69b89a5 100644 --- a/starpunk/routes/search.py +++ b/starpunk/routes/search.py @@ -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 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: diff --git a/starpunk/routes/webmention.py b/starpunk/routes/webmention.py index c320571..96f67f7 100644 --- a/starpunk/routes/webmention.py +++ b/starpunk/routes/webmention.py @@ -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) diff --git a/starpunk/search.py b/starpunk/search.py index c2b62c7..c080e9f 100644 --- a/starpunk/search.py +++ b/starpunk/search.py @@ -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 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']), diff --git a/starpunk/slug_utils.py b/starpunk/slug_utils.py index d89c9bb..2c4e11f 100644 --- a/starpunk/slug_utils.py +++ b/starpunk/slug_utils.py @@ -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 diff --git a/starpunk/syndication.py b/starpunk/syndication.py index f9c8521..f15b952 100644 --- a/starpunk/syndication.py +++ b/starpunk/syndication.py @@ -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) diff --git a/starpunk/utils.py b/starpunk/utils.py index 4eed0fe..38173b7 100644 --- a/starpunk/utils.py +++ b/starpunk/utils.py @@ -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/ when it has a title, else /note/ (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) diff --git a/templates/admin/dashboard.html b/templates/admin/dashboard.html index c76a576..d48b3a1 100644 --- a/templates/admin/dashboard.html +++ b/templates/admin/dashboard.html @@ -67,7 +67,7 @@ {% if note.published %} - + View {% endif %} diff --git a/templates/note.html b/templates/note.html index b625cc3..651d0b2 100644 --- a/templates/note.html +++ b/templates/note.html @@ -54,7 +54,7 @@
- {{ 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) }}