downlaod crash fix maybe

This commit is contained in:
cranci1 2025-08-07 09:44:14 +02:00
parent b3933f0da4
commit 1ebb400336
5 changed files with 78 additions and 31 deletions

View file

@ -20,9 +20,13 @@ struct SoraApp: App {
UIView.appearance(whenContainedInInstancesOf: [UIAlertController.self]).tintColor = userAccentColor UIView.appearance(whenContainedInInstancesOf: [UIAlertController.self]).tintColor = userAccentColor
} }
Task { @MainActor in Task {
await Self.clearTmpFolder() await Self.clearTmpFolder()
await MainActor.run {
jsController.initializeDownloadSession()
}
TraktToken.checkAuthenticationStatus { isAuthenticated in TraktToken.checkAuthenticationStatus { isAuthenticated in
if isAuthenticated { if isAuthenticated {
Logger.shared.log("Trakt authentication is valid", type: "Debug") Logger.shared.log("Trakt authentication is valid", type: "Debug")

View file

@ -21,25 +21,40 @@ class DownloadManager: NSObject, ObservableObject {
override init() { override init() {
super.init() super.init()
initializeDownloadSession() Task {
await initializeDownloadSession()
}
loadLocalContent() loadLocalContent()
} }
private func initializeDownloadSession() { private func initializeDownloadSession() async {
#if targetEnvironment(simulator) #if targetEnvironment(simulator)
Logger.shared.log("Download Sessions are not available on Simulator", type: "Error") Logger.shared.log("Download Sessions are not available on Simulator", type: "Error")
#else #else
let configuration = URLSessionConfiguration.background(withIdentifier: "hls-downloader") await MainActor.run {
let configuration = URLSessionConfiguration.background(withIdentifier: "hls-downloader")
assetDownloadURLSession = AVAssetDownloadURLSession(
configuration: configuration, assetDownloadURLSession = AVAssetDownloadURLSession(
assetDownloadDelegate: self, configuration: configuration,
delegateQueue: .main assetDownloadDelegate: self,
) delegateQueue: .main
)
}
#endif #endif
} }
func downloadAsset(from url: URL, headers: [String: String]? = nil, subtitleURL: URL? = nil) { func downloadAsset(from url: URL, headers: [String: String]? = nil, subtitleURL: URL? = nil) {
guard assetDownloadURLSession != nil else {
Logger.shared.log("Download session not initialized yet, retrying...", type: "Warning")
Task {
await initializeDownloadSession()
await MainActor.run {
self.downloadAsset(from: url, headers: headers, subtitleURL: subtitleURL)
}
}
return
}
if let headers = headers { if let headers = headers {
activeDownloadHeaders[url] = headers activeDownloadHeaders[url] = headers
} }

View file

@ -143,7 +143,15 @@ extension JSController {
} }
guard let downloadSession = downloadURLSession else { guard let downloadSession = downloadURLSession else {
completionHandler?(false, "Download session not available") Logger.shared.log("Download session not initialized, initializing and retrying...", type: "Warning")
Task {
await MainActor.run {
self.initializeDownloadSession()
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
self.downloadMP4(request: request, completionHandler: completionHandler)
}
}
}
return return
} }

View file

@ -46,24 +46,25 @@ extension JSController {
#if targetEnvironment(simulator) #if targetEnvironment(simulator)
Logger.shared.log("Download Sessions are not available on Simulator", type: "Error") Logger.shared.log("Download Sessions are not available on Simulator", type: "Error")
#else #else
// Create a unique identifier for the background session Task {
let sessionIdentifier = "hls-downloader-\(UUID().uuidString)" let sessionIdentifier = "hls-downloader-\(UUID().uuidString)"
let configuration = URLSessionConfiguration.background(withIdentifier: sessionIdentifier) let configuration = URLSessionConfiguration.background(withIdentifier: sessionIdentifier)
// Configure session configuration.allowsCellularAccess = true
configuration.allowsCellularAccess = true configuration.shouldUseExtendedBackgroundIdleMode = true
configuration.shouldUseExtendedBackgroundIdleMode = true configuration.waitsForConnectivity = true
configuration.waitsForConnectivity = true
// Create session with configuration await MainActor.run {
downloadURLSession = AVAssetDownloadURLSession( self.downloadURLSession = AVAssetDownloadURLSession(
configuration: configuration, configuration: configuration,
assetDownloadDelegate: self, assetDownloadDelegate: self,
delegateQueue: .main delegateQueue: .main
) )
print("Download session initialized with ID: \(sessionIdentifier)") print("Download session initialized with ID: \(sessionIdentifier)")
}
}
#endif #endif
loadSavedAssets() loadSavedAssets()
@ -208,6 +209,17 @@ extension JSController {
// Set flag to prevent multiple concurrent processing // Set flag to prevent multiple concurrent processing
isProcessingQueue = true isProcessingQueue = true
// Check if download session is ready before processing queue
guard downloadURLSession != nil else {
print("Download session not ready, deferring queue processing...")
isProcessingQueue = false
// Retry after a delay to allow session initialization
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in
self?.processDownloadQueue()
}
return
}
// Calculate how many more downloads we can start // Calculate how many more downloads we can start
let activeCount = activeDownloads.count let activeCount = activeDownloads.count
let slotsAvailable = max(0, maxConcurrentDownloads - activeCount) let slotsAvailable = max(0, maxConcurrentDownloads - activeCount)
@ -288,8 +300,15 @@ extension JSController {
return return
} }
// Create the download task guard let downloadSession = downloadURLSession else {
guard let task = downloadURLSession?.makeAssetDownloadTask( print("Download session not yet initialized, retrying in background...")
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in
self?.startQueuedDownload(queuedDownload)
}
return
}
guard let task = downloadSession.makeAssetDownloadTask(
asset: asset, asset: asset,
assetTitle: queuedDownload.title ?? queuedDownload.originalURL.lastPathComponent, assetTitle: queuedDownload.title ?? queuedDownload.originalURL.lastPathComponent,
assetArtworkData: nil, assetArtworkData: nil,
@ -1627,4 +1646,4 @@ enum DownloadQueueStatus: Equatable {
case downloading case downloading
/// Download has been completed /// Download has been completed
case completed case completed
} }

View file

@ -69,13 +69,14 @@ class JSController: NSObject, ObservableObject {
context.exceptionHandler = { context, exception in context.exceptionHandler = { context, exception in
print("[JS Exception]", exception?.toString() ?? "unknown") print("[JS Exception]", exception?.toString() ?? "unknown")
} }
setupDownloadSession()
} }
private func setupDownloadSession() { private func setupDownloadSession() {
if downloadURLSession == nil { if downloadURLSession == nil {
initializeDownloadSession() Task {
setupDownloadFunction() initializeDownloadSession()
setupDownloadFunction()
}
} }
} }