Files
museion/Museion/MicropubMedia.swift
T
AlexKucera 6db4cf8cf1 feat(microblog): set and create categories
A piece's `category:` frontmatter line now travels to Micro.blog: a
first send carries the list beside title and content, and a re-send
replaces the post's categories with exactly the piece's list — only
when the piece has the line (opt-in by key; `[]` clears; no line
leaves the blog's). Naming a category Micro.blog doesn't know creates
it there, so there is no separate create step.

The publish sheet gains a Categories field: a comma list with the
system completion menu over the blog's own categories. The system
replaces the whole field text with a completion, so the completion is
the merge — a pick adds, a half-typed last word is replaced. The edit
lands on the piece at the send (a failed write refuses with nothing
on the wire); Publish with a pending edit applies it first and flips
the post that send touched.

The one-line codec lives in PostFrontmatter (line-bounded; backslashes
and quotes escaped; a Set de-duplicates). Import keeps an imported
`category:` line — the writer's classification, unlike the micropub
bookkeeping keys.

Reviewed twice (two-axis during the build, finish-audit after): the
stale pending baseline after a failed step, the backslash round-trip,
and the publish targeting the caller's possibly-stale URL were found
and fixed before this commit. 39 of the 40 new or changed pins were
watched fail on their own guard. Rail 791/791; SwiftFormat and
SwiftLint clean.

Docs: AGENTS.md bullets and learnings, the GLOSSARY term, CHANGELOG
[Unreleased], PRD S6.1, the devlog, and the swift wiki (text
completion is a whole-text contract).

Closes #207
2026-12-05 08:09:57 +01:00

254 lines
11 KiB
Swift

//
// MicropubMedia.swift
// Museion
//
// #34 (S6.2): illustrations travel with it. Ink-sketch PNGs in the
// piece's assets/ upload and travel INLINE: q=config names the media
// endpoint, the PNG rides a multipart POST, and each `assets/` ref
// REWRITES in place with its uploaded URL — the image renders exactly
// where the writer placed it, alt travels in the markdown (a photo
// PROPERTY would render wherever the theme decides — live-verified
// 2026-11-01: bottom of the post, position lost). The FLOOR (G12):
// no photo ships without alt text — the only gate; style judgment
// stays with the author and the mentor NEVER assesses images
// (nothing here consults the engine).
//
// Wire facts (microblog.dev/api/posting, book.micro.blog/micropub):
// `GET /micropub?q=config` carries `media-endpoint`;
// `POST <media-endpoint>` multipart → 202 + Location = upload URL.
// #206: the upload memo — an image whose bytes uploaded before rides
// that URL again (`.museion-uploads.json` in the piece folder).
//
import CryptoKit
import Foundation
nonisolated extension Micropub {
/// One illustration ref in the body: `![alt](assets/…)`.
struct Illustration: Equatable {
/// Verbatim bracket text — the parse never hides a ref; the
/// floor (trimmed emptiness) is the model's call.
let alt: String
/// The ref's destination as written, always `assets/`-rooted.
let destination: String
}
/// A media-step result: the URL (the config-named endpoint, or an
/// upload's Location) or the failure outcome to surface as-is.
enum MediaResult: Equatable {
case url(String)
case failed(Outcome)
}
// MARK: Parsing the body (G12: plain image refs into assets/)
/// Every `assets/` image ref in the body — the only images Museion
/// uploads. Remote http(s) refs ride as prose (not ours to upload),
/// and refs rooted elsewhere stay put. Ceiling (ponytail): the
/// plain paren form; a destination containing spaces (the
/// `<(assets/my ink.png)>` form) doesn't match and rides verbatim —
/// never uploaded, never gated. No fence scan either: an
/// illustration ref inside a code fence is not corpus reality.
static func illustrations(in body: String) -> [Illustration] {
guard let regex = illustrationRegex else { return [] }
let scanner = body as NSString
return regex.matches(in: body, range: NSRange(location: 0, length: scanner.length)).map { match in
Illustration(
alt: scanner.substring(with: match.range(at: 1)),
destination: scanner.substring(with: match.range(at: 2)),
)
}
}
/// The wire content: the body with each uploaded illustration ref
/// REWRITTEN in place with its uploaded URL — position is the
/// writer's, so the image renders exactly where placed and the alt
/// travels in the markdown. A ref with no upload in the map (and
/// every untouched line) rides byte-identical. The piece on disk
/// is never modified.
static func rewritingIllustrations(_ body: String, uploaded: [String: String]) -> String {
guard let regex = illustrationRegex else { return body }
let scanner = body as NSString
let matches = regex.matches(in: body, range: NSRange(location: 0, length: scanner.length))
var result = ""
var cursor = 0
for match in matches {
guard let url = uploaded[scanner.substring(with: match.range(at: 2))] else { continue }
result += scanner.substring(with: NSRange(location: cursor, length: match.range.location - cursor))
// Alt rides verbatim from the match; a quoted title drops
// (it never parsed into the Illustration either). The
// destination rides the ANGLE form when the URL carries
// markdown-active characters — a plain-paren dest would
// close at the first `)` and smuggle a live attacker link
// into the published post (the trustworthyURL gate was
// built for line-bounded frontmatter, not this sink).
let active = url.rangeOfCharacter(from: CharacterSet(charactersIn: "()<> \t")) != nil
let dest = active ? "<\(url)>" : url
result += "![\(scanner.substring(with: match.range(at: 1)))](\(dest))"
cursor = match.range.location + match.range.length
}
guard cursor > 0 else { return body } // nothing rewritten
return result + scanner.substring(from: cursor)
}
/// The upload's content type — exactly the formats Micro.blog's
/// media endpoint accepts. Anything else refuses honestly; no
/// guessed content type ever ships.
static func mimeType(forDestination destination: String) -> String? {
switch URL(fileURLWithPath: destination).pathExtension.lowercased() {
case "png": "image/png"
case "jpg", "jpeg": "image/jpeg"
case "gif": "image/gif"
case "webp": "image/webp"
case "svg": "image/svg+xml"
default: nil
}
}
// MARK: q=config (hop 1)
static func makeConfigRequest(token: String) -> URLRequest {
queryRequest("config", token: token)
}
/// The one `GET <endpoint>?q=…` shape (#34's config query, #207's
/// category list): the fixed endpoint, Bearer token, 30 s.
static func queryRequest(_ q: String, token: String) -> URLRequest {
var components = URLComponents(url: endpoint, resolvingAgainstBaseURL: false)!
components.queryItems = [URLQueryItem(name: "q", value: q)]
var request = URLRequest(url: components.url!)
request.timeoutInterval = 30
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
return request
}
/// Ask the endpoint where media goes. The discovered endpoint is
/// trust-boundary data — the writer's PNG and token POST to it —
/// so it passes the same format gate as the draft URL.
static func mediaEndpoint(token: String, transport: Transport = urlSessionTransport) async -> MediaResult {
do {
let (data, response) = try await transport(makeConfigRequest(token: token))
guard (200 ..< 300).contains(response.statusCode) else {
return .failed(decodeFailure(status: response.statusCode, body: data))
}
let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]
guard let raw = root["media-endpoint"] as? String, trustworthyURL(raw) else {
return .failed(.requestFailed(status: response.statusCode, detail: "no trustworthy media endpoint in q=config"))
}
return .url(raw)
} catch {
return .failed(.unreachable(error.localizedDescription))
}
}
// MARK: The multipart upload (hop 2)
static func makeMediaUploadRequest(
mediaEndpoint: String,
filename: String,
mimeType: String,
data: Data,
token: String,
) -> URLRequest {
let boundary = "museion-\(UUID().uuidString)"
// The filename rides a Content-Disposition header — quotes and
// control characters can never break out of it.
let safeFilename = filename.filter { $0 != "\"" && !$0.isNewline && !($0.asciiValue.map { $0 < 0x20 } ?? false) }
var request = URLRequest(url: URL(string: mediaEndpoint)!)
request.httpMethod = "POST"
request.timeoutInterval = 60
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
var body = Data()
body.append(Data("--\(boundary)\r\n".utf8))
body.append(Data("Content-Disposition: form-data; name=\"file\"; filename=\"\(safeFilename)\"\r\n".utf8))
body.append(Data("Content-Type: \(mimeType)\r\n\r\n".utf8))
body.append(data)
body.append(Data("\r\n--\(boundary)--\r\n".utf8))
request.httpBody = body
return request
}
/// Upload one file to the media endpoint. The decode mirrors the
/// create's: Location header first, body `url` second, every URL
/// trust-gated — a 2xx with no trustworthy URL is a failure, never
/// a silent success.
static func uploadMedia(
mediaEndpoint: String,
filename: String,
mimeType: String,
data: Data,
token: String,
transport: Transport = urlSessionTransport,
) async -> MediaResult {
do {
let (body, response) = try await transport(makeMediaUploadRequest(
mediaEndpoint: mediaEndpoint,
filename: filename,
mimeType: mimeType,
data: data,
token: token,
))
guard (200 ..< 300).contains(response.statusCode) else {
return .failed(decodeFailure(status: response.statusCode, body: body))
}
let root = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any] ?? [:]
let url = response.value(forHTTPHeaderField: "Location") ?? root["url"] as? String
guard let url, trustworthyURL(url) else {
return .failed(.requestFailed(status: response.statusCode, detail: "no trustworthy upload URL in the response"))
}
return .url(url)
} catch {
return .failed(.unreachable(error.localizedDescription))
}
}
// MARK: #206 — the upload memo (a re-send never re-uploads)
/// `.museion-uploads.json` in the piece folder — the cursor
/// sidecar's posture: Finder-invisible, dies with the folder.
static let uploadMemoFile = ".museion-uploads.json"
/// The memo's key: the asset's exact bytes. Rename the file or
/// rewrite the alt and it is still the same upload; change one byte
/// and it uploads fresh.
static func uploadKey(_ data: Data) -> String {
SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
}
/// `uploadKey → uploaded URL`. Disk is external data: a symlinked
/// memo never reads (the rail's planted-link posture) and only
/// trustworthy URLs come back — a memo URL lands in published
/// content. ponytail: an upload deleted on Micro.blog stays memoized
/// (a dead image URL) until the sidecar is removed; no liveness probe.
static func readUploadMemo(in pieceFolder: URL) -> [String: String] {
let url = pieceFolder.appendingPathComponent(uploadMemoFile)
guard let values = try? url.resourceValues(forKeys: [.isSymbolicLinkKey]),
values.isSymbolicLink != true,
let data = try? Data(contentsOf: url)
else { return [:] }
let memo = (try? JSONDecoder().decode([String: String].self, from: data)) ?? [:]
return memo.filter { trustworthyURL($1) }
}
/// Best-effort, like the cursor sidecar: a failed memo write only
/// costs a re-upload, never a send.
static func writeUploadMemo(_ memo: [String: String], in pieceFolder: URL) {
let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys // a stable file: no churn across sends or syncs
guard let data = try? encoder.encode(memo) else { return }
try? data.write(to: pieceFolder.appendingPathComponent(uploadMemoFile), options: .atomic)
}
/// The one illustration-ref pattern both passes share (the parse
/// and the rewrite can never drift). The alt class is single-line
/// (`[^\]\n]*`) on purpose: a ref whose alt spans lines must NOT
/// parse — it rides as prose, never uploaded, never rewritten (a
/// parsed-but-unrewritten ref would ship a broken relative link).
/// A `let` — the pattern is compile-constant; compiling it per
/// access was the only cost.
private static let illustrationRegex = try? NSRegularExpression(
pattern: #"!\[([^\]\n]*)\]\((assets/[^\s)]+)(?:\s+"[^"]*")?\)"#,
)
}