Update main image when organising images

This commit is contained in:
Christoph Hagen 2023-01-15 02:10:34 +01:00
parent 7a969185e9
commit e95cae79c4

View File

@ -172,12 +172,13 @@ final class CapServer: ServerOwner {
}
private func organizeImages() {
caps.keys.forEach(organizeImage)
caps.values.forEach(organizeImage)
}
private func organizeImage(for cap: Int) {
guard let images = try? images(in: folder(of: cap)) else {
log("Failed to get image urls for cap \(cap)")
private func organizeImage(for cap: Cap) {
var cap = cap
guard let images = try? images(in: folder(of: cap.id)) else {
log("Failed to get image urls for cap \(cap.id)")
return
}
var sorted: [(id: Int, url: URL)] = images.compactMap {
@ -190,17 +191,21 @@ final class CapServer: ServerOwner {
guard version != sorted[version].id else {
continue
}
let last = sorted.popLast()!.url
let newUrl = file(of: cap, version: version)
let lastImage = sorted.popLast()!
let newUrl = file(of: cap.id, version: version)
do {
try fm.moveItem(at: last, to: newUrl)
try fm.moveItem(at: lastImage.url, to: newUrl)
} catch {
log("Failed to move file \(last.path) to \(newUrl.path): \(error)")
log("Failed to move file \(lastImage.url.path) to \(newUrl.path): \(error)")
return
}
if cap.mainImage == lastImage.id {
cap.mainImage = version
}
sorted.insert((version, newUrl), at: version)
}
caps[cap]?.count = sorted.count
cap.count = sorted.count
caps[cap.id] = cap
}
// MARK: Paths