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
}
}

140
ios/Sources/APIModels.swift Normal file
View File

@@ -0,0 +1,140 @@
import Foundation
/// What ipx sends, as Swift types. The names are the server's, so a field here can be checked
/// against src/web.rs without translating first.
enum IPX {}
extension IPX {
/// One subscribed feed, as GET /api/feeds sends it.
struct Feed: Decodable, Identifiable, Hashable {
let id: String
let url: String
let title: String?
let image: String?
/// The OPML subscription it came from, if any. Feeds in one are drawn as a folder.
let group: String?
/// In a group, but the OPML no longer lists it. Kept because it has downloads.
let orphaned: Bool
let folder: String?
let category: String?
let feedCategory: String?
let lastChecked: Int?
let nextCheck: Int?
let lastError: String?
let entries: Int
let downloaded: Int
let unread: Int
/// Including you. More than one means every file here is shared.
let subscribers: Int
let pinned: Bool
var name: String { title?.isEmpty == false ? title! : id }
enum CodingKeys: String, CodingKey {
case id, url, title, image, group, orphaned, folder, category, entries, downloaded,
unread, subscribers, pinned
case feedCategory = "feed_category"
case lastChecked = "last_checked"
case nextCheck = "next_check"
case lastError = "last_error"
}
}
/// A file on an entry. `path` is the only thing that says it is downloaded.
struct Enclosure: Decodable, Identifiable, Hashable {
let id: Int
let feedId: String
let guid: String
let url: String
let mime: String?
let length: Int?
let path: String?
let state: String
let lastError: String?
var isDownloaded: Bool { path?.isEmpty == false }
/// Whether it is worth handing to a player. Having a file is not the same as being
/// playable: blog feeds put article images in enclosures.
var isPlayable: Bool {
guard isDownloaded else { return false }
let m = (mime ?? "").lowercased()
if m.hasPrefix("audio/") || m.hasPrefix("video/") { return true }
if !m.isEmpty { return false }
let name = (path ?? url).split(separator: "?").first.map(String.init) ?? ""
let ext = (name as NSString).pathExtension.lowercased()
return ["mp3","m4a","m4b","aac","ogg","oga","opus","flac","wav",
"mp4","m4v","mov","webm","mkv"].contains(ext)
}
var isVideo: Bool { (mime ?? "").lowercased().hasPrefix("video/") }
enum CodingKeys: String, CodingKey {
case id, guid, url, mime, length, path, state
case feedId = "feed_id"
case lastError = "last_error"
}
}
/// One item. Read, pinned and position are this person's; the entry itself is shared.
struct Entry: Decodable, Identifiable, Hashable {
let guid: String
let feedId: String
let title: String?
let link: String?
let published: Int?
/// Feed-supplied HTML, already sanitized with ammonia server-side.
let description: String?
let read: Bool
let flagged: Bool
let image: String?
let duration: Int?
let episode: Int?
let season: Int?
let position: Int
let enclosures: [Enclosure]
/// Unique across feeds; guid alone is not.
var id: String { feedId + "\n" + guid }
var playable: Enclosure? { enclosures.first(where: \.isPlayable) }
enum CodingKeys: String, CodingKey {
case guid, title, link, published, description, read, flagged, image, duration,
episode, season, position, enclosures
case feedId = "feed_id"
}
}
/// A page of items. `total` is the whole result, not the page.
struct EntryPage: Decodable {
let total: Int
let entries: [Entry]
}
struct Me: Decodable {
let name: String
let admin: Bool
/// Where to send someone the proxy signed in; signing out of ipx alone cannot stick.
let signOut: String?
let theme: String?
let mode: String?
enum CodingKeys: String, CodingKey {
case name, admin, theme, mode
case signOut = "sign_out"
}
}
/// Which items to ask for. The server does the work; these go on the query.
enum Filter: String, CaseIterable {
case all, unread, downloaded, pinned
}
enum Sort: String {
case published, title, feed, kept, type, size
}
enum Direction: String {
case asc, desc
}
}

View File

