diff --git a/Sources/NextcloudKit/NKCommon.swift b/Sources/NextcloudKit/NKCommon.swift index 36ccbd6b..f12bb48f 100644 --- a/Sources/NextcloudKit/NKCommon.swift +++ b/Sources/NextcloudKit/NKCommon.swift @@ -97,13 +97,10 @@ public struct NKCommon: Sendable { completion: @escaping (_ filesChunk: [(fileName: String, size: Int64)], _ error: Error?) -> Void = { _, _ in }) { // Return existing chunks immediately if !filesChunk.isEmpty { + numChunks(max(0, filesChunk.count - 1)) return completion(filesChunk, nil) } - defer { - NotificationCenter.default.removeObserver(self, name: notificationCenterChunkedFileStop, object: nil) - } - let fileManager = FileManager.default var isDirectory: ObjCBool = false var reader: FileHandle? @@ -116,10 +113,6 @@ public struct NKCommon: Sendable { let bufferSize = 1_000_000 var stop = false - NotificationCenter.default.addObserver(forName: notificationCenterChunkedFileStop, object: nil, queue: nil) { _ in - stop = true - } - // If max chunk count is > 10000 (max count), add + 100 MB to the chunk size to reduce the count. This is an edge case. let inputFilePath = inputDirectory + "/" + fileName let totalSize = getFileSize(filePath: inputFilePath) @@ -147,6 +140,17 @@ public struct NKCommon: Sendable { return completion([], NSError(domain: "chunkedFile", code: -1, userInfo: [NSLocalizedDescriptionKey: "Failed to open the input file for reading."])) } + let tokenObserver = NotificationCenter.default.addObserver(forName: notificationCenterChunkedFileStop, object: nil, queue: nil) { _ in + stop = true + } + + defer { + NotificationCenter.default.removeObserver(tokenObserver) + + try? writer?.close() + try? reader?.close() + } + outerLoop: repeat { if stop { return completion([], NSError(domain: "chunkedFile", code: -5, userInfo: [NSLocalizedDescriptionKey: "Chunking was stopped by user request or system notification."])) @@ -228,9 +232,6 @@ public struct NKCommon: Sendable { } } while true - writer?.closeFile() - reader?.closeFile() - // Update incremental chunk sizes for i in 0..