Ensure proper naming of images on system start

This commit is contained in:
Christoph Hagen 2023-01-15 01:47:32 +01:00
parent bb3ed0e8c3
commit a474b509c1

View File

@ -82,9 +82,9 @@ final class CapServer: ServerOwner {
func loadData() throws { func loadData() throws {
loadClassifierVersion(at: classifierVersionFile) loadClassifierVersion(at: classifierVersionFile)
try loadCaps() try loadCaps()
try updateCounts()
saveCapCountHTML() saveCapCountHTML()
try ensureExistenceOfChangedImagesFile() try ensureExistenceOfChangedImagesFile()
organizeImages()
} }
private func loadClassifierVersion(at url: URL) { private func loadClassifierVersion(at url: URL) {
@ -171,6 +171,38 @@ final class CapServer: ServerOwner {
try? content.data(using: .utf8)!.write(to: htmlFile) try? content.data(using: .utf8)!.write(to: htmlFile)
} }
private func organizeImages() {
caps.keys.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)")
return
}
var sorted: [(id: Int, url: URL)] = images.compactMap {
guard let id = Int($0.deletingPathExtension().lastPathComponent) else {
return nil
}
return (id, $0)
}.sorted { $0.id < $1.id }
for version in 0..<images.count {
guard version != sorted[version].id else {
continue
}
let last = sorted.popLast()!.url
let newUrl = file(of: cap, version: version)
do {
try fm.moveItem(at: last, to: newUrl)
} catch {
log("Failed to move file \(last.path) to \(newUrl.path): \(error)")
return
}
sorted.insert((version, newUrl), at: version)
}
caps[cap]?.count = sorted.count
}
// MARK: Paths // MARK: Paths
func folder(of cap: Int) -> URL { func folder(of cap: Int) -> URL {
@ -207,9 +239,9 @@ final class CapServer: ServerOwner {
} }
} }
func countImages(in folder: URL) throws -> Int { private func images(in folder: URL) throws -> [URL] {
try fm.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil) try fm.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil)
.filter({ $0.pathExtension == "jpg" }).count .filter { $0.pathExtension == "jpg" }
} }
/** /**
@ -220,7 +252,7 @@ final class CapServer: ServerOwner {
guard fm.fileExists(atPath: f.path) else { guard fm.fileExists(atPath: f.path) else {
return 0 return 0
} }
return try countImages(in: f) return try images(in: f).count
} }
// MARK: Images // MARK: Images