Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion IOS_Client_Xcode/TM_Sonder_Client/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import PackageDescription
import Foundation

// Exercise the actual client persistence code without a simulator or signing.
let sources = ["SonderClientModels.swift", "SonderOfflineDownloads.swift", "SonderAudiobookChapters.swift", "SonderProgressQueue.swift", "SonderEPUB.swift"]
let sources = ["SonderClientModels.swift", "SonderOfflineDownloads.swift", "SonderAudiobookChapters.swift", "SonderProgressQueue.swift", "SonderEPUB.swift", "SonderServerConnection.swift"]
let directory = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("TM_Sonder_Client")
let excluded = (try? FileManager.default.contentsOfDirectory(atPath: directory.path))?.filter { !sources.contains($0) } ?? []
let package = Package(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,237 @@
import XCTest
@testable import OfflineCore

final class ServerAddressTests: XCTestCase {
func testParseAddsSchemeAndNormalizes() {
XCTAssertEqual(SonderServerAddresses.parse(" sonder.stoverparc.org/ ", defaultScheme: "https")?.absoluteString,
"https://sonder.stoverparc.org")
XCTAssertEqual(SonderServerAddresses.parse("10.20.0.117:8096", defaultScheme: "http")?.absoluteString,
"http://10.20.0.117:8096")
XCTAssertEqual(SonderServerAddresses.parse("HTTPS://Sonder.Example.org/base/?x=1#y", defaultScheme: "http")?.absoluteString,
"https://sonder.example.org/base")
}

func testParseRejectsUnusableText() {
XCTAssertNil(SonderServerAddresses.parse("", defaultScheme: "https"))
XCTAssertNil(SonderServerAddresses.parse(" ", defaultScheme: "https"))
XCTAssertNil(SonderServerAddresses.parse("ftp://files.example.org", defaultScheme: "https"))
XCTAssertNil(SonderServerAddresses.parse("https://", defaultScheme: "https"))
}

func testIdentityPrefersPublicAddress() {
let publicURL = URL(string: "https://sonder.example.org")!
let localURL = URL(string: "http://10.0.0.5:8096")!
XCTAssertEqual(SonderServerAddresses(publicURL: publicURL, localURL: localURL).identityURL, publicURL)
XCTAssertEqual(SonderServerAddresses(publicURL: nil, localURL: localURL).identityURL, localURL)
XCTAssertTrue(SonderServerAddresses().isEmpty)
}
}

final class EndpointSelectorTests: XCTestCase {
private let publicURL = URL(string: "https://sonder.example.org")!
private let localURL = URL(string: "http://10.0.0.5:8096")!

func testUsesLocalWhenItAnswers() async {
let probed = ProbeLog()
let choice = await SonderEndpointSelector.choose(.init(publicURL: publicURL, localURL: localURL)) { url in
await probed.add(url); return true
}
XCTAssertEqual(choice, SonderEndpointChoice(url: localURL, route: .local))
let urls = await probed.urls
XCTAssertEqual(urls, [localURL])
}

func testFallsBackToPublicWhenLocalDoesNotAnswer() async {
let choice = await SonderEndpointSelector.choose(.init(publicURL: publicURL, localURL: localURL)) { _ in false }
XCTAssertEqual(choice, SonderEndpointChoice(url: publicURL, route: .public))
}

func testPublicOnlyIsNotProbed() async {
let probed = ProbeLog()
let choice = await SonderEndpointSelector.choose(.init(publicURL: publicURL, localURL: nil)) { url in
await probed.add(url); return false
}
XCTAssertEqual(choice, SonderEndpointChoice(url: publicURL, route: .public))
let urls = await probed.urls
XCTAssertTrue(urls.isEmpty)
}

func testSameAddressTwiceIsTreatedAsPublic() async {
let probed = ProbeLog()
let choice = await SonderEndpointSelector.choose(.init(publicURL: publicURL, localURL: publicURL)) { url in
await probed.add(url); return true
}
XCTAssertEqual(choice?.route, .public)
let urls = await probed.urls
XCTAssertTrue(urls.isEmpty)
}

func testLocalOnlyIsUsedEvenWhenUnreachable() async {
let choice = await SonderEndpointSelector.choose(.init(publicURL: nil, localURL: localURL)) { _ in false }
XCTAssertEqual(choice, SonderEndpointChoice(url: localURL, route: .local))
}

func testNoAddressesGivesNoChoice() async {
let choice = await SonderEndpointSelector.choose(.init()) { _ in true }
XCTAssertNil(choice)
}
}

final class ServerProbeTests: XCTestCase {
override func tearDown() { StubURLProtocol.handler = nil }

private var probe: SonderServerProbe { SonderServerProbe(session: StubURLProtocol.session(), timeout: 1) }
private let base = URL(string: "http://10.0.0.5:8096")!

func testSonderIdentityHeaderCountsAsReachable() async {
StubURLProtocol.handler = { request in
XCTAssertEqual(request.url?.path, "/api/auth/session")
XCTAssertNil(request.value(forHTTPHeaderField: "Cookie"))
return (401, ["X-Sonder-Server": "tm-sonder"], Data())
}
let reachable = await probe.isSonderServer(base)
XCTAssertTrue(reachable)
}

func testOtherWebServerIsNotReachable() async {
StubURLProtocol.handler = { _ in (200, ["Content-Type": "text/html"], Data("<html>portal</html>".utf8)) }
let reachable = await probe.isSonderServer(base)
XCTAssertFalse(reachable)
}

func testNetworkFailureIsNotReachable() async {
StubURLProtocol.handler = { _ in throw URLError(.cannotConnectToHost) }
let reachable = await probe.isSonderServer(base)
XCTAssertFalse(reachable)
}
}

final class AccountSignInTests: XCTestCase {
override func tearDown() { StubURLProtocol.handler = nil }

private var client: SonderAccountClient { SonderAccountClient(session: StubURLProtocol.session()) }
private let base = URL(string: "https://sonder.example.org")!

func testSignInReturnsSessionCookieAsToken() async throws {
StubURLProtocol.handler = { request in
XCTAssertEqual(request.httpMethod, "POST")
XCTAssertEqual(request.url?.path, "/api/auth/login")
XCTAssertEqual(request.value(forHTTPHeaderField: "Content-Type"), "application/json")
let body = try JSONSerialization.jsonObject(with: StubURLProtocol.body(of: request)) as? [String: String]
XCTAssertEqual(body?["username"], "sean")
XCTAssertEqual(body?["password"], "correct horse")
return (200, ["Set-Cookie": "sonder_session=abc123; Path=/; Expires=Wed, 02 Dec 2026 18:00:00 GMT; HttpOnly; Secure; SameSite=Lax",
"Content-Type": "application/json"],
Data(#"{"authenticated":true,"username":"sean","expiresAt":"2026-12-02T18:00:00.123456789Z"}"#.utf8))
}
let result = try await client.signIn(baseURL: base, username: " sean ", password: "correct horse")
XCTAssertEqual(result.token, "abc123")
XCTAssertEqual(result.username, "sean")
XCTAssertEqual(result.expiresAt?.timeIntervalSince1970 ?? 0, 1_796_234_400.123, accuracy: 0.01)
}

func testWrongPasswordFromSonderIsInvalidCredentials() async {
StubURLProtocol.handler = { _ in (401, ["X-Sonder-Server": "tm-sonder"], Data(#"{"error":"Invalid credentials"}"#.utf8)) }
await assertSignIn(throws: .invalidCredentials)
}

func testUnauthorizedWithoutSonderHeaderIsNotSonder() async {
StubURLProtocol.handler = { _ in (401, [:], Data()) }
await assertSignIn(throws: .notSonderServer)
}

func testThrottleCarriesRetryAfter() async {
StubURLProtocol.handler = { _ in (429, ["Retry-After": "900", "X-Sonder-Server": "tm-sonder"], Data()) }
await assertSignIn(throws: .throttled(retryAfterSeconds: 900))
}

func testNoAccountYetIsSetupRequired() async {
StubURLProtocol.handler = { _ in (409, ["X-Sonder-Server": "tm-sonder"], Data()) }
await assertSignIn(throws: .setupRequired)
}

func testSuccessWithoutCookieIsReported() async {
StubURLProtocol.handler = { _ in (200, ["X-Sonder-Server": "tm-sonder"], Data(#"{"authenticated":true}"#.utf8)) }
await assertSignIn(throws: .noSessionIssued)
}

func testSessionStatusSendsBearerToken() async throws {
StubURLProtocol.handler = { request in
XCTAssertEqual(request.url?.path, "/api/auth/session")
XCTAssertEqual(request.value(forHTTPHeaderField: "Authorization"), "Bearer tok")
return (200, ["X-Sonder-Server": "tm-sonder"],
Data(#"{"authenticated":true,"googleLinked":false,"setupRequired":false,"username":"sean"}"#.utf8))
}
let status = try await client.sessionStatus(baseURL: base, token: "tok")
XCTAssertEqual(status, SonderAuthSessionStatus(setupRequired: false, authenticated: true, username: "sean"))
}

func testServerDateParsingAcceptsGoNanoseconds() {
XCTAssertNotNil(SonderAccountClient.parseServerDate("2026-12-02T18:00:00.123456789Z"))
XCTAssertNotNil(SonderAccountClient.parseServerDate("2026-12-02T18:00:00-05:00"))
XCTAssertNil(SonderAccountClient.parseServerDate("not a date"))
XCTAssertNil(SonderAccountClient.parseServerDate(nil))
}

private func assertSignIn(throws expected: SonderSignInError, file: StaticString = #filePath, line: UInt = #line) async {
do {
_ = try await client.signIn(baseURL: base, username: "sean", password: "pw")
XCTFail("Expected \(expected)", file: file, line: line)
} catch {
XCTAssertEqual(error as? SonderSignInError, expected, file: file, line: line)
}
}
}

private actor ProbeLog {
var urls: [URL] = []
func add(_ url: URL) { urls.append(url) }
}

/// Serves canned responses so the networking code runs without a server.
final class StubURLProtocol: URLProtocol, @unchecked Sendable {
typealias Handler = @Sendable (URLRequest) throws -> (Int, [String: String], Data)
nonisolated(unsafe) static var handler: Handler?

static func session() -> URLSession {
let configuration = URLSessionConfiguration.ephemeral
configuration.protocolClasses = [StubURLProtocol.self]
return URLSession(configuration: configuration)
}

static func body(of request: URLRequest) -> Data {
if let body = request.httpBody { return body }
guard let stream = request.httpBodyStream else { return Data() }
stream.open()
defer { stream.close() }
var data = Data()
var buffer = [UInt8](repeating: 0, count: 4096)
while stream.hasBytesAvailable {
let count = stream.read(&buffer, maxLength: buffer.count)
if count <= 0 { break }
data.append(buffer, count: count)
}
return data
}

override class func canInit(with request: URLRequest) -> Bool { true }
override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }

override func startLoading() {
guard let handler = Self.handler else {
client?.urlProtocol(self, didFailWithError: URLError(.unknown))
return
}
do {
let (status, headers, data) = try handler(request)
let response = HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: "HTTP/1.1", headerFields: headers)!
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
client?.urlProtocol(self, didLoad: data)
client?.urlProtocolDidFinishLoading(self)
} catch {
client?.urlProtocol(self, didFailWithError: error)
}
}

override func stopLoading() {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ struct ContentView: View {
@Environment(\.scenePhase) private var scenePhase
@StateObject private var model = SonderClientModel()
@StateObject private var browser = SonderServerBrowser()
@State private var signInDismissed = false

var body: some View {
NavigationStack {
Expand Down Expand Up @@ -37,15 +38,26 @@ struct ContentView: View {
guard let endpoint = endpoints.first(where: model.shouldAutomaticallyUseDiscoveredEndpoint) else { return }
Task { await model.connect(to: endpoint) }
}
.onChange(of: model.needsSignIn) { _, needsSignIn in
if needsSignIn == false { signInDismissed = false }
}
.sheet(isPresented: Binding(
get: { model.hasConfiguredServer && model.needsSignIn && signInDismissed == false },
set: { if $0 == false { signInDismissed = true } }
)) {
ServerSignInView(model: model) { signInDismissed = true }
}
.tint(SonderPalette.accent)
}
}

struct ServerOnboardingView: View {
@ObservedObject var model: SonderClientModel
@ObservedObject var browser: SonderServerBrowser
@State private var manualURL = ""
@State private var publicURLText = ""
@State private var localURLText = ""
@State private var token = ""
@State private var addressError: String?

var body: some View {
ScrollView {
Expand Down Expand Up @@ -117,7 +129,7 @@ struct ServerOnboardingView: View {
Text("Searching for Sonder on your local network")
.font(.subheadline.weight(.semibold))
.foregroundStyle(SonderPalette.text)
Text("Make sure LAN sharing is enabled on the Mac server. Tailscale and private URLs can be entered below.")
Text("Make sure LAN sharing is enabled on the server, or enter its address below.")
.font(.caption)
.foregroundStyle(SonderPalette.textLight)
}
Expand Down Expand Up @@ -160,24 +172,17 @@ struct ServerOnboardingView: View {

private var manualPanel: some View {
VStack(alignment: .leading, spacing: 12) {
Label("Manual or Tailscale", systemImage: "link")
Label("Server address", systemImage: "link")
.font(.headline)
.foregroundStyle(SonderPalette.text)

TextField("http://sonder.local:8797", text: $manualURL)
.textFieldStyle(.plain)
.autocorrectionDisabled()
.textInputAutocapitalization(.never)
.padding(12)
.background(SonderPalette.surfaceDeep, in: RoundedRectangle(cornerRadius: 8))
.overlay(RoundedRectangle(cornerRadius: 8).stroke(SonderPalette.border))
ServerAddressFields(publicText: $publicURLText, localText: $localURLText, pairingToken: $token)

SecureField("Optional token for restricted servers", text: $token)
.textFieldStyle(.plain)
.autocorrectionDisabled()
.padding(12)
.background(SonderPalette.surfaceDeep, in: RoundedRectangle(cornerRadius: 8))
.overlay(RoundedRectangle(cornerRadius: 8).stroke(SonderPalette.border))
if let addressError {
Label(addressError, systemImage: "exclamationmark.triangle")
.font(.caption)
.foregroundStyle(SonderPalette.ironGrey)
}

Button {
connectManualURL()
Expand All @@ -186,17 +191,24 @@ struct ServerOnboardingView: View {
.frame(maxWidth: .infinity)
}
.buttonStyle(.borderedProminent)
.disabled(URL(string: manualURL.trimmingCharacters(in: .whitespacesAndNewlines)) == nil)
.disabled(publicURLText.trimmingCharacters(in: .whitespaces).isEmpty && localURLText.trimmingCharacters(in: .whitespaces).isEmpty)
.accessibilityIdentifier("server.connect")
}
.padding(16)
.background(SonderPalette.surface, in: RoundedRectangle(cornerRadius: 8))
.overlay(RoundedRectangle(cornerRadius: 8).stroke(SonderPalette.border))
}

private func connectManualURL() {
guard let url = URL(string: manualURL.trimmingCharacters(in: .whitespacesAndNewlines)) else { return }
model.saveServer(baseURL: url, accessToken: token)
Task { await model.reload() }
switch ServerAddressFields.addresses(publicText: publicURLText, localText: localURLText) {
case let .failure(error):
addressError = error.message
case let .success(addresses):
addressError = nil
let pairing = token.trimmingCharacters(in: .whitespacesAndNewlines)
guard model.saveServer(addresses: addresses, pairingToken: pairing.isEmpty ? nil : pairing) else { return }
Task { await model.reload() }
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ struct CachedPosterImage<Placeholder: View>: View {
// Posters dominate initial rendering. Allow URLSession's disk-backed
// cache to satisfy repeat launches instead of redownloading every card.
request.cachePolicy = .returnCacheDataElseLoad
request.httpShouldHandleCookies = false
let token = accessToken.trimmingCharacters(in: .whitespacesAndNewlines)
if token.isEmpty == false {
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ struct LibraryHomeTab: View {
LibrarySearchBar(model: model)

if model.filteredItems.isEmpty && model.isLoading == false {
EmptyLibraryState()
EmptyLibraryState(needsSignIn: model.needsSignIn)
} else {
if inProgressItems.isEmpty == false {
MediaShelf(title: "Continue Watching", subtitle: "Pick up where you left off", items: Array(inProgressItems.prefix(12)), model: model, selectedItem: $selectedItem)
Expand Down Expand Up @@ -100,7 +100,7 @@ struct MediaKindTab: View {
LibrarySearchBar(model: model)

if items.isEmpty {
EmptyLibraryState()
EmptyLibraryState(needsSignIn: model.needsSignIn)
} else {
LazyVGrid(columns: [GridItem(.adaptive(minimum: 126, maximum: 150), spacing: 16)], spacing: 18) {
ForEach(items) { item in
Expand Down Expand Up @@ -218,8 +218,12 @@ struct SectionHeader: View {
}

struct EmptyLibraryState: View {
var needsSignIn = false

var body: some View {
ContentUnavailableView("No Titles", systemImage: "rectangle.stack", description: Text("Check the server URL or adjust the current filters."))
ContentUnavailableView(needsSignIn ? "Sign In to See Your Library" : "No Titles",
systemImage: needsSignIn ? "person.crop.circle.badge.exclamationmark" : "rectangle.stack",
description: Text(needsSignIn ? "The server answered and needs your Sonder account. Sign in from Settings." : "Check the server address or adjust the current filters."))
.foregroundStyle(SonderPalette.text)
.frame(maxWidth: .infinity, minHeight: 260)
}
Expand Down
Loading
Loading