@@ -67,7 +67,9 @@ final class Bridge: NSObject, WKScriptMessageHandler {
case "rate": if let v = m["v"] as? Double { playback.setRate(Float(v)) }
case "volume": if let v = m["v"] as? Double { playback.setVolume(Float(v)) }
case "stop": playback.stop()
case "position": playback.savePosition(path: m["url"] as? String)
// The page sends the path it would have written to; we save against the item we
// are playing instead, because our clock is the one that is not stale.
case "position": playback.savePosition()
default: break
}
}

126
ios/Sources/Events.swift Normal file
View File

@@ -0,0 +1,126 @@
import Foundation
/// What the daemon is doing, as it does it.
///
/// `GET /api/events` is server-sent events carrying the same broadcast the control socket does,
/// so a scan started from anywhere shows up here. The stream is a broadcast: a client attached
/// to a busy daemon also sees that daemon's other work.
enum IPXEvent: Decodable, Sendable {
case feedStart(feed: String)
case feedSkip(feed: String, reason: String)
case feedDone(feed: String, new: Int, downloaded: Int, failed: Int)
case feedError(feed: String, msg: String)
/// Carries the enclosure id, without which a UI cannot tell one download from another and
/// ends up animating every pending row. Throttled to whole percents by the server.
case progress(feed: String, enclosure: Int, file: String, done: Int, total: Int?)
case downloadDone(feed: String, enclosure: Int, path: String, bytes: Int)
case downloadError(feed: String, enclosure: Int, msg: String)
case reaped(path: String, bytes: Int)
case scanDone(feeds: Int)
case reapDone(files: Int, bytes: Int)
/// Anything this build does not know about. New events must not break an old app.
case other(String)
private enum Keys: String, CodingKey {
case ev, feed, reason, new, downloaded, failed, msg, enclosure, file, done, total,
path, bytes, feeds, files
}
init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: Keys.self)
let ev = try c.decode(String.self, forKey: .ev)
func str(_ k: Keys) -> String { (try? c.decode(String.self, forKey: k)) ?? "" }
func int(_ k: Keys) -> Int { (try? c.decode(Int.self, forKey: k)) ?? 0 }
switch ev {
case "feed_start": self = .feedStart(feed: str(.feed))
case "feed_skip": self = .feedSkip(feed: str(.feed), reason: str(.reason))
case "feed_done": self = .feedDone(feed: str(.feed), new: int(.new),
downloaded: int(.downloaded), failed: int(.failed))
case "feed_error": self = .feedError(feed: str(.feed), msg: str(.msg))
case "progress": self = .progress(feed: str(.feed), enclosure: int(.enclosure),
file: str(.file), done: int(.done),
total: try? c.decode(Int.self, forKey: .total))
case "download_done": self = .downloadDone(feed: str(.feed), enclosure: int(.enclosure),
path: str(.path), bytes: int(.bytes))
case "download_error": self = .downloadError(feed: str(.feed), enclosure: int(.enclosure),
msg: str(.msg))
case "reaped": self = .reaped(path: str(.path), bytes: int(.bytes))
case "scan_done": self = .scanDone(feeds: int(.feeds))
case "reap_done": self = .reapDone(files: int(.files), bytes: int(.bytes))
default: self = .other(ev)
}
}
}
/// Reads the event stream and keeps reading it.
///
/// URLSession's byte stream does the parsing work; there is no need for another dependency.
/// The connection drops -- a deploy, a sleeping laptop, a tunnel blinking -- so it reconnects,
/// backing off so a daemon that is down is not hammered.
@MainActor
final class Events {
private(set) var isConnected = false
private var task: Task<Void, Never>?
private var handlers: [UUID: (IPXEvent) -> Void] = [:]
/// Returns a token; hold it for as long as you want the events, and forget it to stop.
@discardableResult
func onEvent(_ handler: @escaping (IPXEvent) -> Void) -> UUID {
let id = UUID()
handlers[id] = handler
return id
}
func remove(_ id: UUID) { handlers[id] = nil }
func start() {
guard task == nil else { return }
task = Task { [weak self] in
var backoff = 1.0
while !Task.isCancelled {
let ok = await self?.readOnce() ?? false
if Task.isCancelled { return }
// A clean end means the daemon closed it, which is normal on a deploy: try again
// soon. A failure means it is down, so wait longer each time, up to half a minute.
backoff = ok ? 1.0 : min(backoff * 2, 30)
try? await Task.sleep(nanoseconds: UInt64(backoff * 1_000_000_000))
}
}
}
func stop() {
task?.cancel()
task = nil
isConnected = false
}
/// One connection, for as long as it lasts. True if it ended rather than failed.
private func readOnce() async -> Bool {
guard let url = ServerSettings.url("/api/events") else { return false }
var req = URLRequest(url: url)
req.setValue("text/event-stream", forHTTPHeaderField: "Accept")
// The stream is meant to stay open; the default timeout would cut it every minute.
req.timeoutInterval = .infinity
do {
let (bytes, response) = try await URLSession.shared.bytes(for: req)
guard (response as? HTTPURLResponse)?.statusCode == 200 else { return false }
isConnected = true
defer { isConnected = false }
for try await line in bytes.lines {
if Task.isCancelled { return true }
// Every event ipx sends is unnamed, so the data lines are the whole of it.
// Comments (": keep-alive") and blank separators are skipped.
guard line.hasPrefix("data:") else { continue }
let json = line.dropFirst(5).trimmingCharacters(in: .whitespaces)
guard let data = json.data(using: .utf8),
let event = try? JSONDecoder().decode(IPXEvent.self, from: data) else { continue }
for handler in handlers.values { handler(event) }
}
return true
} catch {
return false
}
}
}

