diff --git a/apple-tv/SozoTV/APIClient.swift b/apple-tv/SozoTV/APIClient.swift index 197f90bb..9ed3028f 100644 --- a/apple-tv/SozoTV/APIClient.swift +++ b/apple-tv/SozoTV/APIClient.swift @@ -14,16 +14,24 @@ 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 static let mediaSegmentEndpoint = defaultBase.appendingPathComponent("contents/media-segment") 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 @@ -33,7 +41,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") @@ -43,13 +51,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 } @@ -75,7 +94,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) } } @@ -94,34 +113,71 @@ 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 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) } } - var code: String? { if case .server(_, let code, _) = self { code } else { nil } } + + // 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) 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 { - 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..08ff2a53 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 @@ -23,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 f69f5382..4da5d420 100644 --- a/apple-tv/SozoTV/DetailView.swift +++ b/apple-tv/SozoTV/DetailView.swift @@ -19,7 +19,13 @@ struct DetailView: View { @State private var sourceSwitchPositionMs: Int64? @State private var pendingNextEpisode = false @State private var error: String? - @State private var saved = false + @State private var notice: String? + @State private var favorite: Bool? + @State private var pendingRetry: (episode: Episode, source: VideoSource?, positionMs: Int64?)? + @State private var playingSource: VideoSource? + @State private var primaryFocused = false + @FocusState private var focus: DetailFocus? + private enum DetailFocus: Hashable { case primary, episode(Int) } @State private var saving = false @State private var resolving = false @State private var loading = false @@ -53,15 +59,17 @@ struct DetailView: View { Text(([detail?.year?.text].compactMap { $0 } + (detail?.genres ?? [])).joined(separator: " · ")).font(.system(size: 22)).foregroundStyle(.secondary) Text(detail?.description ?? "").font(.system(size: 24)).foregroundStyle(.secondary).frame(maxWidth: 1100, alignment: .leading) if loading || resolving || saving { SozoLoadingState(title: loading ? "Loading title…" : resolving ? "Finding playable sources…" : "Saving…") } - if saved { Label("Saved to this profile", systemImage: "checkmark.circle").foregroundStyle(.green) } + if let notice { Label(notice, systemImage: "checkmark.circle").foregroundStyle(.green) } if let error { Text(error).foregroundStyle(.red).accessibilityIdentifier("detail.error") Button { run { await load() } } label: { SozoActionLabel(title: "Reload title", symbol: "arrow.clockwise") }.buttonStyle(SozoProfileButtonStyle()).disabled(busy) } SozoGlassGroup { HStack(spacing: 24) { - Button { run { await saveTo("auth/favorites") } } label: { SozoActionLabel(title: "Add to favorites", symbol: "heart") } - Button { run { await saveTo("auth/lists/watch-later") } } label: { SozoActionLabel(title: "Watch later", symbol: "bookmark") } + Button { run { await toggleFavorite() } } label: { + SozoActionLabel(title: favorite == true ? "Remove from favorites" : "Add to favorites", symbol: favorite == true ? "heart.fill" : "heart") + }.accessibilityIdentifier("detail.favorite") + Button { run { await saveTo("auth/lists/watch-later", notice: "Added to Watch later") } } label: { SozoActionLabel(title: "Watch later", symbol: "bookmark") } }.buttonStyle(SozoProfileButtonStyle()).disabled(busy || url.isEmpty) } if loadComplete { @@ -85,22 +93,37 @@ struct DetailView: View { if episodeList.isEmpty { SozoEmptyState(title: "No episodes", message: "No episodes are available from this source.", symbol: "film.stack") } LazyVGrid(columns: [GridItem(.adaptive(minimum: 260), spacing: 22)], spacing: 24) { ForEach(visibleEpisodes) { episode in - episodeButton(episode, index: episodeList.firstIndex(where: { $0.id == episode.id }) ?? 0) + episodeButton(episode, index: episodeList.firstIndex(where: { $0.id == episode.id }) ?? 0, primary: episode.id == primaryEpisodeID) } } if hasMore { Button { run { await loadPage() } } label: { SozoActionLabel(title: loadingPage ? "Loading episodes…" : "Load more episodes", symbol: "plus") }.buttonStyle(SozoProfileButtonStyle()).disabled(busy).accessibilityIdentifier("detail.episodes.more") } } else { - episodeButton(Episode(episode: nil, label: resumePosition(for: nil) > 0 ? "Resume film" : "Play film", mediaRef: episodeList.first?.mediaRef ?? url, image: card.thumbnail), index: 0) + episodeButton(Episode(episode: nil, label: resumePosition(for: nil) > 0 ? "Resume film" : "Play film", mediaRef: episodeList.first?.mediaRef ?? url, image: card.thumbnail), index: 0, primary: true) } } }.padding(70) } } .task(id: session.profileScopeIdentity) { visible = true; await load() } + .task(id: session.profileScopeIdentity) { await loadFavorite() } + .defaultFocus($focus, .primary) + .onChange(of: loadComplete && !busy) { _, ready in + // Land on Play or the episodes, not the save row above them. + guard ready, !primaryFocused else { return } + primaryFocused = true; focus = .primary + } .onAppear { visible = true } .onDisappear { visible = false; actionTask?.cancel() } .fullScreenCover(item: $playback, onDismiss: { - if reopenSourcePicker { reopenSourcePicker = false; showingSources = true } + if let retry = pendingRetry { + pendingRetry = nil + run { await resolve(retry.episode, retrying: retry.source, positionMs: retry.positionMs) } + } + else if reopenSourcePicker { + // Signed stream URLs expire, so another source starts from a fresh resolution. + reopenSourcePicker = false + if let episode = selectedEpisode { run { await resolve(episode, choosingSource: true) } } + } else if pendingNextEpisode { pendingNextEpisode = false run { await playNextEpisode() } @@ -112,7 +135,8 @@ struct DetailView: View { } reopenSourcePicker = true; playback = nil }, - nextEpisode: canPlayNextEpisode ? { pendingNextEpisode = true; playback = nil } : nil).ignoresSafeArea() + nextEpisode: canPlayNextEpisode ? { pendingNextEpisode = true; playback = nil } : nil, + retry: retryAction(for: item)).ignoresSafeArea() } .sheet(isPresented: $showingSources) { VStack(alignment: .leading, spacing: 24) { @@ -141,13 +165,29 @@ struct DetailView: View { }.padding(60) } } - private func episodeButton(_ episode: Episode, index: Int) -> some View { + /// Resolves again rather than replaying the URL, because signed links expire. + private func retryAction(for item: PlaybackItem) -> ((Double?) -> Void)? { + guard let episode = selectedEpisode else { return nil } + let source = playingSource + return { position in + var positionMs = item.history?.positionMs + if let position, position.isFinite, position >= 0, position < Double(Int64.max) / 1000 { positionMs = Int64(position * 1000) } + pendingRetry = (episode, source, positionMs) + playback = nil + } + } + private var primaryEpisodeID: Episode.ID? { + let resumed = EpisodeCatalog.resumedEpisode(in: episodeList, number: resume?.episodeNumber, index: resume?.episodeIndex) + if let resumed, visibleEpisodes.contains(where: { $0.id == resumed.id }) { return resumed.id } + return visibleEpisodes.first?.id + } + private func episodeButton(_ episode: Episode, index: Int, primary: Bool = false) -> some View { Button { run { await resolve(episode) } } label: { VStack(alignment: .leading, spacing: 10) { Text(episode.label ?? "Episode \(episode.episode ?? index + 1)").font(.system(size: 24, weight: .semibold)).lineLimit(2) if isSerial && resumePosition(for: episode) > 0 { Label("Resume", systemImage: "play.circle").font(.caption) } }.frame(maxWidth: .infinity, minHeight: 70, alignment: .leading).padding(20) - }.buttonStyle(SozoProfileButtonStyle()).disabled(busy).accessibilityIdentifier("detail.episode.\(index)") + }.buttonStyle(SozoProfileButtonStyle()).disabled(busy).focused($focus, equals: primary ? .primary : .episode(index)).accessibilityIdentifier("detail.episode.\(index)") } private func run(_ work: @escaping () async -> Void) { guard !busy else { return }; actionTask = Task { await work() } } private func current(_ scope: String) -> Bool { visible && !Task.isCancelled && session.profileScopeIdentity == scope } @@ -157,18 +197,40 @@ struct DetailView: View { guard let episode else { return 0 } return EpisodeCatalog.resumedEpisode(in: episodeList, number: resume.episodeNumber, index: resume.episodeIndex)?.id == episode.id ? resume.positionMs : 0 } - private func saveTo(_ path: String) async { + private func saveTo(_ path: String, notice message: String) async { let scope = session.profileScopeIdentity - saving = true; saved = false; error = nil + saving = true; notice = nil; error = nil defer { saving = false } do { let _: ProfileJSON = try await session.request(path, method: "POST", body: ["provider": provider, "contentUrl": url, "title": title, "thumbnail": detail?.thumbnail ?? card.thumbnail ?? ""]) - if current(scope) { saved = true } + if current(scope) { notice = message } } catch { if current(scope) { self.error = error.localizedDescription } } } + private func toggleFavorite() async { + guard favorite == true else { + await saveTo("auth/favorites", notice: "Added to favorites") + if notice != nil { favorite = true } + return + } + let scope = session.profileScopeIdentity + saving = true; notice = nil; error = nil + defer { saving = false } + do { + let _: ProfileJSON = try await session.request("auth/favorites", method: "DELETE", body: ["contentUrl": url]) + if current(scope) { favorite = false; notice = "Removed from favorites" } + } catch { if current(scope) { self.error = error.localizedDescription } } + } + /// Unknown stays nil so a failed lookup still offers Add. + private func loadFavorite() async { + let scope = session.profileScopeIdentity + favorite = nil + guard !url.isEmpty, let value: ProfileJSON = try? await session.request("auth/favorites") else { return } + guard current(scope), favorite == nil else { return } + favorite = value["items"].array.contains { $0["contentUrl"].string == url } + } private func load() async { let scope = session.profileScopeIdentity - loading = true; error = nil; loadComplete = false; episodeList = []; selectedSeason = nil; page = 0; hasMore = false; detail = nil; movieSources = []; movieSubtitles = []; movieHeaders = [:]; episodeSerial = nil; hasExternalSubtitles = false + loading = true; error = nil; notice = nil; primaryFocused = false; loadComplete = false; episodeList = []; selectedSeason = nil; page = 0; hasMore = false; detail = nil; movieSources = []; movieSubtitles = []; movieHeaders = [:]; episodeSerial = nil; hasExternalSubtitles = false defer { loading = false } do { let value: MediaDetail = try await session.request("contents/detail", query: [.init(name: "provider", value: provider), .init(name: "url", value: url)]) @@ -209,17 +271,22 @@ struct DetailView: View { } } catch { if current(scope) { self.error = error.localizedDescription } } } - private func resolve(_ episode: Episode) async { + private func resolve(_ episode: Episode, retrying failed: VideoSource? = nil, positionMs: Int64? = nil, choosingSource: Bool = false) async { let scope = session.profileScopeIdentity - resolving = true; error = nil; sourceSwitchPositionMs = nil + resolving = true; error = nil + if failed != nil { sourceSwitchPositionMs = positionMs } else if !choosingSource { sourceSwitchPositionMs = nil } defer { resolving = false } do { let envelope: MediaEnvelope if !isSerial && !movieSources.isEmpty { + if failed != nil || choosingSource { + await refreshMovieSources() + guard current(scope) else { return } + } 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,8 +296,26 @@ 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 } - } catch { if current(scope) { self.error = error.localizedDescription } } + let same = failed.flatMap { failed in + playable.first { $0.videoUrl == failed.videoUrl } ?? playable.first { $0.quality == failed.quality && $0.type == failed.type } + } + if let source = same { start(source) } + else if playable.count == 1 && !choosingSource { start(playable[0]) } + else { showingSources = true } + } catch { + guard current(scope) else { return } + if choosingSource, selectedEpisode?.id == episode.id, !candidates.isEmpty { showingSources = true; return } + sourceSwitchPositionMs = nil + self.error = error.localizedDescription + } + } + /// A film's links come with the first episode page; fetch it again so a retry gets fresh ones. + private func refreshMovieSources() async { + let scope = session.profileScopeIdentity + guard 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")]), + current(scope), let sources = value.movieEnvelope.videoSources, !sources.isEmpty else { return } + let movie = value.movieEnvelope + movieSources = sources; movieSubtitles = movie.subtitles ?? []; movieHeaders = movie.headers ?? [:] } private var canPlayNextEpisode: Bool { guard isSerial, let selectedEpisode, @@ -253,6 +338,7 @@ struct DetailView: View { } private func start(_ source: VideoSource) { guard let stream = PlaybackSourcePolicy.playableURL(source.videoUrl, type: source.type) else { return } + playingSource = source let playbackTitle = isSerial ? title + " · " + (selectedEpisode?.label ?? "Episode") : title playback = PlaybackItem(url: stream, title: playbackTitle, headers: PlaybackSourcePolicy.headers(base: candidateHeaders, source: source.headers ?? [:]), history: PlaybackHistoryContext(provider: provider, contentUrl: url, title: title, thumbnail: detail?.thumbnail ?? card.thumbnail, isSerial: isSerial, episodeIndex: selectedEpisode.flatMap { selected in episodeList.firstIndex(where: { $0.id == selected.id }) }, episodeNumber: selectedEpisode?.episode, positionMs: sourceSwitchPositionMs ?? resumePosition(for: selectedEpisode)), subtitles: candidateSubtitles) } 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/PlaybackSmokeView.swift b/apple-tv/SozoTV/PlaybackSmokeView.swift index 991ef1df..20506d0c 100644 --- a/apple-tv/SozoTV/PlaybackSmokeView.swift +++ b/apple-tv/SozoTV/PlaybackSmokeView.swift @@ -14,7 +14,7 @@ struct PlaybackSmokeView: View { @State private var route = "" var body: some View { ZStack(alignment: .bottom) { - if let item { TVPlayerView(item: item, changeSource: { _ in route = "Source picker requested"; self.item = nil }, nextEpisode: { route = "Next episode requested"; self.item = nil }).ignoresSafeArea() } + if let item { TVPlayerView(item: item, changeSource: { _ in route = "Source picker requested"; self.item = nil }, nextEpisode: { route = "Next episode requested"; self.item = nil }, retry: { _ in route = "Retry requested"; self.item = nil }).ignoresSafeArea() } if !route.isEmpty { Text(route).accessibilityIdentifier("playback.route") } Text(status).font(.system(size: 24)).padding(20).background(.black.opacity(0.7)) .accessibilityIdentifier("playback.probe").padding(.bottom, 70) diff --git a/apple-tv/SozoTV/PlaybackSourcePolicy.swift b/apple-tv/SozoTV/PlaybackSourcePolicy.swift index d8b54406..6c69fea6 100644 --- a/apple-tv/SozoTV/PlaybackSourcePolicy.swift +++ b/apple-tv/SozoTV/PlaybackSourcePolicy.swift @@ -141,3 +141,75 @@ struct PlaybackStartupState { mutating func enteredBackground() { autoPlay = false; pendingPlay = false } mutating func finish() { phase = .finished; pendingPlay = false; autoPlay = false } } + +/// Turns AVFoundation errors and access-log details into a reason the viewer can act on. +enum PlaybackFailure: Equatable { + case offline, expired, missing, blocked, unsupported, stalled, timedOut, generic + + /// The error chain wins; an error-log entry only explains an error that maps to nothing. + init(error: Error?, logStatus: Int? = nil, logComment: String? = nil) { + var next = error.map { $0 as NSError } + var depth = 0 + while let current = next, depth < 6 { + if let mapped = Self.forError(current) { self = mapped; return } + next = current.userInfo[NSUnderlyingErrorKey] as? NSError + depth += 1 + } + self = Self.httpStatus(code: logStatus, comment: logComment).flatMap(Self.forHTTP) ?? .generic + } + + var isRetryable: Bool { self != .unsupported && self != .missing && self != .blocked } + + var message: String { + switch self { + case .offline: return "Apple TV lost its internet connection. Check the network, then retry." + case .expired: return "The source refused this stream. Its link may have expired: retry to fetch a new one, or choose another source." + case .missing: return "This stream is no longer available from the source. Choose another source." + case .blocked: return "Couldn't open the video source. The server may have blocked it. Choose another source." + case .unsupported: return "This stream uses a format Apple TV cannot play. Choose another source." + case .stalled: return "The stream stopped loading. Retry, or choose another source if it keeps happening." + case .timedOut: return "The stream did not start in time. Retry or choose another source." + case .generic: return "This stream could not be played. Retry or choose another source." + } + } + + private static func httpStatus(code: Int?, comment: String?) -> Int? { + if let code, (400..<600).contains(code) { return code } + // CoreMedia reports some HTTP failures with its own codes. + switch code { + case -12660: return 403 + case -12938: return 404 + default: break + } + guard let comment, let range = comment.range(of: #"HTTP (\d{3})"#, options: .regularExpression) else { return nil } + return Int(comment[range].dropFirst(5)) + } + + private static func forHTTP(_ status: Int) -> PlaybackFailure? { + switch status { + case 401, 403: return .expired + case 404, 410: return .missing + default: return nil + } + } + + private static func forError(_ error: NSError) -> PlaybackFailure? { + switch (error.domain, error.code) { + case (NSURLErrorDomain, NSURLErrorNotConnectedToInternet), (NSURLErrorDomain, NSURLErrorNetworkConnectionLost), + (NSURLErrorDomain, NSURLErrorDataNotAllowed), (NSURLErrorDomain, NSURLErrorInternationalRoamingOff): + return .offline + case (NSURLErrorDomain, NSURLErrorTimedOut): return .timedOut + case (NSURLErrorDomain, NSURLErrorFileDoesNotExist), (NSURLErrorDomain, NSURLErrorResourceUnavailable): return .missing + case (NSURLErrorDomain, NSURLErrorUserAuthenticationRequired), (NSURLErrorDomain, NSURLErrorNoPermissionsToReadFile): return .expired + // fileFormatNotRecognized: usually a block or challenge page served instead of media. + case ("AVFoundationErrorDomain", -11828): return .blocked + // AVError fileFailedToParse, failedToParse, decodeFailed, decoderNotFound, formatUnsupported. + case ("AVFoundationErrorDomain", -11829), ("AVFoundationErrorDomain", -11853), + ("AVFoundationErrorDomain", -11821), ("AVFoundationErrorDomain", -11833), ("AVFoundationErrorDomain", -11864): + return .unsupported + case ("CoreMediaErrorDomain", let code): + return httpStatus(code: code, comment: nil).flatMap(forHTTP) + default: return nil + } + } +} 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..ddd395a0 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,14 +63,21 @@ 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" { + // 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 } } diff --git a/apple-tv/SozoTV/TVPlayerView.swift b/apple-tv/SozoTV/TVPlayerView.swift index ee776701..6bd74ee0 100644 --- a/apple-tv/SozoTV/TVPlayerView.swift +++ b/apple-tv/SozoTV/TVPlayerView.swift @@ -16,8 +16,9 @@ struct TVPlayerView: UIViewControllerRepresentable { let item: PlaybackItem var changeSource: ((Double?) -> Void)? = nil var nextEpisode: (() -> Void)? = nil + var retry: ((Double?) -> Void)? = nil - func makeCoordinator() -> Coordinator { Coordinator(session: session, history: item.history, close: { dismiss() }, changeSource: changeSource, nextEpisode: nextEpisode, item: item) } + func makeCoordinator() -> Coordinator { Coordinator(session: session, history: item.history, close: { dismiss() }, changeSource: changeSource, nextEpisode: nextEpisode, retry: retry, item: item) } func makeUIViewController(context: Context) -> AVPlayerViewController { let asset: AVURLAsset @@ -73,6 +74,7 @@ struct TVPlayerView: UIViewControllerRepresentable { private let close: () -> Void private let changeSource: ((Double?) -> Void)? private let nextEpisode: (() -> Void)? + private let retry: ((Double?) -> Void)? private let item: PlaybackItem var playlistLoader: RelayedPlaylistLoader? #if DEBUG @@ -92,6 +94,11 @@ struct TVPlayerView: UIViewControllerRepresentable { private var lifecycleObservers: [NSObjectProtocol] = [] private var startupTimeout: Task? private var failurePresented = false + private var stallTimeout: Task? + private var lastLogStatus: Int? + private var lastLogComment: String? + private var lastLogTime = 0.0 + private var timeControlObservation: NSKeyValueObservation? private var player: AVPlayer? private var observer: Any? private var statusObservation: NSKeyValueObservation? @@ -105,9 +112,9 @@ struct TVPlayerView: UIViewControllerRepresentable { private var pending: [String: Any]? private var saving = false - init(session: SessionStore, history: PlaybackHistoryContext?, close: @escaping () -> Void, changeSource: ((Double?) -> Void)?, nextEpisode: (() -> Void)?, item: PlaybackItem) { + init(session: SessionStore, history: PlaybackHistoryContext?, close: @escaping () -> Void, changeSource: ((Double?) -> Void)?, nextEpisode: (() -> Void)?, retry: ((Double?) -> Void)?, item: PlaybackItem) { self.close = close; self.changeSource = changeSource - self.nextEpisode = nextEpisode; self.item = item + self.nextEpisode = nextEpisode; self.retry = retry; self.item = item self.session = session; self.history = history scope = session.profileScopeIdentity; revision = session.revision super.init() @@ -196,7 +203,7 @@ struct TVPlayerView: UIViewControllerRepresentable { startupTimeout = Task { [weak self] in try? await Task.sleep(for: .seconds(35)) guard !Task.isCancelled, let self, !self.didResume else { return } - self.showFailure("The stream did not become ready. Return and choose another source.") + self.showFailure(.timedOut) } lifecycleObservers.append(NotificationCenter.default.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: .main) { [weak self] _ in Task { @MainActor [weak self] in @@ -233,6 +240,28 @@ struct TVPlayerView: UIViewControllerRepresentable { self.offerNextEpisode() } }) + lifecycleObservers.append(NotificationCenter.default.addObserver(forName: .AVPlayerItemFailedToPlayToEndTime, object: player.currentItem, queue: .main) { [weak self] note in + let error = note.userInfo?[AVPlayerItemFailedToPlayToEndTimeErrorKey] as? Error + Task { @MainActor [weak self] in + guard let self else { return } + self.showFailure(self.failure(for: error)) + } + }) + lifecycleObservers.append(NotificationCenter.default.addObserver(forName: .AVPlayerItemPlaybackStalled, object: player.currentItem, queue: .main) { [weak self] _ in + Task { @MainActor [weak self] in self?.watchStall() } + }) + lifecycleObservers.append(NotificationCenter.default.addObserver(forName: AVPlayerItem.newErrorLogEntryNotification, object: player.currentItem, queue: .main) { [weak self] note in + let event = (note.object as? AVPlayerItem)?.errorLog()?.events.last + let status = event?.errorStatusCode, comment = event?.errorComment + Task { @MainActor [weak self] in + self?.lastLogStatus = status; self?.lastLogComment = comment + self?.lastLogTime = ProcessInfo.processInfo.systemUptime + } + }) + timeControlObservation = player.observe(\.timeControlStatus, options: [.new]) { [weak self] _, change in + guard change.newValue == .playing else { return } + Task { @MainActor [weak self] in self?.stallTimeout?.cancel(); self?.stallTimeout = nil } + } statusObservation = player.currentItem?.observe(\.status, options: [.initial, .new]) { [weak self] _, _ in Task { @MainActor [weak self] in self?.ready() } } @@ -353,7 +382,7 @@ struct TVPlayerView: UIViewControllerRepresentable { #endif guard sameScope else { player?.pause(); close(); return } if player?.currentItem?.status == .failed { - showFailure(player?.currentItem?.error?.localizedDescription ?? "This stream cannot be played. Choose another source.") + showFailure(failure(for: player?.currentItem?.error)) return } guard !didResume, let player, player.currentItem?.status == .readyToPlay else { return } @@ -440,12 +469,41 @@ struct TVPlayerView: UIViewControllerRepresentable { userInfo: ["status": "\(player.rate > 0 ? "Playing" : "Paused") • \(Int(position))s"]) } #endif - private func showFailure(_ message: String) { + /// AVPlayer usually recovers from a stall by itself; only a long one is reported. + private func watchStall() { + stallTimeout?.cancel() + stallTimeout = Task { [weak self] in + try? await Task.sleep(for: .seconds(30)) + guard !Task.isCancelled, let self, let player = self.player, + player.timeControlStatus == .waitingToPlayAtSpecifiedRate else { return } + self.showFailure(.stalled) + } + } + /// Error-log entries AVPlayer already recovered from must not explain a later failure. + private func failure(for error: Error?) -> PlaybackFailure { + let recent = ProcessInfo.processInfo.systemUptime - lastLogTime < 10 + return PlaybackFailure(error: error, logStatus: recent ? lastLogStatus : nil, logComment: recent ? lastLogComment : nil) + } + private func showFailure(_ failure: PlaybackFailure) { guard !failurePresented, sameScope, let controller else { return } - failurePresented = true; player?.pause(); startupTimeout?.cancel() - let alert = UIAlertController(title: "Playback unavailable", message: message, preferredStyle: .alert) - alert.addAction(UIAlertAction(title: "Choose another source", style: .default) { [weak self] _ in if let self { if let changeSource = self.changeSource { changeSource(self.sourceSwitchPosition) } else { self.close() } } }) - controller.present(alert, animated: true) + let position = sourceSwitchPosition + failurePresented = true; player?.pause(); startupTimeout?.cancel(); stallTimeout?.cancel() + enqueueSnapshot() + let alert = UIAlertController(title: "Playback unavailable", message: failure.message, preferredStyle: .alert) + if failure.isRetryable, let retry { + alert.addAction(UIAlertAction(title: "Retry", style: .default) { [weak self] _ in + guard let self else { return } + if self.sameScope { retry(position) } else { self.close() } + }) + } + if let changeSource { + alert.addAction(UIAlertAction(title: "Choose another source", style: .default) { [weak self] _ in + guard let self else { return } + if self.sameScope { changeSource(position) } else { self.close() } + }) + } + alert.addAction(UIAlertAction(title: "Close", style: .cancel) { [weak self] _ in self?.close() }) + (controller.presentedViewController ?? controller).present(alert, animated: true) } func finish() { startupState.finish() @@ -457,8 +515,9 @@ struct TVPlayerView: UIViewControllerRepresentable { #endif subtitleObserver = nil; subtitleTask?.cancel(); subtitleTask = nil subtitleLabel?.removeFromSuperview(); subtitleLabel = nil; subtitleBottom = nil; cues = [] - observer = nil; statusObservation = nil; player = nil + observer = nil; statusObservation = nil; timeControlObservation = nil; player = nil startupTimeout?.cancel(); startupTimeout = nil + stallTimeout?.cancel(); stallTimeout = nil hintTask?.cancel(); hintTask = nil lifecycleObservers.forEach { NotificationCenter.default.removeObserver($0) } lifecycleObservers = []; controller = nil diff --git a/apple-tv/Tests/ContinueWatching/main.swift b/apple-tv/Tests/ContinueWatching/main.swift index 87849d50..80d6e906 100644 --- a/apple-tv/Tests/ContinueWatching/main.swift +++ b/apple-tv/Tests/ContinueWatching/main.swift @@ -5,5 +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) - 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","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", "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/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/PlaybackSources/main.swift b/apple-tv/Tests/PlaybackSources/main.swift index 030d60e4..6de698e1 100644 --- a/apple-tv/Tests/PlaybackSources/main.swift +++ b/apple-tv/Tests/PlaybackSources/main.swift @@ -81,3 +81,16 @@ assert(inactiveThenFinish.apply(inactiveThenFinish.becameReady(needsResume: fals inactiveThenFinish.finish() assert(inactiveThenFinish.becameActive() == .none) print("Playback startup: transient inactive defers once; background and teardown discard deferred Play") +let offline = NSError(domain: "AVFoundationErrorDomain", code: -11800, userInfo: [NSUnderlyingErrorKey: NSError(domain: NSURLErrorDomain, code: NSURLErrorNotConnectedToInternet)]) +assert(PlaybackFailure(error: offline) == .offline) +assert(PlaybackFailure(error: NSError(domain: "AVFoundationErrorDomain", code: -11828)) == .blocked) +assert(PlaybackFailure(error: NSError(domain: "AVFoundationErrorDomain", code: -11829)) == .unsupported) +assert(!PlaybackFailure.unsupported.isRetryable && !PlaybackFailure.blocked.isRetryable && PlaybackFailure.stalled.isRetryable && PlaybackFailure.expired.isRetryable) +assert(PlaybackFailure(error: offline, logStatus: 404) == .offline, "A mapped error outranks an older error-log entry") +assert(PlaybackFailure(error: NSError(domain: "AVFoundationErrorDomain", code: -11800), logStatus: 403) == .expired, "The error log explains a generic failure") +assert(PlaybackFailure(error: nil, logStatus: -12938) == .missing) +assert(PlaybackFailure(error: nil, logStatus: -1, logComment: "HTTP 410: Gone") == .missing) +assert(PlaybackFailure(error: NSError(domain: "CoreMediaErrorDomain", code: -12660)) == .expired) +assert(PlaybackFailure(error: NSError(domain: "AVFoundationErrorDomain", code: -11800)) == .generic) +assert(!PlaybackFailure.generic.message.contains("Error Domain")) +print("Playback failures: network, refused, missing and unsupported streams map to friendly reasons") diff --git a/apple-tv/Tests/SessionTransportChecks.swift b/apple-tv/Tests/SessionTransportChecks.swift index 732fb068..bceb1888 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,66 @@ 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 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: 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]) + + // 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") } + try await settle(["p1", "p3"]) + require(session.activeProfile == nil, "removed active profile is dropped, so the picker shows") + } + + @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") + require(!APIError.http(-1).localizedDescription.contains("-1"), "internal sentinel status is not shown") + } + @MainActor static func pinAndDraft() async throws { let session = make(MemoryCredentials()) StubProtocol.handler = { request in diff --git a/apple-tv/Tests/UI/PlaybackUITests.swift b/apple-tv/Tests/UI/PlaybackUITests.swift index 9ebaad9d..04b899f5 100644 --- a/apple-tv/Tests/UI/PlaybackUITests.swift +++ b/apple-tv/Tests/UI/PlaybackUITests.swift @@ -43,6 +43,8 @@ final class PlaybackUITests: XCTestCase { app.launch() XCTAssertTrue(app.alerts["Playback unavailable"].waitForExistence(timeout: 15), app.debugDescription) XCTAssertTrue(app.buttons["Choose another source"].exists) + XCTAssertTrue(app.buttons["Close"].exists) + XCTAssertFalse(app.buttons["Retry"].exists, "Retrying the same unreadable file cannot help") } func testRemoteSelectShowsNativeTimelineAndPlaybackControls() throws { diff --git a/apple-tv/scripts/check-profiles.sh b/apple-tv/scripts/check-profiles.sh index 270ede6d..56298647 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"