From 9b06a4bdd476d089573d3f42cb20a159784cab21 Mon Sep 17 00:00:00 2001 From: professorDeveloper <108933534+professorDeveloper@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:57:18 +0500 Subject: [PATCH 1/2] Apple TV: survive slow sources, throttling and a deleted profile The backend gives /contents/media 60 s to resolve a slow provider, but every request here gave up after 30 s of silence. Media now waits 75 s; everything else keeps 30 s. Backend messages are Uzbek and mostly carry no code, so they no longer reach the screen: the error code, then the HTTP status, picks an English message, and a body that does not decode says so instead of Foundation's text. A 429 or 503 GET with a short Retry-After is retried once after that wait; a longer one is shown as "try again in N seconds". Device-link polling stopped for good on the first failed poll. It now backs off exponentially on network errors, 429, 503 and 5xx, honours Retry-After, and gives up only on permanent errors or code expiry. The "denied" branch is gone: pollToken only returns pending, expired or approved. A PROFILE_NOT_FOUND reply drops the active profile, which brings back the picker, and reloads the list. "Choose another source" and playing a film no longer reuse the first, possibly expired, signed URLs: episodes call contents/media again and inline film sources are fetched again from contents/episodes, since they have no media ref. Continue watching skips a malformed row instead of losing the whole rail. --- apple-tv/SozoTV/APIClient.swift | 110 +++++++++++++++----- apple-tv/SozoTV/ContinueWatching.swift | 14 ++- apple-tv/SozoTV/DetailView.swift | 22 +++- apple-tv/SozoTV/DeviceLinkPolling.swift | 25 +++++ apple-tv/SozoTV/RootView.swift | 25 +++-- apple-tv/SozoTV/SessionStore.swift | 32 ++++-- apple-tv/Tests/ContinueWatching/main.swift | 5 +- apple-tv/Tests/DeviceLinkPolling/main.swift | 17 +++ apple-tv/Tests/SessionTransportChecks.swift | 60 ++++++++++- apple-tv/scripts/check-profiles.sh | 2 + 10 files changed, 261 insertions(+), 51 deletions(-) create mode 100644 apple-tv/SozoTV/DeviceLinkPolling.swift create mode 100644 apple-tv/Tests/DeviceLinkPolling/main.swift diff --git a/apple-tv/SozoTV/APIClient.swift b/apple-tv/SozoTV/APIClient.swift index 7cf0adb7..e7bda99f 100644 --- a/apple-tv/SozoTV/APIClient.swift +++ b/apple-tv/SozoTV/APIClient.swift @@ -14,14 +14,23 @@ actor APIClient { return URL(string: String(decoding: plain, as: UTF8.self))! }() + /// The backend allows /contents/media 60 s to resolve a slow provider before it answers. + static let mediaTimeout: TimeInterval = 75 + static let defaultTimeout: TimeInterval = 30 + /// A throttled GET waits this long at most before its single retry. + static let maximumRetryWait: TimeInterval = 5 + init(base: URL = APIClient.defaultBase, session: URLSession? = nil) { self.base = base - self.session = session ?? URLSession(configuration: .ephemeral, delegate: SameOriginRedirects(), delegateQueue: nil) + let config = URLSessionConfiguration.ephemeral + config.timeoutIntervalForRequest = APIClient.mediaTimeout + 15 + self.session = session ?? URLSession(configuration: config, delegate: SameOriginRedirects(), delegateQueue: nil) } func request( _ path: String, query: [URLQueryItem] = [], method: String = "GET", - body: [String: Any]? = nil, token: String? = nil, profileId: String? = nil + body: [String: Any]? = nil, token: String? = nil, profileId: String? = nil, + timeout: TimeInterval = APIClient.defaultTimeout ) async throws -> T { guard !path.hasPrefix("/"), !path.contains("://"), !path.split(separator: "/").contains("..") else { throw APIError.invalidRequest @@ -31,7 +40,7 @@ actor APIClient { guard let url = parts.url else { throw APIError.invalidRequest } var request = URLRequest(url: url) request.httpMethod = method - request.timeoutInterval = 30 + request.timeoutInterval = timeout request.setValue("application/json", forHTTPHeaderField: "Accept") request.setValue("en", forHTTPHeaderField: "Accept-Language") request.setValue("SozoTV/tvOS", forHTTPHeaderField: "User-Agent") @@ -41,13 +50,24 @@ actor APIClient { request.httpBody = try JSONSerialization.data(withJSONObject: body) request.setValue("application/json", forHTTPHeaderField: "Content-Type") } + do { return try await send(request) } + catch let failure as APIError where method == "GET" && failure.isThrottled { + guard let wait = failure.retryAfter, wait <= APIClient.maximumRetryWait else { throw failure } + try await Task.sleep(nanoseconds: UInt64(max(wait, 0.5) * 1_000_000_000)) + return try await send(request) + } + } + + private func send(_ request: URLRequest) async throws -> T { let (data, response) = try await session.data(for: request) guard let http = response as? HTTPURLResponse else { throw APIError.http(-1) } guard 200..<300 ~= http.statusCode else { let payload = try? decoder.decode(ErrorPayload.self, from: data) - throw APIError.server(status: http.statusCode, code: payload?.code, message: payload?.message) + throw APIError.server(status: http.statusCode, code: payload?.code, message: payload?.message, + retryAfter: http.value(forHTTPHeaderField: "Retry-After").flatMap(APIError.retryAfter)) } - return try decoder.decode(T.self, from: data) + do { return try decoder.decode(T.self, from: data) } + catch { throw APIError.invalidResponse } } func providers() async throws -> [Provider] { let catalog: ProviderCatalog = try await request("contents/providers"); return catalog.items } @@ -73,7 +93,7 @@ actor APIClient { try await request("contents/media", query: [ .init(name: "provider", value: provider), .init(name: "ref", value: ref), .init(name: "lang", value: "sub"), - ]) + ], timeout: APIClient.mediaTimeout) } } @@ -92,34 +112,70 @@ private final class SameOriginRedirects: NSObject, URLSessionTaskDelegate, @unch } enum APIError: LocalizedError { - case http(Int), server(status: Int, code: String?, message: String?) - case noPlayableSource, invalidRequest, unauthenticated, staleSession, pinRequired, incompleteDeviceSession + case http(Int), server(status: Int, code: String?, message: String?, retryAfter: TimeInterval? = nil) + case noPlayableSource, invalidRequest, invalidResponse, unauthenticated, staleSession, pinRequired, incompleteDeviceSession case keychain(Int32) var statusCode: Int? { - switch self { case .http(let code): code; case .server(let code, _, _): code; default: nil } + switch self { case .http(let code): code; case .server(let code, _, _, _): code; default: nil } } - var code: String? { if case .server(_, let code, _) = self { code } else { nil } } + var code: String? { if case .server(_, let code, _, _) = self { code } else { nil } } + var retryAfter: TimeInterval? { if case .server(_, _, _, let wait) = self { wait } else { nil } } + var isThrottled: Bool { statusCode == 429 || statusCode == 503 } + + /// Retry-After is either delay-seconds or an HTTP date. + static func retryAfter(_ header: String) -> TimeInterval? { + let value = header.trimmingCharacters(in: .whitespaces) + if let seconds = TimeInterval(value), seconds >= 0 { return seconds } + let format = DateFormatter() + format.locale = Locale(identifier: "en_US_POSIX"); format.timeZone = TimeZone(identifier: "GMT") + format.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz" + return format.date(from: value).map { max(0, $0.timeIntervalSinceNow) } + } + + // Backend messages are Uzbek and mostly uncoded, so only the code and status choose the text. var errorDescription: String? { switch self { - case .http(let code): "Server error (\(code))" - case .server(let status, let code, let message): + case .http(let code): String(localized: "Sozo could not be reached (\(code)). Please try again.") + case .server(let status, let code, _, let wait): switch code { - case "PIN_INVALID": "Incorrect PIN. Please try again." - case "PIN_REQUIRED": "Enter the PIN for this profile." - case "PROFILE_LIMIT": "The maximum number of profiles has been reached." - case "KIDS_PROFILE": "Switch to an adult profile to continue." - case "DEFAULT_PROFILE": "The default profile cannot be deleted or made a kids profile." - case "PROFILE_NOT_FOUND": "This profile could not be found." - case "PROFILE_NAME_TAKEN": "This profile name is already in use." - default: message ?? "Server error (\(status))" + case "PIN_INVALID": String(localized: "Incorrect PIN. Please try again.") + case "PIN_REQUIRED": String(localized: "Enter the PIN for this profile.") + case "PROFILE_LIMIT": String(localized: "The maximum number of profiles has been reached.") + case "KIDS_PROFILE": String(localized: "Switch to an adult profile to continue.") + case "DEFAULT_PROFILE": String(localized: "The default profile cannot be deleted or made a kids profile.") + case "PROFILE_NOT_FOUND": String(localized: "This profile was removed. Choose a profile to continue.") + case "PROFILE_NAME_TAKEN": String(localized: "This profile name is already in use.") + default: Self.describe(status: status, retryAfter: wait) } - case .noPlayableSource: "This video could not be opened on Apple TV." - case .invalidRequest: "The request address is invalid." - case .unauthenticated: "Link this Apple TV again." - case .staleSession: "The profile or account changed. Please try again." - case .pinRequired: "Enter the PIN for this profile." - case .incompleteDeviceSession: "The sign-in response was incomplete. Link this Apple TV again." - case .keychain: "Your sign-in could not be saved securely." + case .noPlayableSource: String(localized: "This video could not be opened on Apple TV.") + case .invalidRequest: String(localized: "The request address is invalid.") + case .invalidResponse: String(localized: "Sozo sent a response this app could not read. Please try again later.") + case .unauthenticated: String(localized: "Link this Apple TV again.") + case .staleSession: String(localized: "The profile or account changed. Please try again.") + case .pinRequired: String(localized: "Enter the PIN for this profile.") + case .incompleteDeviceSession: String(localized: "The sign-in response was incomplete. Link this Apple TV again.") + case .keychain: String(localized: "Your sign-in could not be saved securely.") + } + } + + static func describe(status: Int, retryAfter: TimeInterval?) -> String { + let seconds = retryAfter.map { max(1, Int($0.rounded(.up))) } + switch status { + case 429: + if let seconds { return String(localized: "Too many requests. Try again in \(seconds) seconds.") } + return String(localized: "Too many requests. Please wait a moment and try again.") + case 503: + if let seconds { return String(localized: "Sozo is busy right now. Try again in \(seconds) seconds.") } + return String(localized: "Sozo is busy right now. Please try again in a moment.") + case 400: return String(localized: "The request could not be completed. Please try again.") + case 401: return String(localized: "Link this Apple TV again.") + case 403: return String(localized: "This account is not allowed to do this.") + case 404: return String(localized: "This could not be found. It may have been removed.") + case 409: return String(localized: "This changed on another device. Refresh and try again.") + case 410: return String(localized: "This is no longer available.") + case 408, 504: return String(localized: "Sozo took too long to respond. Please try again.") + case 500...599: return String(localized: "Sozo is having trouble right now (\(status)). Please try again.") + default: return String(localized: "Something went wrong (\(status)). Please try again.") } } } diff --git a/apple-tv/SozoTV/ContinueWatching.swift b/apple-tv/SozoTV/ContinueWatching.swift index 72f14bdb..85b6de95 100644 --- a/apple-tv/SozoTV/ContinueWatching.swift +++ b/apple-tv/SozoTV/ContinueWatching.swift @@ -1,6 +1,18 @@ import Foundation -struct ContinueWatchingEnvelope: Decodable { let items: [ContinueWatchingItem] } +struct ContinueWatchingEnvelope: Decodable { + let items: [ContinueWatchingItem] + private enum CodingKeys: String, CodingKey { case items } + private struct Row: Decodable { + let item: ContinueWatchingItem? + init(from decoder: Decoder) { item = try? ContinueWatchingItem(from: decoder) } + } + /// One malformed row is skipped instead of emptying the whole rail. + init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + items = (try c.decodeIfPresent([Row].self, forKey: .items) ?? []).compactMap(\.item) + } +} struct ContinueWatchingItem: Decodable, Identifiable { let provider: String let contentUrl: String diff --git a/apple-tv/SozoTV/DetailView.swift b/apple-tv/SozoTV/DetailView.swift index f69f5382..0c181b50 100644 --- a/apple-tv/SozoTV/DetailView.swift +++ b/apple-tv/SozoTV/DetailView.swift @@ -100,7 +100,11 @@ struct DetailView: View { .onAppear { visible = true } .onDisappear { visible = false; actionTask?.cancel() } .fullScreenCover(item: $playback, onDismiss: { - if reopenSourcePicker { reopenSourcePicker = false; showingSources = true } + if reopenSourcePicker, let episode = selectedEpisode { + // Signed stream URLs expire, so another source starts from a fresh resolution. + reopenSourcePicker = false + run { await resolve(episode, choosingSource: true) } + } else if pendingNextEpisode { pendingNextEpisode = false run { await playNextEpisode() } @@ -209,17 +213,25 @@ struct DetailView: View { } } catch { if current(scope) { self.error = error.localizedDescription } } } - private func resolve(_ episode: Episode) async { + private func resolve(_ episode: Episode, choosingSource: Bool = false) async { let scope = session.profileScopeIdentity - resolving = true; error = nil; sourceSwitchPositionMs = nil + resolving = true; error = nil + if !choosingSource { sourceSwitchPositionMs = nil } defer { resolving = false } do { let envelope: MediaEnvelope if !isSerial && !movieSources.isEmpty { + // Film sources come inline with the episodes reply and carry no media ref; fetch them again. + let value: EpisodePage = try await session.request("contents/episodes", query: [.init(name: "provider", value: provider), .init(name: "url", value: url), .init(name: "page", value: "1"), .init(name: "size", value: "100")]) + guard current(scope) else { return } + let movie = value.movieEnvelope + if let fresh = movie.videoSources, !fresh.isEmpty { + movieSources = fresh; movieSubtitles = movie.subtitles ?? []; movieHeaders = movie.headers ?? [:] + } envelope = MediaEnvelope(videoUrl: nil, type: nil, headers: movieHeaders, videoSources: movieSources, subtitles: movieSubtitles) } else { guard let ref = episode.mediaRef, !ref.isEmpty else { throw APIError.noPlayableSource } - envelope = try await session.request("contents/media", query: [.init(name: "provider", value: provider), .init(name: "ref", value: ref), .init(name: "lang", value: "sub")]) + envelope = try await session.request("contents/media", query: [.init(name: "provider", value: provider), .init(name: "ref", value: ref), .init(name: "lang", value: "sub")], timeout: APIClient.mediaTimeout) } guard current(scope) else { return } let options = envelope.playbackSources @@ -229,7 +241,7 @@ struct DetailView: View { let playable = PlaybackSourcePolicy.preferred(eligible, quality: UserDefaults.standard.string(forKey: choiceKey)) guard !playable.isEmpty else { error = "This source did not provide an Apple TV compatible stream. Embedded web pages, DASH and torrents cannot play here. Try another source or adjust your maximum quality setting."; return } candidates = playable; candidateHeaders = envelope.headers ?? [:]; candidateSubtitles = envelope.subtitles ?? []; selectedEpisode = episode - if playable.count == 1 { start(playable[0]) } else { showingSources = true } + if playable.count == 1 && !choosingSource { start(playable[0]) } else { showingSources = true } } catch { if current(scope) { self.error = error.localizedDescription } } } private var canPlayNextEpisode: Bool { diff --git a/apple-tv/SozoTV/DeviceLinkPolling.swift b/apple-tv/SozoTV/DeviceLinkPolling.swift new file mode 100644 index 00000000..b63ff615 --- /dev/null +++ b/apple-tv/SozoTV/DeviceLinkPolling.swift @@ -0,0 +1,25 @@ +import Foundation + +/// Device-link polling rides out brief outages and rate limits until the code itself expires. +enum DeviceLinkPolling { + static let maximumDelay: TimeInterval = 60 + + static func isTransient(_ error: Error) -> Bool { + if let error = error as? APIError { + if case .invalidResponse = error { return true } + guard let status = error.statusCode else { return false } + return status < 0 || status == 408 || status == 429 || status >= 500 + } + guard let error = error as? URLError else { return false } + return [.timedOut, .networkConnectionLost, .notConnectedToInternet, .cannotConnectToHost, .cannotFindHost, + .dnsLookupFailed, .badServerResponse, .resourceUnavailable, .dataNotAllowed, .internationalRoamingOff, + .secureConnectionFailed].contains(error.code) + } + + /// The server's interval while healthy, doubling per consecutive failure; Retry-After is a floor. + static func delay(interval: Int, failures: Int, retryAfter: TimeInterval? = nil) -> TimeInterval { + let base = TimeInterval(max(interval, 1)) + let backoff = base * pow(2, Double(min(max(failures, 0), 6))) + return min(maximumDelay, max(backoff, retryAfter ?? 0)) + } +} diff --git a/apple-tv/SozoTV/RootView.swift b/apple-tv/SozoTV/RootView.swift index 2f4e95e7..0a9d1b9e 100644 --- a/apple-tv/SozoTV/RootView.swift +++ b/apple-tv/SozoTV/RootView.swift @@ -86,17 +86,30 @@ struct DeviceLinkView: View { do { let value = try await session.createDeviceCode() try Task.checkCancellation() - code = value; expiresAt = Date().addingTimeInterval(TimeInterval(max(1, value.expiresIn))); loading = false - for _ in 0.. 0 { + let wait = DeviceLinkPolling.delay(interval: value.interval, failures: failures, retryAfter: retryAfter) + try await Task.sleep(for: .seconds(min(wait, max(1, deadline.timeIntervalSinceNow)))) + let result: DeviceToken + do { result = try await session.pollDeviceToken(value.deviceCode) } + catch where DeviceLinkPolling.isTransient(error) && !Task.isCancelled { + failures += 1; retryAfter = (error as? APIError)?.retryAfter + continue + } + failures = 0; retryAfter = nil try Task.checkCancellation() if result.accessToken != nil { try await session.accept(result); return } - if result.status == "denied" { code = nil; message = "Sign-in was declined. Get a new code to try again."; return } if result.status == "expired" { break } } code = nil; message = "This code has expired. Get a new code to continue." - } catch is CancellationError {} catch { if !Task.isCancelled { code = nil; message = error.localizedDescription } } + } catch is CancellationError {} catch { + guard !Task.isCancelled else { return } + code = nil + let status = (error as? APIError)?.statusCode + message = status == 404 || status == 410 ? String(localized: "This code is no longer valid. Get a new code to continue.") : error.localizedDescription + } } } diff --git a/apple-tv/SozoTV/SessionStore.swift b/apple-tv/SozoTV/SessionStore.swift index f8aa4dda..ba3e3074 100644 --- a/apple-tv/SozoTV/SessionStore.swift +++ b/apple-tv/SozoTV/SessionStore.swift @@ -53,7 +53,8 @@ final class SessionStore: ObservableObject { /// Authenticated calls capture their profile before awaiting; replies from old scopes never escape. func request(_ path: String, query: [URLQueryItem] = [], method: String = "GET", - body: [String: Any]? = nil, profileScoped: Bool = true) async throws -> T { + body: [String: Any]? = nil, profileScoped: Bool = true, + timeout: TimeInterval = APIClient.defaultTimeout) async throws -> T { let generation = accountGeneration, scopeRevision = revision let profile = profileScoped ? activeProfile?.id : nil guard let initial = credentials?.accessToken else { throw APIError.unauthenticated } @@ -62,17 +63,30 @@ final class SessionStore: ObservableObject { try Task.checkCancellation() } do { - let value: T = try await api.request(path, query: query, method: method, body: body, token: initial, profileId: profile) - try validate(); return value - } catch let failure as APIError where failure.statusCode == 401 { - try validate() - let fresh = try await refreshedToken(rejected: initial) - try validate() - let value: T = try await api.request(path, query: query, method: method, body: body, token: fresh, profileId: profile) - try validate(); return value + do { + let value: T = try await api.request(path, query: query, method: method, body: body, token: initial, profileId: profile, timeout: timeout) + try validate(); return value + } catch let failure as APIError where failure.statusCode == 401 { + try validate() + let fresh = try await refreshedToken(rejected: initial) + try validate() + let value: T = try await api.request(path, query: query, method: method, body: body, token: fresh, profileId: profile, timeout: timeout) + try validate(); return value + } + } catch let failure as APIError where failure.code == "PROFILE_NOT_FOUND" { + if let profile, generation == accountGeneration, activeProfile?.id == profile { profileRemoved(profile) } + throw failure } } + /// The active profile was deleted elsewhere: drop it, so RootView shows the picker, and reload the list. + private func profileRemoved(_ id: String) { + profiles.removeAll { $0.id == id } + activeProfile = nil; revision &+= 1 + defaults.removeObject(forKey: profileKey) + Task { await loadProfiles() } + } + private func refreshedToken(rejected: String) async throws -> String { guard let current = credentials else { throw APIError.unauthenticated } if current.accessToken != rejected { return current.accessToken } diff --git a/apple-tv/Tests/ContinueWatching/main.swift b/apple-tv/Tests/ContinueWatching/main.swift index 87849d50..de57f32f 100644 --- a/apple-tv/Tests/ContinueWatching/main.swift +++ b/apple-tv/Tests/ContinueWatching/main.swift @@ -5,5 +5,8 @@ do { precondition(history.items.count == 2 && history.items[0].episodeNumber == nil) precondition(history.items[0].context.episodeIndex == 12 && history.items[0].canResume) precondition(history.items[1].canResume) - print("PASS: fractional mobile history preserves its episode index and other resume entries") + let mixed = Data(#"{"items":[{"provider":"source","contentUrl":"a","positionMs":1000,"durationMs":60000},{"provider":"source","contentUrl":"b","episodeIndex":"7"},{"contentUrl":"c"},42,{"provider":"source","contentUrl":"d","positionMs":2000,"durationMs":60000}]}"#.utf8) + let rows = try JSONDecoder().decode(ContinueWatchingEnvelope.self, from: mixed).items + precondition(rows.map(\.contentUrl) == ["a", "d"], "bad rows are skipped, good rows kept") + print("PASS: fractional mobile history preserves its episode index and other resume entries; bad rows do not hide the rail") } catch { print("FAIL: fractional history decoding: \(error)"); exit(1) } diff --git a/apple-tv/Tests/DeviceLinkPolling/main.swift b/apple-tv/Tests/DeviceLinkPolling/main.swift new file mode 100644 index 00000000..53c517d5 --- /dev/null +++ b/apple-tv/Tests/DeviceLinkPolling/main.swift @@ -0,0 +1,17 @@ +import Foundation + +precondition(DeviceLinkPolling.delay(interval: 5, failures: 0) == 5, "healthy polling keeps the server interval") +precondition(DeviceLinkPolling.delay(interval: 5, failures: 2) == 20, "failures back off exponentially") +precondition(DeviceLinkPolling.delay(interval: 5, failures: 40) == DeviceLinkPolling.maximumDelay, "backoff is capped") +precondition(DeviceLinkPolling.delay(interval: 5, failures: 1, retryAfter: 30) == 30, "Retry-After is honoured") +precondition(DeviceLinkPolling.delay(interval: 0, failures: 0) == 1, "zero interval never spins") +for status in [429, 500, 502, 503, 504] { + precondition(DeviceLinkPolling.isTransient(APIError.server(status: status, code: nil, message: nil)), "\(status) retries") +} +for status in [400, 403, 404, 410] { + precondition(!DeviceLinkPolling.isTransient(APIError.server(status: status, code: nil, message: nil)), "\(status) stops") +} +precondition(DeviceLinkPolling.isTransient(URLError(.timedOut)) && DeviceLinkPolling.isTransient(URLError(.notConnectedToInternet)), "network blips retry") +precondition(!DeviceLinkPolling.isTransient(URLError(.cancelled)) && !DeviceLinkPolling.isTransient(CancellationError()), "cancellation stops") +precondition(DeviceLinkPolling.isTransient(APIError.invalidResponse), "a garbled reply retries") +print("PASS: device-link polling backs off, honours Retry-After and stops only on permanent errors") diff --git a/apple-tv/Tests/SessionTransportChecks.swift b/apple-tv/Tests/SessionTransportChecks.swift index 732fb068..057ff41d 100644 --- a/apple-tv/Tests/SessionTransportChecks.swift +++ b/apple-tv/Tests/SessionTransportChecks.swift @@ -4,6 +4,7 @@ private struct Stub { let status: Int let body: String var delay: Double = 0 + var headers: [String: String] = [:] } private final class StubProtocol: URLProtocol, @unchecked Sendable { static let lock = NSLock() @@ -18,7 +19,7 @@ private final class StubProtocol: URLProtocol, @unchecked Sendable { stateLock.lock(); let canceled = stopped; stateLock.unlock() guard !canceled else { return } client?.urlProtocol(self, didReceive: HTTPURLResponse(url: request.url!, statusCode: stub.status, - httpVersion: "HTTP/1.1", headerFields: ["Content-Type": "application/json"])!, cacheStoragePolicy: .notAllowed) + httpVersion: "HTTP/1.1", headerFields: stub.headers.merging(["Content-Type": "application/json"]) { a, _ in a })!, cacheStoragePolicy: .notAllowed) client?.urlProtocol(self, didLoad: Data(stub.body.utf8)) client?.urlProtocolDidFinishLoading(self) } @@ -53,7 +54,9 @@ private func require(_ condition: @autoclosure () -> Bool, _ label: String) { try await logoutDuringRefresh() try await pinAndDraft() try await staleProfileSelection() - print("PASS: refresh coalescing and atomic persistence; profile response isolation; logout rotation revocation; PIN and draft contracts; stale profile selection protection") + try await removedProfile() + try await errorPresentation() + print("PASS: refresh coalescing and atomic persistence; profile response isolation; logout rotation revocation; PIN and draft contracts; stale profile selection protection; removed profile recovery; error presentation and Retry-After") } @MainActor static func concurrentRefresh() async throws { let memory = MemoryCredentials(); let session = make(memory) @@ -149,6 +152,59 @@ private func require(_ condition: @autoclosure () -> Bool, _ label: String) { require(session.activeProfile?.name == "Updated child", "selection keeps current display metadata") } + @MainActor static func removedProfile() async throws { + let session = make(MemoryCredentials()) + var removed = false + StubProtocol.handler = { request in + if request.url!.path.hasSuffix("/profiles") { + return Stub(status: 200, body: removed + ? "{\"profiles\":[{\"id\":\"p1\",\"name\":\"One\",\"hasPin\":true},{\"id\":\"p3\",\"name\":\"Three\"}],\"max\":4}" + : profileJSON) + } + return Stub(status: 404, body: "{\"message\":\"Profil topilmadi\",\"code\":\"PROFILE_NOT_FOUND\"}") + } + await session.loadProfiles() + try await session.select(session.profiles[1]) + removed = true + do { let _: Value = try await session.request("history"); fatalError("Removed profile request succeeded") } + catch let error as APIError { require(error.code == "PROFILE_NOT_FOUND", "removed profile error surfaces") } + require(session.activeProfile == nil, "removed profile is no longer active, so the picker shows") + for _ in 0..<50 where session.profiles.map(\.id) != ["p1", "p3"] { try await Task.sleep(nanoseconds: 10_000_000) } + require(session.profiles.map(\.id) == ["p1", "p3"], "profiles reloaded after removal") + require(session.activeProfile == nil, "no profile chosen on the viewer's behalf") + } + + @MainActor static func errorPresentation() async throws { + let session = make(MemoryCredentials()) + var calls = 0 + StubProtocol.handler = { request in + calls += 1 + if request.url!.path.hasSuffix("busy") { + return calls == 1 ? Stub(status: 503, body: "{\"message\":\"Server hozir bandlik darajasida\"}", headers: ["Retry-After": "0"]) + : Stub(status: 200, body: "{\"value\":5}") + } + if request.url!.path.hasSuffix("limited") { + return Stub(status: 429, body: "{\"message\":\"Juda ko'p so'rov\"}", headers: ["Retry-After": "30"]) + } + return Stub(status: 200, body: "{\"unexpected\":true}") + } + let value: Value = try await session.request("busy", profileScoped: false) + require(value.value == 5 && calls == 2, "short Retry-After on a GET is waited out once") + calls = 0 + do { let _: Value = try await session.request("limited", profileScoped: false); fatalError("429 succeeded") } + catch let error as APIError { + require(calls == 1 && error.retryAfter == 30, "long Retry-After is reported, not slept through") + let text = error.localizedDescription + require(text == "Too many requests. Try again in 30 seconds." && !text.contains("so'rov"), "no Uzbek backend text: \(text)") + } + do { let _: Value = try await session.request("shape", profileScoped: false); fatalError("bad shape decoded") } + catch let error as APIError { + guard case .invalidResponse = error else { fatalError("FAILED: decode error kept Foundation text") } + } + require(APIError.server(status: 403, code: nil, message: "Hisobingiz bloklangan").localizedDescription == "This account is not allowed to do this.", "uncoded 403 is English") + require(APIError.retryAfter("Wed, 21 Oct 2015 07:28:00 GMT") == 0, "past HTTP date clamps to zero") + } + @MainActor static func pinAndDraft() async throws { let session = make(MemoryCredentials()) StubProtocol.handler = { request in diff --git a/apple-tv/scripts/check-profiles.sh b/apple-tv/scripts/check-profiles.sh index 1391ef00..0151c047 100755 --- a/apple-tv/scripts/check-profiles.sh +++ b/apple-tv/scripts/check-profiles.sh @@ -16,6 +16,8 @@ swiftc SozoTV/Models.swift SozoTV/PlaybackSourcePolicy.swift Tests/PlaybackSourc "$check_dir/sources" swiftc SozoTV/ProfileRequestState.swift Tests/ProfileRequestChecks.swift -o "$check_dir/requests" "$check_dir/requests" +swiftc SozoTV/Models.swift SozoTV/APIClient.swift SozoTV/DeviceLinkPolling.swift Tests/DeviceLinkPolling/main.swift -o "$check_dir/polling" +"$check_dir/polling" swiftc SozoTV/Models.swift SozoTV/PlaybackHistoryContext.swift SozoTV/ContinueWatching.swift Tests/ContinueWatching/main.swift -o "$check_dir/continuing" "$check_dir/continuing" From 4ce062fe7b09e4963bba2a58354e57fa4b972d3b Mon Sep 17 00:00:00 2001 From: professorDeveloper <108933534+professorDeveloper@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:02:35 +0500 Subject: [PATCH 2/2] Apple TV: keep the active profile when only a managed profile is gone The backend returns PROFILE_NOT_FOUND both for a missing active profile and for a missing target of a profile edit, delete or PIN check. Reload the listing instead of assuming the active one was deleted, as the phone app does. Switching sources falls back to the earlier candidates when the fresh resolution fails, and films refetch their inline sources only on a switch. A string episodeIndex in history is read like a string episodeNumber. --- apple-tv/SozoTV/APIClient.swift | 1 + apple-tv/SozoTV/ContinueWatching.swift | 3 ++- apple-tv/SozoTV/DetailView.swift | 25 +++++++++++------- apple-tv/SozoTV/SessionStore.swift | 12 +++------ apple-tv/Tests/ContinueWatching/main.swift | 5 ++-- apple-tv/Tests/SessionTransportChecks.swift | 29 +++++++++++++-------- 6 files changed, 43 insertions(+), 32 deletions(-) diff --git a/apple-tv/SozoTV/APIClient.swift b/apple-tv/SozoTV/APIClient.swift index e7bda99f..29633b22 100644 --- a/apple-tv/SozoTV/APIClient.swift +++ b/apple-tv/SozoTV/APIClient.swift @@ -135,6 +135,7 @@ enum APIError: LocalizedError { // Backend messages are Uzbek and mostly uncoded, so only the code and status choose the text. var errorDescription: String? { switch self { + case .http(let code) where code < 0: String(localized: "Sozo could not be reached. Please try again.") case .http(let code): String(localized: "Sozo could not be reached (\(code)). Please try again.") case .server(let status, let code, _, let wait): switch code { diff --git a/apple-tv/SozoTV/ContinueWatching.swift b/apple-tv/SozoTV/ContinueWatching.swift index 85b6de95..08ff2a53 100644 --- a/apple-tv/SozoTV/ContinueWatching.swift +++ b/apple-tv/SozoTV/ContinueWatching.swift @@ -35,7 +35,8 @@ struct ContinueWatchingItem: Decodable, Identifiable { let number = (try? c.decode(Double.self, forKey: .episodeNumber)) ?? (try? c.decode(String.self, forKey: .episodeNumber)).flatMap(Double.init) episodeNumber = number.flatMap { Int(exactly: $0) } - episodeIndex = try c.decodeIfPresent(Int.self, forKey: .episodeIndex) + episodeIndex = (try? c.decode(Int.self, forKey: .episodeIndex)) + ?? (try? c.decode(String.self, forKey: .episodeIndex)).flatMap { Int($0) } positionMs = try c.decodeIfPresent(Int64.self, forKey: .positionMs) durationMs = try c.decodeIfPresent(Int64.self, forKey: .durationMs) deletedAt = try c.decodeIfPresent(String.self, forKey: .deletedAt) diff --git a/apple-tv/SozoTV/DetailView.swift b/apple-tv/SozoTV/DetailView.swift index 0c181b50..f2f688c5 100644 --- a/apple-tv/SozoTV/DetailView.swift +++ b/apple-tv/SozoTV/DetailView.swift @@ -100,10 +100,10 @@ struct DetailView: View { .onAppear { visible = true } .onDisappear { visible = false; actionTask?.cancel() } .fullScreenCover(item: $playback, onDismiss: { - if reopenSourcePicker, let episode = selectedEpisode { + if reopenSourcePicker { // Signed stream URLs expire, so another source starts from a fresh resolution. reopenSourcePicker = false - run { await resolve(episode, choosingSource: true) } + if let episode = selectedEpisode { run { await resolve(episode, choosingSource: true) } } } else if pendingNextEpisode { pendingNextEpisode = false @@ -221,12 +221,14 @@ struct DetailView: View { do { let envelope: MediaEnvelope if !isSerial && !movieSources.isEmpty { - // Film sources come inline with the episodes reply and carry no media ref; fetch them again. - let value: EpisodePage = try await session.request("contents/episodes", query: [.init(name: "provider", value: provider), .init(name: "url", value: url), .init(name: "page", value: "1"), .init(name: "size", value: "100")]) - guard current(scope) else { return } - let movie = value.movieEnvelope - if let fresh = movie.videoSources, !fresh.isEmpty { - movieSources = fresh; movieSubtitles = movie.subtitles ?? []; movieHeaders = movie.headers ?? [:] + // Film sources come inline with the episodes reply and carry no media ref; refresh them + // before switching sources, and keep the loaded ones if that fails. + if choosingSource, let value: EpisodePage = try? await session.request("contents/episodes", query: [.init(name: "provider", value: provider), .init(name: "url", value: url), .init(name: "page", value: "1"), .init(name: "size", value: "100")]) { + guard current(scope) else { return } + let movie = value.movieEnvelope + if let fresh = movie.videoSources, !fresh.isEmpty { + movieSources = fresh; movieSubtitles = movie.subtitles ?? []; movieHeaders = movie.headers ?? [:] + } } envelope = MediaEnvelope(videoUrl: nil, type: nil, headers: movieHeaders, videoSources: movieSources, subtitles: movieSubtitles) } else { @@ -242,7 +244,12 @@ struct DetailView: View { guard !playable.isEmpty else { error = "This source did not provide an Apple TV compatible stream. Embedded web pages, DASH and torrents cannot play here. Try another source or adjust your maximum quality setting."; return } candidates = playable; candidateHeaders = envelope.headers ?? [:]; candidateSubtitles = envelope.subtitles ?? []; selectedEpisode = episode if playable.count == 1 && !choosingSource { start(playable[0]) } else { showingSources = true } - } catch { if current(scope) { self.error = error.localizedDescription } } + } catch { + guard current(scope) else { return } + if choosingSource, selectedEpisode?.id == episode.id, !candidates.isEmpty { showingSources = true; return } + sourceSwitchPositionMs = nil + self.error = error.localizedDescription + } } private var canPlayNextEpisode: Bool { guard isSerial, let selectedEpisode, diff --git a/apple-tv/SozoTV/SessionStore.swift b/apple-tv/SozoTV/SessionStore.swift index ba3e3074..ddd395a0 100644 --- a/apple-tv/SozoTV/SessionStore.swift +++ b/apple-tv/SozoTV/SessionStore.swift @@ -74,19 +74,13 @@ final class SessionStore: ObservableObject { try validate(); return value } } catch let failure as APIError where failure.code == "PROFILE_NOT_FOUND" { - if let profile, generation == accountGeneration, activeProfile?.id == profile { profileRemoved(profile) } + // The missing profile may be the active one or only the target of a profile edit, PIN check or delete. + // A fresh listing tells them apart; loadProfiles drops the active profile only when it is gone. + if profile != nil, generation == accountGeneration, path != "auth/profiles" { Task { await loadProfiles() } } throw failure } } - /// The active profile was deleted elsewhere: drop it, so RootView shows the picker, and reload the list. - private func profileRemoved(_ id: String) { - profiles.removeAll { $0.id == id } - activeProfile = nil; revision &+= 1 - defaults.removeObject(forKey: profileKey) - Task { await loadProfiles() } - } - private func refreshedToken(rejected: String) async throws -> String { guard let current = credentials else { throw APIError.unauthenticated } if current.accessToken != rejected { return current.accessToken } diff --git a/apple-tv/Tests/ContinueWatching/main.swift b/apple-tv/Tests/ContinueWatching/main.swift index de57f32f..80d6e906 100644 --- a/apple-tv/Tests/ContinueWatching/main.swift +++ b/apple-tv/Tests/ContinueWatching/main.swift @@ -5,8 +5,9 @@ do { precondition(history.items.count == 2 && history.items[0].episodeNumber == nil) precondition(history.items[0].context.episodeIndex == 12 && history.items[0].canResume) precondition(history.items[1].canResume) - let mixed = Data(#"{"items":[{"provider":"source","contentUrl":"a","positionMs":1000,"durationMs":60000},{"provider":"source","contentUrl":"b","episodeIndex":"7"},{"contentUrl":"c"},42,{"provider":"source","contentUrl":"d","positionMs":2000,"durationMs":60000}]}"#.utf8) + let mixed = Data(#"{"items":[{"provider":"source","contentUrl":"a","positionMs":1000,"durationMs":60000},{"provider":"source","contentUrl":"b","positionMs":"soon"},{"provider":"source","contentUrl":"e","isSerial":true,"episodeIndex":"7","positionMs":1000,"durationMs":60000},{"contentUrl":"c"},42,{"provider":"source","contentUrl":"d","positionMs":2000,"durationMs":60000}]}"#.utf8) let rows = try JSONDecoder().decode(ContinueWatchingEnvelope.self, from: mixed).items - precondition(rows.map(\.contentUrl) == ["a", "d"], "bad rows are skipped, good rows kept") + precondition(rows.map(\.contentUrl) == ["a", "e", "d"], "bad rows are skipped, good rows kept") + precondition(rows[1].episodeIndex == 7 && rows[1].canResume, "a string episode index is read like a string episode number") print("PASS: fractional mobile history preserves its episode index and other resume entries; bad rows do not hide the rail") } catch { print("FAIL: fractional history decoding: \(error)"); exit(1) } diff --git a/apple-tv/Tests/SessionTransportChecks.swift b/apple-tv/Tests/SessionTransportChecks.swift index 057ff41d..bceb1888 100644 --- a/apple-tv/Tests/SessionTransportChecks.swift +++ b/apple-tv/Tests/SessionTransportChecks.swift @@ -154,24 +154,30 @@ private func require(_ condition: @autoclosure () -> Bool, _ label: String) { @MainActor static func removedProfile() async throws { let session = make(MemoryCredentials()) - var removed = false + var listing = "{\"profiles\":[{\"id\":\"p1\",\"name\":\"One\",\"isDefault\":true},{\"id\":\"p2\",\"name\":\"Two\"},{\"id\":\"p3\",\"name\":\"Three\"}],\"max\":4}" StubProtocol.handler = { request in - if request.url!.path.hasSuffix("/profiles") { - return Stub(status: 200, body: removed - ? "{\"profiles\":[{\"id\":\"p1\",\"name\":\"One\",\"hasPin\":true},{\"id\":\"p3\",\"name\":\"Three\"}],\"max\":4}" - : profileJSON) - } + if request.url!.path.hasSuffix("/profiles") { return Stub(status: 200, body: listing) } return Stub(status: 404, body: "{\"message\":\"Profil topilmadi\",\"code\":\"PROFILE_NOT_FOUND\"}") } + func settle(_ ids: [String]) async throws { + for _ in 0..<50 where session.profiles.map(\.id) != ids { try await Task.sleep(nanoseconds: 10_000_000) } + require(session.profiles.map(\.id) == ids, "profiles reloaded to \(ids)") + } await session.loadProfiles() try await session.select(session.profiles[1]) - removed = true + + // Another device deleted the profile being managed, not the one watching. + listing = "{\"profiles\":[{\"id\":\"p1\",\"name\":\"One\",\"isDefault\":true},{\"id\":\"p2\",\"name\":\"Two\"}],\"max\":4}" + do { try await session.deleteProfile(id: "p3"); fatalError("Deleting a missing profile succeeded") } + catch let error as APIError { require(error.code == "PROFILE_NOT_FOUND", "missing target error surfaces") } + try await settle(["p1", "p2"]) + require(session.activeProfile?.id == "p2", "a missing target profile leaves the active profile selected") + + listing = "{\"profiles\":[{\"id\":\"p1\",\"name\":\"One\",\"hasPin\":true},{\"id\":\"p3\",\"name\":\"Three\"}],\"max\":4}" do { let _: Value = try await session.request("history"); fatalError("Removed profile request succeeded") } catch let error as APIError { require(error.code == "PROFILE_NOT_FOUND", "removed profile error surfaces") } - require(session.activeProfile == nil, "removed profile is no longer active, so the picker shows") - for _ in 0..<50 where session.profiles.map(\.id) != ["p1", "p3"] { try await Task.sleep(nanoseconds: 10_000_000) } - require(session.profiles.map(\.id) == ["p1", "p3"], "profiles reloaded after removal") - require(session.activeProfile == nil, "no profile chosen on the viewer's behalf") + try await settle(["p1", "p3"]) + require(session.activeProfile == nil, "removed active profile is dropped, so the picker shows") } @MainActor static func errorPresentation() async throws { @@ -203,6 +209,7 @@ private func require(_ condition: @autoclosure () -> Bool, _ label: String) { } require(APIError.server(status: 403, code: nil, message: "Hisobingiz bloklangan").localizedDescription == "This account is not allowed to do this.", "uncoded 403 is English") require(APIError.retryAfter("Wed, 21 Oct 2015 07:28:00 GMT") == 0, "past HTTP date clamps to zero") + require(!APIError.http(-1).localizedDescription.contains("-1"), "internal sentinel status is not shown") } @MainActor static func pinAndDraft() async throws {