SPB Git

Repository Public

SourceResolver.swift 4.5 KB 86 lines swift

1// SP Music iOS2// File: Core/Sources/SPMusicCore/Audio/SourceResolver.swift3// Description: Chooses where a track is read from: the device, or the stream in the allowed quality.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai78import Foundation910public struct ResolvedSource: Sendable, Equatable {11    public var url: URL12    public var isLocal: Bool13    public var variant: AudioVariant14    public var cookies: [HTTPCookie]15    public init(url: URL, isLocal: Bool, variant: AudioVariant, cookies: [HTTPCookie] = []) { self.url = url; self.isLocal = isLocal; self.variant = variant; self.cookies = cookies }16}1718public enum PlayerError: Error, Sendable, Equatable {19    case offline                 // not on the device, and no network20    case cellularNotAllowed      // not on the device, and streaming over cellular is switched off21    case signedOut               // not on the device, and no session to stream with22    case network                 // the stream broke; playback resumes when the network returns23    case unavailable             // the server no longer has the file, or it cannot be decoded24    public var message: String {25        switch self {26        case .offline: "Ce titre n'est pas téléchargé et aucune connexion n'est disponible."27        case .cellularNotAllowed: "La diffusion sur réseau cellulaire est désactivée dans les réglages."28        case .signedOut: "Connectez-vous pour écouter ce titre en diffusion."29        case .network: "Connexion interrompue. La lecture reprendra dès son retour."30        case .unavailable: "Ce titre ne peut pas être lu."31        }32    }33}3435public protocol AudioSourceResolving: Sendable {36    /// Where to read a track from, now. `forcing` asks for one variant of the stream (fallback after a decode error).37    func resolve(_ track: Track, forcing: AudioVariant?) async -> Result<ResolvedSource, PlayerError>38}3940/// The file on the device when there is one — playing it needs no network and no session. Otherwise the stream, in41/// the quality the listener chose for the current kind of network.42public struct SourceResolver: AudioSourceResolving {43    let api: APIClient44    let downloads: DownloadManager45    let settings: @Sendable () -> TransferSettings46    let network: @Sendable () -> NetworkStatus4748    public init(api: APIClient, downloads: DownloadManager, settings: @escaping @Sendable () -> TransferSettings, network: @escaping @Sendable () -> NetworkStatus) {49        self.api = api; self.downloads = downloads; self.settings = settings; self.network = network50    }5152    public func resolve(_ track: Track, forcing: AudioVariant?) async -> Result<ResolvedSource, PlayerError> {53        if forcing == nil, let local = await downloads.localFile(trackId: track.id) {54            return .success(ResolvedSource(url: local.url, isLocal: true, variant: local.variant))55        }56        guard SafeID.isValid(track.id) else { return .failure(.unavailable) }57        let quality: Quality58        switch NetworkPolicy.stream(settings(), network()) {59        case .blocked(.offline): return .failure(.offline)60        case .blocked: return .failure(.cellularNotAllowed)61        case .allowed(let q): quality = q62        }63        guard let cookie = api.sessionCookie() else { return .failure(.signedOut) }64        var variant = forcing ?? quality.variant65        if track.file == nil { variant = .compat }66        if variant == .compat, track.compatState != "ready" {67            // Ask the server for the rendition and give it a moment; a listener should not wait long for a choice68            // that only saves data, so the original is played if it is not there in time.69            variant = await waitForRendition(track.id, seconds: forcing == .compat ? 60 : 12) ? .compat : .original70            if variant == .original, forcing == .compat || track.file == nil { return .failure(.unavailable) }71        }72        return .success(ResolvedSource(url: api.streamURL(trackId: track.id, variant: variant), isLocal: false, variant: variant, cookies: [cookie]))73    }7475    private func waitForRendition(_ id: String, seconds: Int) async -> Bool {76        guard var state = try? await api.requestRendition(trackId: id) else { return false }77        let deadline = Date().addingTimeInterval(TimeInterval(seconds))78        while state != "ready", state != "error", state != "disabled", Date() < deadline {79            try? await Task.sleep(for: .seconds(1.5))80            if Task.isCancelled { return false }81            state = (try? await api.renditionState(trackId: id)) ?? state82        }83        return state == "ready"84    }85}86
Files main
Menu

Theme