An API client for ipx, and its event stream (#1)

Everything native needs this first, and it is worth having whatever happens
to the rest: a CarPlay browse tree is built from exactly these calls.

API covers what a client reads and writes -- feeds, entries with the
server's own paging, filtering, sorting and search, read and pinned,
position, read-all, download, delete, fetch -- and APIModels is what ipx
sends, with the server's field names kept so a type here can be checked
against web.rs without translating first. It sends nothing of its own to
authenticate: ipx decides who is asking by cookie and CookieBridge keeps
HTTPCookieStorage in step, which is the same property that lets a plain
<audio src> work.

Events reads /api/events with URLSession's byte stream, so there is no new
dependency. An event this build has never heard of decodes as .other rather
than throwing, because a new one on the server must not stop the stream. It
reconnects with a backoff: a deploy closes the stream cleanly and should be
picked straight back up, a daemon that is down should not be hammered.

Library is gone, folded into API. Two clients writing positions was one too
many, and the page's forwarded beacon no longer carries a path: it asks the
host to save, and the host uses its own clock, which is the only one not
stale when the web view has been frozen in the background.

The tests run against the browser suite's fixture daemon rather than canned
JSON, because the shapes being decoded are the server's and a fixture would
only prove it matches itself. Thirteen pass, including a live scan reported
over SSE and the playback round trip, which still works after the move.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-19 22:48:14 -04:00
parent aa91b457bb
commit f88ae657f3
11 changed files with 652 additions and 101 deletions

168
ios/Sources/API.swift Normal file
View File

@@ -0,0 +1,168 @@
import Foundation
import UIKit
/// ipx's HTTP API.
///
/// It sends nothing of its own to authenticate: ipx decides who is asking by cookie, and
/// CookieBridge keeps HTTPCookieStorage in step with the web view's store. That is deliberate --
/// the auth layer was written so a plain `<audio src>` would work, and it is why no API of our
/// own is needed.
actor API {
enum Failure: LocalizedError {
case notSignedIn
case noServer
case http(Int)
case transport(Error)
var errorDescription: String? {
switch self {
case .notSignedIn: return "Sign in again"
case .noServer: return "No server is set"
case .http(let code): return "The server answered \(code)"
case .transport(let e): return e.localizedDescription
}
}
}
private let session: URLSession
private let decoder = JSONDecoder()
init() {
let cfg = URLSessionConfiguration.default
cfg.httpCookieStorage = HTTPCookieStorage.shared
cfg.httpShouldSetCookies = true
cfg.waitsForConnectivity = true
// A list is worth waiting a few seconds for; it is not worth a minute.
cfg.timeoutIntervalForRequest = 20
self.session = URLSession(configuration: cfg)
}
// MARK: - reading
func me() async throws -> IPX.Me { try await get("/api/me") }
func feeds() async throws -> [IPX.Feed] { try await get("/api/feeds") }
/// One feed's items, or every subscribed feed's when `feed` is nil (All Subscriptions).
/// The sorting, filtering and searching are the server's; it pages fifty at a time.
func entries(feed: String? = nil,
filter: IPX.Filter = .all,
search: String? = nil,
sort: IPX.Sort = .published,
direction: IPX.Direction = .desc,
offset: Int = 0,
limit: Int = 50) async throws -> IPX.EntryPage {
var items = [
URLQueryItem(name: "filter", value: filter.rawValue),
URLQueryItem(name: "sort", value: sort.rawValue),
URLQueryItem(name: "dir", value: direction.rawValue),
URLQueryItem(name: "offset", value: String(offset)),
// The server clamps this to 200; asking for more is not an error, just pointless.
URLQueryItem(name: "limit", value: String(min(limit, 200))),
]
if let search, !search.trimmingCharacters(in: .whitespaces).isEmpty {
items.append(URLQueryItem(name: "q", value: search))
}
let path = feed.map { "/api/feeds/\(esc($0))/entries" } ?? "/api/entries"
return try await get(path, query: items)
}
// MARK: - writing
func setRead(_ read: Bool, feed: String, guid: String) async throws {
try await send("/api/entries/\(esc(feed))/\(esc(guid))/flags", ["read": read])
}
func setPinned(_ pinned: Bool, feed: String, guid: String) async throws {
// `flagged` is the column's name from before it was called pinned in the interface.
try await send("/api/entries/\(esc(feed))/\(esc(guid))/flags", ["flagged": pinned])
}
func setPosition(secs: Int, duration: Int?, feed: String, guid: String) async throws {
var body: [String: Any] = ["secs": secs]
// Left out rather than sent as null when there is none: it is Option<i64> either way.
if let duration { body["duration"] = duration }
try await send("/api/entries/\(esc(feed))/\(esc(guid))/position", body)
}
func readAll(feed: String?) async throws {
try await send(feed.map { "/api/feeds/\(esc($0))/read-all" } ?? "/api/read-all", [:])
}
func download(enclosure id: Int) async throws {
try await send("/api/enclosures/\(id)/download", [:])
}
/// `force` overrides the warning that the file is shared with other subscribers.
func deleteFile(enclosure id: Int, force: Bool = false) async throws {
try await send("/api/enclosures/\(id)", [:], method: "DELETE",
query: force ? [URLQueryItem(name: "force", value: "true")] : [])
}
func fetch(feed: String? = nil) async throws {
try await send("/api/fetch", feed.map { ["feed": $0] } ?? [:])
}
// MARK: - bytes
/// Artwork, or any image the feed named. Returns nil rather than throwing: a missing
/// picture is not a failure worth interrupting anything for.
func image(_ path: String) async -> UIImage? {
guard let url = ServerSettings.url(path),
let (data, _) = try? await session.data(from: url) else { return nil }
return UIImage(data: data)
}
// MARK: - plumbing
private func get<T: Decodable>(_ path: String, query: [URLQueryItem] = []) async throws -> T {
let data = try await body(for: try request(path, query: query))
do {
return try decoder.decode(T.self, from: data)
} catch {
throw Failure.transport(error)
}
}
private func send(_ path: String, _ json: [String: Any],
method: String = "POST", query: [URLQueryItem] = []) async throws {
var req = try request(path, query: query)
req.httpMethod = method
if !json.isEmpty {
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.httpBody = try? JSONSerialization.data(withJSONObject: json)
}
_ = try await body(for: req)
}
private func request(_ path: String, query: [URLQueryItem]) throws -> URLRequest {
guard let base = ServerSettings.url(path) else { throw Failure.noServer }
var components = URLComponents(url: base, resolvingAgainstBaseURL: false)
if !query.isEmpty { components?.queryItems = query }
guard let url = components?.url else { throw Failure.noServer }
var req = URLRequest(url: url)
// Without this ipx redirects a browser-looking request to /login and we decode HTML.
req.setValue("application/json", forHTTPHeaderField: "Accept")
return req
}
private func body(for req: URLRequest) async throws -> Data {
let data: Data, response: URLResponse
do {
(data, response) = try await session.data(for: req)
} catch {
throw Failure.transport(error)
}
guard let http = response as? HTTPURLResponse else { return data }
switch http.statusCode {
case 200..<300: return data
// 401 is the one worth naming: the Access cookie expired and only a sign-in fixes it.
case 401, 403: throw Failure.notSignedIn
default: throw Failure.http(http.statusCode)
}
}
private nonisolated func esc(_ s: String) -> String {
s.addingPercentEncoding(withAllowedCharacters: .alphanumerics.union(.init(charactersIn: "-._~"))) ?? s
}
}