Skip to content

Commit

Permalink
Merge pull request #1159 from TortugaPower/crash-import-existing
Browse files Browse the repository at this point in the history
Fix crash when importing missing backing files for existing books
  • Loading branch information
GianniCarlo authored Aug 1, 2024
2 parents 545a6dc + 19b5c1b commit 2e077f9
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 8 deletions.
24 changes: 18 additions & 6 deletions BookPlayer/Import/Models/ImportOperation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -165,9 +165,16 @@ public class ImportOperation: Operation {
}

private func hasExistingBook(_ fileURL: URL) -> Bool {
guard let existingBook = self.libraryService.findBooks(containing: fileURL)?.first,
let existingFileURL = existingBook.fileURL,
!FileManager.default.fileExists(atPath: existingFileURL.path) else { return false }
guard
let existingBook = self.libraryService.findBooks(containing: fileURL)?.first,
let existingFileURL = existingBook.fileURL,
!FileManager.default.fileExists(atPath: existingFileURL.path)
else { return false }

// Add support for iCloud documents
let accessGranted = fileURL.startAccessingSecurityScopedResource()

defer { fileURL.stopAccessingSecurityScopedResource() }

do {
// create parent folder if it doesn't exist
Expand All @@ -177,10 +184,15 @@ public class ImportOperation: Operation {
try FileManager.default.createDirectory(at: parentFolder, withIntermediateDirectories: true, attributes: nil)
}

try FileManager.default.moveItem(at: fileURL, to: existingFileURL)
try (existingFileURL as NSURL).setResourceValue(URLFileProtection.none, forKey: .fileProtectionKey)
if accessGranted {
try FileManager.default.copyItem(at: fileURL, to: existingFileURL)
} else {
try FileManager.default.moveItem(at: fileURL, to: existingFileURL)
}

existingFileURL.disableFileProtection()
} catch {
fatalError("Fail to move file from \(fileURL) to \(existingFileURL)")
fatalError("Existing book, fail to move file from \(fileURL) to \(existingFileURL). Error: \(error.localizedDescription)")
}

return true
Expand Down
8 changes: 6 additions & 2 deletions BookPlayer/Settings/Storage/StorageViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,9 @@ final class StorageViewModel: StorageViewModelProtocol {

@Published var publishedFiles = [StorageItem]() {
didSet {
self.showFixAllButton = self.publishedFiles.contains { $0.showWarning }
DispatchQueue.main.async {
self.showFixAllButton = self.publishedFiles.contains { $0.showWarning }
}
}
}
@Published var showFixAllButton = false
Expand Down Expand Up @@ -402,7 +404,9 @@ final class StorageViewModel: StorageViewModelProtocol {
))
}
} else {
completionHandler()
await MainActor.run {
completionHandler()
}
}
}
}
Expand Down

0 comments on commit 2e077f9

Please sign in to comment.