Improve logging, fix image upload

This commit is contained in:
Christoph Hagen 2023-02-17 12:04:32 +01:00
parent 8a42dddb2c
commit fe0fdec03d
2 changed files with 31 additions and 6 deletions

View File

@ -35,10 +35,10 @@ extension CapServer {
}
// Upload an image
app.postCatching("images", ":cap") { request in
app.postCatching("images", .parameter("cap")) { request in
try self.ensureOperability()
try authenticator.authorize(request)
guard let cap = request.parameters.get("n", as: Int.self) else {
guard let cap = request.parameters.get("cap", as: Int.self) else {
log("/images/:cap: Invalid 'cap' parameter")
throw Abort(.badRequest)
}

View File

@ -149,6 +149,10 @@ final class CapServer {
}
private func loadCaps() throws {
guard exists(dbFile) else {
log("No cap database found")
return
}
do {
let data = try Data(contentsOf: dbFile)
caps = try JSONDecoder().decode([Cap].self, from: data)
@ -340,9 +344,18 @@ final class CapServer {
guard !unwrittenImageChanges.isEmpty else {
return
}
try ensureExistenceOfChangedImagesFile()
let handle = try FileHandle(forWritingTo: changedImagesFile)
try handle.seekToEnd()
let handle: FileHandle
do {
handle = try FileHandle(forWritingTo: changedImagesFile)
try handle.seekToEnd()
} catch {
log("Failed to open changed images file for writing: \(error)")
throw error
}
var entries = unwrittenImageChanges
defer {
unwrittenImageChanges = entries
@ -351,7 +364,12 @@ final class CapServer {
let dateString = changedImageEntryDateFormatter.string(from: Date())
while let entry = entries.popLast() {
let content = "\(dateString):\(entry.cap):\(entry.image)\n".data(using: .utf8)!
try handle.write(contentsOf: content)
do {
try handle.write(contentsOf: content)
} catch {
log("Failed to write entry to changed images file: \(error)")
throw error
}
}
}
@ -377,6 +395,10 @@ final class CapServer {
}
func removeAllEntriesInImageChangeList(before date: Date) {
guard exists(changedImagesFile) else {
log("No file for changed images to update")
return
}
do {
try String(contentsOf: changedImagesFile)
.components(separatedBy: "\n")
@ -418,6 +440,7 @@ final class CapServer {
private func add(_ cap: Cap) throws {
guard cap.mainImage == 0 else {
log("Attempting to add cap \(cap.id) with main image \(cap.mainImage)")
throw CapError.invalidData
}
var cap = cap
@ -447,10 +470,12 @@ final class CapServer {
func deleteImage(version: Int, for capId: Int) -> Bool {
guard let cap = caps[capId] else {
log("Attempting to delete image \(version) of unknown cap \(capId)")
return false
}
let capImageUrl = imageUrl(of: capId, version: version)
guard exists(capImageUrl) else {
log("Attempting to delete missing image \(version) of cap \(capId)")
return false
}
organizeImages(for: cap)
@ -476,7 +501,7 @@ final class CapServer {
do {
try classifier.write(to: classifierFile)
} catch {
log("Failed to write classifier: \(error)")
log("Failed to write classifier \(version): \(error)")
throw Abort(.internalServerError)
}
classifierVersion = version