From b094762297757e7f911b981469e609da25134a9e Mon Sep 17 00:00:00 2001 From: Christoph Hagen Date: Mon, 13 Mar 2023 10:41:24 +0100 Subject: [PATCH] Allow deletion of caps --- Sources/App/CapServer+Routes.swift | 13 ++++++++++++ Sources/App/CapServer.swift | 33 ++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/Sources/App/CapServer+Routes.swift b/Sources/App/CapServer+Routes.swift index 445a2a2..2f3ae66 100755 --- a/Sources/App/CapServer+Routes.swift +++ b/Sources/App/CapServer+Routes.swift @@ -120,6 +120,19 @@ extension CapServer { } return try encoder.encode(cap) } + + // Delete a cap completely, with all images + app.postCatching("delete", ":cap") { request in + guard let cap = request.parameters.get("cap", as: Int.self) else { + log("/delete/:cap/: Invalid 'cap' parameter for image deletion") + throw Abort(.badRequest) + } + try self.ensureOperability() + try authenticator.authorize(request) + guard self.delete(cap: cap) else { + throw Abort(.gone) + } + } } } diff --git a/Sources/App/CapServer.swift b/Sources/App/CapServer.swift index d98e4c3..0b3860d 100644 --- a/Sources/App/CapServer.swift +++ b/Sources/App/CapServer.swift @@ -504,6 +504,39 @@ final class CapServer { organizeImages(for: cap) return caps[capId]! } + + func delete(cap capId: Int) -> Bool { + guard caps[capId] != nil else { + log("Attempting to delete unknown cap \(capId)") + return false + } + // 1. Remove all images + do { + let imageFolderUrl = folder(of: capId) + if exists(imageFolderUrl) { + try fm.removeItem(at: imageFolderUrl) + } + } catch { + log("Failed to delete image folder of cap \(capId): \(error)") + return false + } + // 2. Remove thumbnail + do { + let url = thumbnail(of: capId) + if exists(url) { + try fm.removeItem(at: url) + } + } catch { + log("Failed to delete thumbnail of cap \(capId): \(error)") + return false + } + + // 3. Remove cap + caps[capId] = nil + saveCapCountHTML() + updateGridCapCount() + return true + } // MARK: Classifier