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:
@@ -81,7 +81,9 @@ For automation, `-ipx.server <url>` as a launch argument overrides the stored va
|
|||||||
| `ios/Sources/WebViewController.swift` | the `WKWebView`, and the banner when something is wrong |
|
| `ios/Sources/WebViewController.swift` | the `WKWebView`, and the banner when something is wrong |
|
||||||
| `ios/Sources/Bridge.swift` | the messages, both directions |
|
| `ios/Sources/Bridge.swift` | the messages, both directions |
|
||||||
| `ios/Sources/Playback.swift` | `AVPlayer`, the audio session, now-playing, the remote commands |
|
| `ios/Sources/Playback.swift` | `AVPlayer`, the audio session, now-playing, the remote commands |
|
||||||
| `ios/Sources/Library.swift` | the API calls the host makes: position, read, artwork |
|
| `ios/Sources/API.swift` | ipx's HTTP API, typed |
|
||||||
|
| `ios/Sources/APIModels.swift` | what ipx sends: feeds, entries, enclosures |
|
||||||
|
| `ios/Sources/Events.swift` | the `/api/events` stream, and reconnecting to it |
|
||||||
| `ios/Sources/CookieBridge.swift` | `WKHTTPCookieStore` into `HTTPCookieStorage.shared` |
|
| `ios/Sources/CookieBridge.swift` | `WKHTTPCookieStore` into `HTTPCookieStorage.shared` |
|
||||||
| `ios/Sources/ServerSettings.swift` | which server |
|
| `ios/Sources/ServerSettings.swift` | which server |
|
||||||
|
|
||||||
|
|||||||
168
ios/Sources/API.swift
Normal file
168
ios/Sources/API.swift
Normal 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
140
ios/Sources/APIModels.swift
Normal 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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -67,7 +67,9 @@ final class Bridge: NSObject, WKScriptMessageHandler {
|
|||||||
case "rate": if let v = m["v"] as? Double { playback.setRate(Float(v)) }
|
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 "volume": if let v = m["v"] as? Double { playback.setVolume(Float(v)) }
|
||||||
case "stop": playback.stop()
|
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
|
default: break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
126
ios/Sources/Events.swift
Normal file
126
ios/Sources/Events.swift
Normal 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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -28,7 +28,7 @@ final class Playback: NSObject {
|
|||||||
var onError: ((String) -> Void)?
|
var onError: ((String) -> Void)?
|
||||||
|
|
||||||
private let cookies: CookieBridge
|
private let cookies: CookieBridge
|
||||||
private let library: Library
|
private let api: API
|
||||||
private var player: AVPlayer?
|
private var player: AVPlayer?
|
||||||
private var item: Item?
|
private var item: Item?
|
||||||
private var timeObserver: Any?
|
private var timeObserver: Any?
|
||||||
@@ -43,9 +43,9 @@ final class Playback: NSObject {
|
|||||||
return d
|
return d
|
||||||
}
|
}
|
||||||
|
|
||||||
init(cookies: CookieBridge, library: Library) {
|
init(cookies: CookieBridge, api: API) {
|
||||||
self.cookies = cookies
|
self.cookies = cookies
|
||||||
self.library = library
|
self.api = api
|
||||||
super.init()
|
super.init()
|
||||||
configureSession()
|
configureSession()
|
||||||
wireRemoteCommands()
|
wireRemoteCommands()
|
||||||
@@ -90,8 +90,11 @@ final class Playback: NSObject {
|
|||||||
if let d = self.duration { self.onMeta?(d) }
|
if let d = self.duration { self.onMeta?(d) }
|
||||||
case .failed:
|
case .failed:
|
||||||
let msg = pi.error?.localizedDescription ?? "the file could not be played"
|
let msg = pi.error?.localizedDescription ?? "the file could not be played"
|
||||||
self.library.check { good in
|
Task {
|
||||||
DispatchQueue.main.async { self.onError?(good ? msg : "sign in again") }
|
// 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
|
default: break
|
||||||
}
|
}
|
||||||
@@ -154,19 +157,17 @@ final class Playback: NSObject {
|
|||||||
if notify { onState?(false) }
|
if notify { onState?(false) }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The page asking us to save, because its own beacon is ours now. It sends the path rather
|
/// Where we are, saved. The page asks for this too, because its own beacon is ours now: it
|
||||||
/// than a time: the time it has may be minutes old if it has been frozen in the background.
|
/// sends no time with the request, since the time a backgrounded web view holds may be
|
||||||
func savePosition(path: String? = nil) {
|
/// minutes old. This clock is the only one worth writing.
|
||||||
|
func savePosition() {
|
||||||
guard let item, let player, player.currentItem?.status == .readyToPlay else { return }
|
guard let item, let player, player.currentItem?.status == .readyToPlay else { return }
|
||||||
let secs = Int(player.currentTime().seconds.rounded())
|
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 }
|
guard secs > 0 else { return }
|
||||||
lastSaved = Double(secs)
|
lastSaved = Double(secs)
|
||||||
let dur = duration.map { Int($0.rounded()) }
|
let dur = duration.map { Int($0.rounded()) }
|
||||||
if let path {
|
Task { try? await api.setPosition(secs: secs, duration: dur, feed: item.feedId, guid: item.guid) }
|
||||||
library.savePosition(path: path, secs: secs, duration: dur)
|
|
||||||
} else {
|
|
||||||
library.savePosition(feedId: item.feedId, guid: item.guid, secs: secs, duration: dur)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - as it plays
|
// MARK: - as it plays
|
||||||
@@ -192,7 +193,7 @@ final class Playback: NSObject {
|
|||||||
private func markRead() {
|
private func markRead() {
|
||||||
guard !markedRead, let item else { return }
|
guard !markedRead, let item else { return }
|
||||||
markedRead = true
|
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
|
// MARK: - the car and the lock screen
|
||||||
@@ -240,9 +241,9 @@ final class Playback: NSObject {
|
|||||||
centre.nowPlayingInfo = info
|
centre.nowPlayingInfo = info
|
||||||
|
|
||||||
if let art = item.artwork {
|
if let art = item.artwork {
|
||||||
library.artwork(art) { image in
|
Task {
|
||||||
guard let image else { return }
|
guard let image = await api.image(art) else { return }
|
||||||
DispatchQueue.main.async {
|
await MainActor.run {
|
||||||
// Read back rather than reusing `info`: by the time the picture arrives the
|
// 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.
|
// elapsed time in it is stale, and writing it would jerk the car's progress bar.
|
||||||
var latest = centre.nowPlayingInfo ?? [:]
|
var latest = centre.nowPlayingInfo ?? [:]
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import WebKit
|
|||||||
final class WebViewController: UIViewController, WKNavigationDelegate {
|
final class WebViewController: UIViewController, WKNavigationDelegate {
|
||||||
private var webView: WKWebView!
|
private var webView: WKWebView!
|
||||||
private var cookies: CookieBridge!
|
private var cookies: CookieBridge!
|
||||||
private var library: Library!
|
private var api: API!
|
||||||
private var playback: Playback!
|
private var playback: Playback!
|
||||||
private var bridge: Bridge!
|
private var bridge: Bridge!
|
||||||
|
|
||||||
@@ -48,8 +48,8 @@ final class WebViewController: UIViewController, WKNavigationDelegate {
|
|||||||
])
|
])
|
||||||
|
|
||||||
cookies = CookieBridge(store: cfg.websiteDataStore.httpCookieStore)
|
cookies = CookieBridge(store: cfg.websiteDataStore.httpCookieStore)
|
||||||
library = Library(cookies: cookies)
|
api = API()
|
||||||
playback = Playback(cookies: cookies, library: library)
|
playback = Playback(cookies: cookies, api: api)
|
||||||
bridge = Bridge(webView: webView, playback: playback)
|
bridge = Bridge(webView: webView, playback: playback)
|
||||||
bridge.onReady = { [weak self] _ in
|
bridge.onReady = { [weak self] _ in
|
||||||
self?.checkedBridge = true
|
self?.checkedBridge = true
|
||||||
|
|||||||
120
ios/Tests/APITests.swift
Normal file
120
ios/Tests/APITests.swift
Normal file
@@ -0,0 +1,120 @@
|
|||||||
|
import XCTest
|
||||||
|
@testable import iPodderX
|
||||||
|
|
||||||
|
/// The client against a real daemon, because the shapes it decodes are the server's and a
|
||||||
|
/// hand-written fixture would only prove the fixture matches itself.
|
||||||
|
///
|
||||||
|
/// Point it at the daemon the browser suite uses, in ipodderx-rs:
|
||||||
|
///
|
||||||
|
/// node -e "require('./tests/ui/global-setup').prepare()"
|
||||||
|
/// node tests/ui/fixtures/serve.js &
|
||||||
|
/// IPX_CONFIG=$ROOT/config/config.toml IPX_DATA_DIR=$ROOT/data ./target/debug/ipx daemon &
|
||||||
|
/// TEST_RUNNER_IPX_SERVER=http://127.0.0.1:8791 TEST_RUNNER_IPX_TOKEN=<fixture token> \
|
||||||
|
/// xcodebuild test ...
|
||||||
|
final class APITests: XCTestCase {
|
||||||
|
var api: API!
|
||||||
|
|
||||||
|
override func setUpWithError() throws {
|
||||||
|
let env = ProcessInfo.processInfo.environment
|
||||||
|
let server = env["IPX_SERVER"] ?? ""
|
||||||
|
let token = env["IPX_TOKEN"] ?? ""
|
||||||
|
try XCTSkipIf(server.isEmpty, "set IPX_SERVER to a fixture daemon")
|
||||||
|
|
||||||
|
ServerSettings.base = try XCTUnwrap(ServerSettings.parse(server))
|
||||||
|
|
||||||
|
// The shared token signs in as the admin. It goes in as a cookie rather than on the
|
||||||
|
// query because that is how the client authenticates everything -- ipx reads
|
||||||
|
// HTTPCookieStorage through the same path the web view fills.
|
||||||
|
if !token.isEmpty, let url = ServerSettings.base {
|
||||||
|
let cookie = try XCTUnwrap(HTTPCookie(properties: [
|
||||||
|
.name: "ipx_token", .value: token, .path: "/",
|
||||||
|
.domain: url.host ?? "127.0.0.1",
|
||||||
|
]))
|
||||||
|
HTTPCookieStorage.shared.setCookie(cookie)
|
||||||
|
}
|
||||||
|
api = API()
|
||||||
|
}
|
||||||
|
|
||||||
|
func testSignedIn() async throws {
|
||||||
|
let me = try await api.me()
|
||||||
|
XCTAssertFalse(me.name.isEmpty, "nobody is signed in")
|
||||||
|
}
|
||||||
|
|
||||||
|
func testFeedsDecode() async throws {
|
||||||
|
let feeds = try await api.feeds()
|
||||||
|
XCTAssertFalse(feeds.isEmpty, "the fixture daemon has five feeds configured")
|
||||||
|
let show = try XCTUnwrap(feeds.first { $0.id == "test-show" }, "no test-show feed")
|
||||||
|
XCTAssertEqual(show.name, "Test Show")
|
||||||
|
XCTAssertEqual(show.entries, 2)
|
||||||
|
XCTAssertGreaterThanOrEqual(show.subscribers, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testEntriesPageAndDecodeEnclosures() async throws {
|
||||||
|
let page = try await api.entries(feed: "test-show")
|
||||||
|
XCTAssertEqual(page.total, 2)
|
||||||
|
let second = try XCTUnwrap(page.entries.first { $0.guid == "ui-2" })
|
||||||
|
XCTAssertEqual(second.feedId, "test-show")
|
||||||
|
// The cap is one download per scan, newest first, so the second episode has the file.
|
||||||
|
let file = try XCTUnwrap(second.playable, "the downloaded episode has no playable file")
|
||||||
|
XCTAssertTrue(file.isDownloaded)
|
||||||
|
XCTAssertEqual(file.mime, "audio/mpeg")
|
||||||
|
XCTAssertFalse(file.isVideo)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An image enclosure is on disk and is not a thing to hand a player.
|
||||||
|
func testAnImageIsNotPlayable() async throws {
|
||||||
|
let page = try await api.entries(feed: "picture-blog")
|
||||||
|
let enclosure = try XCTUnwrap(page.entries.first?.enclosures.first)
|
||||||
|
XCTAssertTrue(enclosure.isDownloaded)
|
||||||
|
XCTAssertFalse(enclosure.isPlayable, "a downloaded JPEG is not something to play")
|
||||||
|
}
|
||||||
|
|
||||||
|
func testFilterAndSortAreTheServersWork() async throws {
|
||||||
|
let downloaded = try await api.entries(feed: "test-show", filter: .downloaded)
|
||||||
|
XCTAssertEqual(downloaded.total, 1, "one of the two episodes has a file")
|
||||||
|
|
||||||
|
let asc = try await api.entries(feed: "test-show", sort: .title, direction: .asc)
|
||||||
|
let desc = try await api.entries(feed: "test-show", sort: .title, direction: .desc)
|
||||||
|
XCTAssertEqual(asc.entries.map(\.guid), desc.entries.map(\.guid).reversed())
|
||||||
|
}
|
||||||
|
|
||||||
|
func testSearchMatchesTitles() async throws {
|
||||||
|
let hit = try await api.entries(feed: "test-show", search: "Second")
|
||||||
|
XCTAssertEqual(hit.entries.count, 1)
|
||||||
|
let miss = try await api.entries(feed: "test-show", search: "nothing matches this")
|
||||||
|
XCTAssertEqual(miss.total, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read is per-person state, so writing it and reading it back is the whole contract.
|
||||||
|
func testReadRoundTrips() async throws {
|
||||||
|
let before = try await api.entries(feed: "test-show", filter: .all)
|
||||||
|
let entry = try XCTUnwrap(before.entries.first { $0.guid == "ui-1" })
|
||||||
|
|
||||||
|
try await api.setRead(!entry.read, feed: entry.feedId, guid: entry.guid)
|
||||||
|
let after = try await api.entries(feed: "test-show")
|
||||||
|
let again = try XCTUnwrap(after.entries.first { $0.guid == "ui-1" })
|
||||||
|
XCTAssertEqual(again.read, !entry.read, "the flag did not stick")
|
||||||
|
|
||||||
|
try await api.setRead(entry.read, feed: entry.feedId, guid: entry.guid)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testPositionRoundTrips() async throws {
|
||||||
|
try await api.setPosition(secs: 42, duration: 900, feed: "test-show", guid: "ui-2")
|
||||||
|
let page = try await api.entries(feed: "test-show")
|
||||||
|
XCTAssertEqual(page.entries.first { $0.guid == "ui-2" }?.position, 42)
|
||||||
|
try await api.setPosition(secs: 0, duration: nil, feed: "test-show", guid: "ui-2")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A 401 has to be legible: it means the session went, and only a sign-in fixes it.
|
||||||
|
func testAnUnauthenticatedCallSaysSoPlainly() async throws {
|
||||||
|
HTTPCookieStorage.shared.removeCookies(since: .distantPast)
|
||||||
|
do {
|
||||||
|
_ = try await api.feeds()
|
||||||
|
XCTFail("a signed-out request should not succeed")
|
||||||
|
} catch API.Failure.notSignedIn {
|
||||||
|
// what we want
|
||||||
|
} catch {
|
||||||
|
XCTFail("expected notSignedIn, got \(error)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
58
ios/Tests/EventsTests.swift
Normal file
58
ios/Tests/EventsTests.swift
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
import XCTest
|
||||||
|
@testable import iPodderX
|
||||||
|
|
||||||
|
/// The event stream, against a real daemon. Asking it to scan is the cheapest way to make it
|
||||||
|
/// say something, and scan_done is terminal, so the test has a definite end rather than a sleep.
|
||||||
|
final class EventsTests: XCTestCase {
|
||||||
|
func testAScanIsReportedOnTheStream() async throws {
|
||||||
|
let env = ProcessInfo.processInfo.environment
|
||||||
|
let server = env["IPX_SERVER"] ?? ""
|
||||||
|
try XCTSkipIf(server.isEmpty, "set IPX_SERVER to a fixture daemon")
|
||||||
|
ServerSettings.base = try XCTUnwrap(ServerSettings.parse(server))
|
||||||
|
|
||||||
|
if let token = env["IPX_TOKEN"], !token.isEmpty, let url = ServerSettings.base {
|
||||||
|
let cookie = try XCTUnwrap(HTTPCookie(properties: [
|
||||||
|
.name: "ipx_token", .value: token, .path: "/",
|
||||||
|
.domain: url.host ?? "127.0.0.1",
|
||||||
|
]))
|
||||||
|
HTTPCookieStorage.shared.setCookie(cookie)
|
||||||
|
}
|
||||||
|
|
||||||
|
let events = await Events()
|
||||||
|
let sawScanDone = expectation(description: "scan_done arrives")
|
||||||
|
sawScanDone.assertForOverFulfill = false
|
||||||
|
|
||||||
|
await MainActor.run {
|
||||||
|
events.onEvent { event in
|
||||||
|
if case .scanDone = event { sawScanDone.fulfill() }
|
||||||
|
}
|
||||||
|
events.start()
|
||||||
|
}
|
||||||
|
// Connect before asking for work, or the answer arrives before anyone is listening.
|
||||||
|
try await Task.sleep(nanoseconds: 1_500_000_000)
|
||||||
|
|
||||||
|
try await API().fetch(feed: "test-show")
|
||||||
|
await fulfillment(of: [sawScanDone], timeout: 30)
|
||||||
|
await MainActor.run { events.stop() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An event this build has never heard of must not stop the stream.
|
||||||
|
func testAnUnknownEventDecodesRatherThanThrowing() throws {
|
||||||
|
let data = Data(#"{"ev":"something_new","feed":"x"}"#.utf8)
|
||||||
|
let event = try JSONDecoder().decode(IPXEvent.self, from: data)
|
||||||
|
guard case .other(let name) = event else { return XCTFail("expected .other, got \(event)") }
|
||||||
|
XCTAssertEqual(name, "something_new")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Progress without a total happens: a server that sends no Content-Length.
|
||||||
|
func testProgressDecodesWithoutATotal() throws {
|
||||||
|
let data = Data(#"{"ev":"progress","feed":"f","enclosure":7,"url":"u","file":"a.mp3","done":10}"#.utf8)
|
||||||
|
guard case .progress(_, let enclosure, _, let done, let total) =
|
||||||
|
try JSONDecoder().decode(IPXEvent.self, from: data) else {
|
||||||
|
return XCTFail("did not decode as progress")
|
||||||
|
}
|
||||||
|
XCTAssertEqual(enclosure, 7)
|
||||||
|
XCTAssertEqual(done, 10)
|
||||||
|
XCTAssertNil(total)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -69,6 +69,17 @@ targets:
|
|||||||
ARCHS[sdk=macosx*]: arm64
|
ARCHS[sdk=macosx*]: arm64
|
||||||
DERIVE_MACCATALYST_PRODUCT_BUNDLE_IDENTIFIER: "NO"
|
DERIVE_MACCATALYST_PRODUCT_BUNDLE_IDENTIFIER: "NO"
|
||||||
|
|
||||||
|
iPodderXTests:
|
||||||
|
type: bundle.unit-test
|
||||||
|
platform: iOS
|
||||||
|
sources:
|
||||||
|
- Tests
|
||||||
|
dependencies:
|
||||||
|
- target: iPodderX
|
||||||
|
settings:
|
||||||
|
base:
|
||||||
|
PRODUCT_BUNDLE_IDENTIFIER: net.sdf1.ipodderx.tests
|
||||||
|
|
||||||
iPodderXUITests:
|
iPodderXUITests:
|
||||||
type: bundle.ui-testing
|
type: bundle.ui-testing
|
||||||
platform: iOS
|
platform: iOS
|
||||||
@@ -85,10 +96,12 @@ schemes:
|
|||||||
build:
|
build:
|
||||||
targets:
|
targets:
|
||||||
iPodderX: all
|
iPodderX: all
|
||||||
|
iPodderXTests: [test]
|
||||||
iPodderXUITests: [test]
|
iPodderXUITests: [test]
|
||||||
run:
|
run:
|
||||||
config: Debug
|
config: Debug
|
||||||
test:
|
test:
|
||||||
config: Debug
|
config: Debug
|
||||||
targets:
|
targets:
|
||||||
|
- iPodderXTests
|
||||||
- iPodderXUITests
|
- iPodderXUITests
|
||||||
|
|||||||
Reference in New Issue
Block a user