fix: issue with concurrent downloads

This commit is contained in:
Fredrik Burmester
2025-02-17 14:19:02 +01:00
parent 3f63dcf168
commit 9ca0f04278
3 changed files with 55 additions and 61 deletions

View File

@@ -46,24 +46,12 @@ export default function IndexLayout() {
title: t("home.downloads.downloads_title"),
}}
/>
<Stack.Screen
name="downloads/[seriesId]"
options={{
title: t("home.downloads.tvseries"),
}}
/>
<Stack.Screen
name="settings"
options={{
title: t("home.settings.settings_title"),
}}
/>
<Stack.Screen
name="settings/optimized-server/page"
options={{
title: "",
}}
/>
<Stack.Screen
name="settings/marlin-search/page"
options={{

View File

@@ -299,41 +299,47 @@ class HLSDownloadDelegate: NSObject, AVAssetDownloadDelegate {
let metadata = module?.activeDownloads[assetDownloadTask.taskIdentifier]?.metadata ?? [:]
let startTime = module?.activeDownloads[assetDownloadTask.taskIdentifier]?.startTime ?? 0
let folderName = providedId
guard let module = module else { return }
// Calculate download size
// let fileManager = FileManager.default
// let enumerator = fileManager.enumerator(
// at: newLocation,
// includingPropertiesForKeys: [.totalFileAllocatedSizeKey],
// options: [.skipsHiddenFiles],
// errorHandler: nil)!
// var totalSize: Int64 = 0
// while let filePath = enumerator.nextObject() as? URL {
// do {
// let resourceValues = try filePath.resourceValues(forKeys: [.totalFileAllocatedSizeKey])
// if let size = resourceValues.totalFileAllocatedSize {
// totalSize += Int64(size)
// }
// } catch {
// print("Error calculating size: \(error)")
// }
// }
do {
guard let module = module else { return }
let newLocation = try module.persistDownloadedFolder(
originalLocation: location, folderName: folderName)
// Calculate download size
// let fileManager = FileManager.default
// let enumerator = fileManager.enumerator(
// at: newLocation,
// includingPropertiesForKeys: [.totalFileAllocatedSizeKey],
// options: [.skipsHiddenFiles],
// errorHandler: nil)!
// var totalSize: Int64 = 0
// while let filePath = enumerator.nextObject() as? URL {
// do {
// let resourceValues = try filePath.resourceValues(forKeys: [.totalFileAllocatedSizeKey])
// if let size = resourceValues.totalFileAllocatedSize {
// totalSize += Int64(size)
// }
// } catch {
// print("Error calculating size: \(error)")
// }
// }
// Handle metadata first
if !metadata.isEmpty {
let metadataLocation = newLocation.deletingLastPathComponent().appendingPathComponent(
"\(providedId).json")
let jsonData = try JSONSerialization.data(withJSONObject: metadata, options: .prettyPrinted)
let jsonData = try JSONSerialization.data(
withJSONObject: metadata, options: .prettyPrinted)
try jsonData.write(to: metadataLocation)
}
// Create a new Task for async operation
Task {
do {
try await rewriteM3U8Files(baseDir: newLocation.path)
module.sendEvent(
"onComplete",
[
@@ -356,7 +362,7 @@ class HLSDownloadDelegate: NSObject, AVAssetDownloadDelegate {
}
}
} catch {
module?.sendEvent(
module.sendEvent(
"onError",
[
"id": providedId,
@@ -366,7 +372,8 @@ class HLSDownloadDelegate: NSObject, AVAssetDownloadDelegate {
"startTime": startTime,
])
}
module?.removeDownload(with: assetDownloadTask.taskIdentifier)
module.removeDownload(with: assetDownloadTask.taskIdentifier)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {

View File

@@ -145,37 +145,35 @@ export const NativeDownloadProvider: React.FC<{
});
useEffect(() => {
const initializeDownloads = async () => {
const hlsDownloads = await checkForExistingDownloads();
const hlsDownloadStates = hlsDownloads.reduce(
(acc, download) => ({
...acc,
[download.id]: {
id: download.id,
progress: download.progress,
state: download.state,
secondsDownloaded: download.secondsDownloaded,
secondsTotal: download.secondsTotal,
metadata: download.metadata,
startTime: download?.startTime,
},
}),
{}
);
// const initializeDownloads = async () => {
// const hlsDownloads = await checkForExistingDownloads();
// const hlsDownloadStates = hlsDownloads.reduce(
// (acc, download) => ({
// ...acc,
// [download.id]: {
// id: download.id,
// progress: download.progress,
// state: download.state,
// secondsDownloaded: download.secondsDownloaded,
// secondsTotal: download.secondsTotal,
// metadata: download.metadata,
// startTime: download?.startTime,
// },
// }),
// {}
// );
setDownloads({ ...hlsDownloadStates });
};
// setDownloads({ ...hlsDownloadStates });
// };
initializeDownloads();
// initializeDownloads();
const progressListener = addProgressListener((download) => {
console.log("Attempting to add progress listener");
if (!download.metadata) throw new Error("No metadata found in download");
console.log(
"[HLS] Download progress:",
download.secondsTotal,
download.secondsDownloaded,
download.metadata.item.Id,
download.progress,
download.state
);
@@ -198,6 +196,7 @@ export const NativeDownloadProvider: React.FC<{
try {
// await rewriteM3U8Files(payload.location);
// await markFileAsDone(payload.id);
console.log("completeListener", payload.id);
setDownloads((prev) => {
const newDownloads = { ...prev };
@@ -205,9 +204,9 @@ export const NativeDownloadProvider: React.FC<{
return newDownloads;
});
await queryClient.invalidateQueries({ queryKey: ["downloadedFiles"] });
if (payload.state === "DONE") toast.success("Download complete ✅");
refetchDownloadedFiles();
} catch (error) {
console.error("Failed to download file:", error);
toast.error("Failed to download ❌");