View File

@@ -1,79 +0,0 @@
import Foundation
import UIKit
/// The bits of ipx's API the native side writes back to, and the artwork it shows.
///
/// Small on purpose. The page does the browsing; this is only what the host has to do when the
/// page cannot -- which is any time the screen is locked, and all the time in CarPlay.
final class Library {
private let cookies: CookieBridge
private let session: URLSession
init(cookies: CookieBridge) {
self.cookies = cookies
let cfg = URLSessionConfiguration.default
cfg.httpCookieStorage = HTTPCookieStorage.shared
cfg.httpShouldSetCookies = true
cfg.waitsForConnectivity = true
self.session = URLSession(configuration: cfg)
}
struct Unauthorized: Error {}
/// Where you are in an episode. The page sends this too, but only while it is running:
/// a backgrounded web view is frozen, and this is the drive it would miss.
func savePosition(feedId: String, guid: String, secs: Int, duration: Int?) {
post("/api/entries/\(esc(feedId))/\(esc(guid))/position", position(secs, duration))
}
func markRead(feedId: String, guid: String) {
post("/api/entries/\(esc(feedId))/\(esc(guid))/flags", ["read": true])
}
/// A path the page handed over, used as-is. It already names the right item, and rebuilding it
/// here would be a second place for the escaping to be wrong.
func savePosition(path: String, secs: Int, duration: Int?) {
post(path, position(secs, duration))
}
/// `duration` is left out when there is none rather than sent as null: it is Option<i64> on
/// the server either way, and `duration as Any` on a nil Optional is an Any wrapping nil,
/// which JSONSerialization refuses -- leaving the request with no body at all.
private func position(_ secs: Int, _ duration: Int?) -> [String: Any] {
var body: [String: Any] = ["secs": secs]
if let duration { body["duration"] = duration }
return body
}
func artwork(_ path: String, done: @escaping (UIImage?) -> Void) {
guard let url = ServerSettings.url(path) else { return done(nil) }
session.dataTask(with: url) { data, _, _ in
done(data.flatMap(UIImage.init(data:)))
}.resume()
}
/// Whether the session is still good, so a failure can say "sign in again" rather than stall.
func check(done: @escaping (Bool) -> Void) {
guard let url = ServerSettings.url("/api/me") else { return done(false) }
session.dataTask(with: url) { _, resp, _ in
done((resp as? HTTPURLResponse)?.statusCode == 200)
}.resume()
}
private func post(_ path: String, _ body: [String: Any]) {
guard let url = ServerSettings.url(path) else { return }
var req = URLRequest(url: url)
req.httpMethod = "POST"
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.httpBody = try? JSONSerialization.data(withJSONObject: body)
session.dataTask(with: req) { _, resp, err in
if let code = (resp as? HTTPURLResponse)?.statusCode, code >= 400 {
NSLog("ipx: %@ -> %d", path, code)
} else if let err { NSLog("ipx: %@ -> %@", path, err.localizedDescription) }
}.resume()
}
private func esc(_ s: String) -> String {
s.addingPercentEncoding(withAllowedCharacters: .alphanumerics.union(.init(charactersIn: "-._~"))) ?? s
}
}

