From db122dacff394405fb2676769a85d1f3c7d79e85 Mon Sep 17 00:00:00 2001 From: professorDeveloper <108933534+professorDeveloper@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:57:14 +0500 Subject: [PATCH 1/5] Apple TV player: explain a failed stream and offer Retry The player only saw item.status and a startup timeout, so a long stall went unnoticed and a failure showed AVFoundation's raw message with a single button. It now also watches FailedToPlayToEndTime, stalls that last 30 seconds and the error log, maps them to a reason the viewer can act on (offline, refused or expired link, gone, unsupported format), and offers Retry, Choose another source and Close. Retry is handed back to the caller so the stream is rebuilt through the normal loading path. --- apple-tv/SozoTV/PlaybackSmokeView.swift | 2 +- apple-tv/SozoTV/PlaybackSourcePolicy.swift | 71 ++++++++++++++++++++++ apple-tv/SozoTV/TVPlayerView.swift | 65 +++++++++++++++++--- apple-tv/Tests/PlaybackSources/main.swift | 11 ++++ apple-tv/Tests/UI/PlaybackUITests.swift | 1 + 5 files changed, 139 insertions(+), 11 deletions(-) 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..130fafb5 100644 --- a/apple-tv/SozoTV/PlaybackSourcePolicy.swift +++ b/apple-tv/SozoTV/PlaybackSourcePolicy.swift @@ -141,3 +141,74 @@ 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, unsupported, stalled, timedOut, generic + + init(error: Error?, logStatus: Int? = nil, logComment: String? = nil) { + if let status = Self.httpStatus(code: logStatus, comment: logComment), let mapped = Self.forHTTP(status) { + self = mapped; return + } + 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 = .generic + } + + var isRetryable: Bool { self != .unsupported && self != .missing } + + 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, so retry or choose another source." + case .missing: return "This stream is no longer available from the source. 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 + // AVError fileFormatNotRecognized, fileFailedToParse, failedToParse, decodeFailed, decoderNotFound, formatUnsupported. + case ("AVFoundationErrorDomain", -11828), ("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/TVPlayerView.swift b/apple-tv/SozoTV/TVPlayerView.swift index 0bf64f62..f1fafbe4 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(url: item.url, options: ["AVURLAssetHTTPHeaderFieldsKey": item.headers]) @@ -64,6 +65,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 #if DEBUG private var positionProbe: UILabel? @@ -82,6 +84,9 @@ 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 player: AVPlayer? private var observer: Any? private var statusObservation: NSKeyValueObservation? @@ -95,9 +100,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() @@ -186,7 +191,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 @@ -223,6 +228,21 @@ 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(PlaybackFailure(error: error, logStatus: self.lastLogStatus, logComment: self.lastLogComment)) + } + }) + 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 } + }) statusObservation = player.currentItem?.observe(\.status, options: [.initial, .new]) { [weak self] _, _ in Task { @MainActor [weak self] in self?.ready() } } @@ -343,7 +363,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(PlaybackFailure(error: player?.currentItem?.error, logStatus: lastLogStatus, logComment: lastLogComment)) return } guard !didResume, let player, player.currentItem?.status == .readyToPlay else { return } @@ -430,12 +450,36 @@ 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) + } + } + 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() @@ -449,6 +493,7 @@ struct TVPlayerView: UIViewControllerRepresentable { subtitleLabel?.removeFromSuperview(); subtitleLabel = nil; subtitleBottom = nil; cues = [] observer = nil; statusObservation = 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/PlaybackSources/main.swift b/apple-tv/Tests/PlaybackSources/main.swift index 030d60e4..4d05e268 100644 --- a/apple-tv/Tests/PlaybackSources/main.swift +++ b/apple-tv/Tests/PlaybackSources/main.swift @@ -81,3 +81,14 @@ 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)) == .unsupported) +assert(!PlaybackFailure.unsupported.isRetryable && PlaybackFailure.stalled.isRetryable) +assert(PlaybackFailure(error: offline, logStatus: 403) == .expired, "An HTTP refusal in the error log explains a generic failure better") +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/UI/PlaybackUITests.swift b/apple-tv/Tests/UI/PlaybackUITests.swift index 9ebaad9d..783873e2 100644 --- a/apple-tv/Tests/UI/PlaybackUITests.swift +++ b/apple-tv/Tests/UI/PlaybackUITests.swift @@ -43,6 +43,7 @@ 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) } func testRemoteSelectShowsNativeTimelineAndPlaybackControls() throws { From 0bc2ab4ed3d4fd2f2700b0cc6ca24e7f36b8560c Mon Sep 17 00:00:00 2001 From: professorDeveloper <108933534+professorDeveloper@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:57:14 +0500 Subject: [PATCH 2/5] Apple TV detail: focus Play or the episodes, and let favourites be removed Focus landed on "Add to favorites" because the save row sits above the playback controls. The screen now focuses Play film, or the resumed or first episode, once loading finishes. The favourites button reads the profile's saved state, shows Remove when the title is already saved and calls DELETE /auth/favorites. The detail screen also wires the player's Retry to present the same stream again from the last position. --- apple-tv/SozoTV/DetailView.swift | 76 ++++++++++++++++++++++++++------ 1 file changed, 62 insertions(+), 14 deletions(-) diff --git a/apple-tv/SozoTV/DetailView.swift b/apple-tv/SozoTV/DetailView.swift index f69f5382..582e5af4 100644 --- a/apple-tv/SozoTV/DetailView.swift +++ b/apple-tv/SozoTV/DetailView.swift @@ -19,7 +19,12 @@ 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 retryItem: PlaybackItem? + @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 +58,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 +92,30 @@ 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 retryItem { self.retryItem = nil; playback = retryItem } + else if reopenSourcePicker { reopenSourcePicker = false; showingSources = true } else if pendingNextEpisode { pendingNextEpisode = false run { await playNextEpisode() } @@ -112,7 +127,13 @@ struct DetailView: View { } reopenSourcePicker = true; playback = nil }, - nextEpisode: canPlayNextEpisode ? { pendingNextEpisode = true; playback = nil } : nil).ignoresSafeArea() + nextEpisode: canPlayNextEpisode ? { pendingNextEpisode = true; playback = nil } : nil, + retry: { position in + var history = item.history + if let position, position.isFinite, position >= 0, position < Double(Int64.max) / 1000 { history?.positionMs = Int64(position * 1000) } + retryItem = PlaybackItem(url: item.url, title: item.title, headers: item.headers, history: history, subtitles: item.subtitles) + playback = nil + }).ignoresSafeArea() } .sheet(isPresented: $showingSources) { VStack(alignment: .leading, spacing: 24) { @@ -141,13 +162,18 @@ struct DetailView: View { }.padding(60) } } - private func episodeButton(_ episode: Episode, index: Int) -> some View { + 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 +183,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 && $0["deletedAt"].string.isEmpty } + } 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)]) 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 3/5] 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 4/5] 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 { From d5e083c5b1104d603fee78d72bcb813833ae4909 Mon Sep 17 00:00:00 2001 From: professorDeveloper <108933534+professorDeveloper@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:03:54 +0500 Subject: [PATCH 5/5] Apple TV player: retry fetches a fresh link instead of replaying the old one Retry replayed the same URL and headers, so a stream refused because its signed link expired just failed again. Retry now resolves the title again (a film refetches its sources) and plays the same source at the kept position. A mapped error now outranks the error log, and only a log entry from the last few seconds is used, so a segment AVPlayer already recovered from no longer explains a later network loss. "Cannot Open" (-11828) is reported as a blocked source, as on mobile. A stall alert no longer fires after playback recovered. --- apple-tv/SozoTV/DetailView.swift | 47 ++++++++++++++++------ apple-tv/SozoTV/PlaybackSourcePolicy.swift | 19 ++++----- apple-tv/SozoTV/TVPlayerView.swift | 22 ++++++++-- apple-tv/Tests/PlaybackSources/main.swift | 8 ++-- apple-tv/Tests/UI/PlaybackUITests.swift | 1 + 5 files changed, 69 insertions(+), 28 deletions(-) diff --git a/apple-tv/SozoTV/DetailView.swift b/apple-tv/SozoTV/DetailView.swift index 582e5af4..9652c063 100644 --- a/apple-tv/SozoTV/DetailView.swift +++ b/apple-tv/SozoTV/DetailView.swift @@ -21,7 +21,8 @@ struct DetailView: View { @State private var error: String? @State private var notice: String? @State private var favorite: Bool? - @State private var retryItem: PlaybackItem? + @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) } @@ -114,7 +115,10 @@ struct DetailView: View { .onAppear { visible = true } .onDisappear { visible = false; actionTask?.cancel() } .fullScreenCover(item: $playback, onDismiss: { - if let retryItem { self.retryItem = nil; playback = retryItem } + if let retry = pendingRetry { + pendingRetry = nil + run { await resolve(retry.episode, retrying: retry.source, positionMs: retry.positionMs) } + } else if reopenSourcePicker { reopenSourcePicker = false; showingSources = true } else if pendingNextEpisode { pendingNextEpisode = false @@ -128,12 +132,7 @@ struct DetailView: View { reopenSourcePicker = true; playback = nil }, nextEpisode: canPlayNextEpisode ? { pendingNextEpisode = true; playback = nil } : nil, - retry: { position in - var history = item.history - if let position, position.isFinite, position >= 0, position < Double(Int64.max) / 1000 { history?.positionMs = Int64(position * 1000) } - retryItem = PlaybackItem(url: item.url, title: item.title, headers: item.headers, history: history, subtitles: item.subtitles) - playback = nil - }).ignoresSafeArea() + retry: retryAction(for: item)).ignoresSafeArea() } .sheet(isPresented: $showingSources) { VStack(alignment: .leading, spacing: 24) { @@ -162,6 +161,17 @@ struct DetailView: View { }.padding(60) } } + /// 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 } @@ -212,7 +222,7 @@ struct DetailView: View { 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 && $0["deletedAt"].string.isEmpty } + favorite = value["items"].array.contains { $0["contentUrl"].string == url } } private func load() async { let scope = session.profileScopeIdentity @@ -257,13 +267,14 @@ 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) async { let scope = session.profileScopeIdentity - resolving = true; error = nil; sourceSwitchPositionMs = nil + resolving = true; error = nil; sourceSwitchPositionMs = positionMs defer { resolving = false } do { let envelope: MediaEnvelope if !isSerial && !movieSources.isEmpty { + if failed != nil { await refreshMovieSources() } envelope = MediaEnvelope(videoUrl: nil, type: nil, headers: movieHeaders, videoSources: movieSources, subtitles: movieSubtitles) } else { guard let ref = episode.mediaRef, !ref.isEmpty else { throw APIError.noPlayableSource } @@ -277,9 +288,20 @@ 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 } + 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 ?? (playable.count == 1 ? playable[0] : nil) { start(source) } else { showingSources = true } } catch { if current(scope) { 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, let index = episodeList.firstIndex(where: { $0.id == selectedEpisode.id }) else { return false } @@ -301,6 +323,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/PlaybackSourcePolicy.swift b/apple-tv/SozoTV/PlaybackSourcePolicy.swift index 130fafb5..6c69fea6 100644 --- a/apple-tv/SozoTV/PlaybackSourcePolicy.swift +++ b/apple-tv/SozoTV/PlaybackSourcePolicy.swift @@ -144,12 +144,10 @@ struct PlaybackStartupState { /// Turns AVFoundation errors and access-log details into a reason the viewer can act on. enum PlaybackFailure: Equatable { - case offline, expired, missing, unsupported, stalled, timedOut, generic + 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) { - if let status = Self.httpStatus(code: logStatus, comment: logComment), let mapped = Self.forHTTP(status) { - self = mapped; return - } var next = error.map { $0 as NSError } var depth = 0 while let current = next, depth < 6 { @@ -157,16 +155,17 @@ enum PlaybackFailure: Equatable { next = current.userInfo[NSUnderlyingErrorKey] as? NSError depth += 1 } - self = .generic + self = Self.httpStatus(code: logStatus, comment: logComment).flatMap(Self.forHTTP) ?? .generic } - var isRetryable: Bool { self != .unsupported && self != .missing } + 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, so retry or choose another source." + 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." @@ -202,8 +201,10 @@ enum PlaybackFailure: Equatable { case (NSURLErrorDomain, NSURLErrorTimedOut): return .timedOut case (NSURLErrorDomain, NSURLErrorFileDoesNotExist), (NSURLErrorDomain, NSURLErrorResourceUnavailable): return .missing case (NSURLErrorDomain, NSURLErrorUserAuthenticationRequired), (NSURLErrorDomain, NSURLErrorNoPermissionsToReadFile): return .expired - // AVError fileFormatNotRecognized, fileFailedToParse, failedToParse, decodeFailed, decoderNotFound, formatUnsupported. - case ("AVFoundationErrorDomain", -11828), ("AVFoundationErrorDomain", -11829), ("AVFoundationErrorDomain", -11853), + // 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): diff --git a/apple-tv/SozoTV/TVPlayerView.swift b/apple-tv/SozoTV/TVPlayerView.swift index f1fafbe4..580245cc 100644 --- a/apple-tv/SozoTV/TVPlayerView.swift +++ b/apple-tv/SozoTV/TVPlayerView.swift @@ -87,6 +87,8 @@ struct TVPlayerView: UIViewControllerRepresentable { 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? @@ -232,7 +234,7 @@ struct TVPlayerView: UIViewControllerRepresentable { let error = note.userInfo?[AVPlayerItemFailedToPlayToEndTimeErrorKey] as? Error Task { @MainActor [weak self] in guard let self else { return } - self.showFailure(PlaybackFailure(error: error, logStatus: self.lastLogStatus, logComment: self.lastLogComment)) + self.showFailure(self.failure(for: error)) } }) lifecycleObservers.append(NotificationCenter.default.addObserver(forName: .AVPlayerItemPlaybackStalled, object: player.currentItem, queue: .main) { [weak self] _ in @@ -241,8 +243,15 @@ struct TVPlayerView: UIViewControllerRepresentable { 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 } + 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() } } @@ -363,7 +372,7 @@ struct TVPlayerView: UIViewControllerRepresentable { #endif guard sameScope else { player?.pause(); close(); return } if player?.currentItem?.status == .failed { - showFailure(PlaybackFailure(error: player?.currentItem?.error, logStatus: lastLogStatus, logComment: lastLogComment)) + showFailure(failure(for: player?.currentItem?.error)) return } guard !didResume, let player, player.currentItem?.status == .readyToPlay else { return } @@ -460,6 +469,11 @@ struct TVPlayerView: UIViewControllerRepresentable { 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 } let position = sourceSwitchPosition @@ -491,7 +505,7 @@ 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 diff --git a/apple-tv/Tests/PlaybackSources/main.swift b/apple-tv/Tests/PlaybackSources/main.swift index 4d05e268..6de698e1 100644 --- a/apple-tv/Tests/PlaybackSources/main.swift +++ b/apple-tv/Tests/PlaybackSources/main.swift @@ -83,9 +83,11 @@ 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)) == .unsupported) -assert(!PlaybackFailure.unsupported.isRetryable && PlaybackFailure.stalled.isRetryable) -assert(PlaybackFailure(error: offline, logStatus: 403) == .expired, "An HTTP refusal in the error log explains a generic failure better") +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) diff --git a/apple-tv/Tests/UI/PlaybackUITests.swift b/apple-tv/Tests/UI/PlaybackUITests.swift index 783873e2..04b899f5 100644 --- a/apple-tv/Tests/UI/PlaybackUITests.swift +++ b/apple-tv/Tests/UI/PlaybackUITests.swift @@ -44,6 +44,7 @@ final class PlaybackUITests: XCTestCase { 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 {