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