View File

@@ -28,7 +28,7 @@ final class Playback: NSObject {
var onError: ((String) -> Void)?
private let cookies: CookieBridge
private let library: Library
private let api: API
private var player: AVPlayer?
private var item: Item?
private var timeObserver: Any?
@@ -43,9 +43,9 @@ final class Playback: NSObject {
return d
}
init(cookies: CookieBridge, library: Library) {
init(cookies: CookieBridge, api: API) {
self.cookies = cookies
self.library = library
self.api = api
super.init()
configureSession()
wireRemoteCommands()
@@ -90,8 +90,11 @@ final class Playback: NSObject {
if let d = self.duration { self.onMeta?(d) }
case .failed:
let msg = pi.error?.localizedDescription ?? "the file could not be played"
self.library.check { good in
DispatchQueue.main.async { self.onError?(good ? msg : "sign in again") }
Task {
// Tell one from the other: a file that will not play, and a session that
// went while it was playing. Only the second has anything to do about it.
let signedIn = (try? await self.api.me()) != nil
await MainActor.run { self.onError?(signedIn ? msg : "Sign in again") }
}
default: break
}
@@ -154,19 +157,17 @@ final class Playback: NSObject {
if notify { onState?(false) }
}
/// The page asking us to save, because its own beacon is ours now. It sends the path rather
/// than a time: the time it has may be minutes old if it has been frozen in the background.
func savePosition(path: String? = nil) {
/// Where we are, saved. The page asks for this too, because its own beacon is ours now: it
/// sends no time with the request, since the time a backgrounded web view holds may be
/// minutes old. This clock is the only one worth writing.
func savePosition() {
guard let item, let player, player.currentItem?.status == .readyToPlay else { return }
let secs = Int(player.currentTime().seconds.rounded())
// A file under a second rounds to nought, and "nought seconds in" is not worth writing.
guard secs > 0 else { return }
lastSaved = Double(secs)
let dur = duration.map { Int($0.rounded()) }
if let path {
library.savePosition(path: path, secs: secs, duration: dur)
} else {
library.savePosition(feedId: item.feedId, guid: item.guid, secs: secs, duration: dur)
}
Task { try? await api.setPosition(secs: secs, duration: dur, feed: item.feedId, guid: item.guid) }
}
// MARK: - as it plays
@@ -192,7 +193,7 @@ final class Playback: NSObject {
private func markRead() {
guard !markedRead, let item else { return }
markedRead = true
library.markRead(feedId: item.feedId, guid: item.guid)
Task { try? await api.setRead(true, feed: item.feedId, guid: item.guid) }
}
// MARK: - the car and the lock screen
@@ -240,9 +241,9 @@ final class Playback: NSObject {
centre.nowPlayingInfo = info
if let art = item.artwork {
library.artwork(art) { image in
guard let image else { return }
DispatchQueue.main.async {
Task {
guard let image = await api.image(art) else { return }
await MainActor.run {
// Read back rather than reusing `info`: by the time the picture arrives the
// elapsed time in it is stale, and writing it would jerk the car's progress bar.
var latest = centre.nowPlayingInfo ?? [:]

View File

@@ -8,7 +8,7 @@ import WebKit
final class WebViewController: UIViewController, WKNavigationDelegate {
private var webView: WKWebView!
private var cookies: CookieBridge!
private var library: Library!
private var api: API!
private var playback: Playback!
private var bridge: Bridge!
@@ -48,8 +48,8 @@ final class WebViewController: UIViewController, WKNavigationDelegate {
])
cookies = CookieBridge(store: cfg.websiteDataStore.httpCookieStore)
library = Library(cookies: cookies)
playback = Playback(cookies: cookies, library: library)
api = API()
playback = Playback(cookies: cookies, api: api)
bridge = Bridge(webView: webView, playback: playback)
bridge.onReady = { [weak self] _ in
self?.checkedBridge = true