Caps-Server/Sources/App/routes.swift
2023-01-14 23:09:03 +01:00

88 lines
2.8 KiB
Swift
Executable File

import Vapor
import Foundation
/// The decoder to extract caps from JSON payloads given to the `cap` route.
private let decoder = JSONDecoder()
private func authorize(_ request: Request) throws {
guard let key = request.headers.first(name: "key") else {
throw Abort(.badRequest) // 400
}
guard server.hasAuthorization(for: key) else {
throw Abort(.forbidden) // 403
}
}
func routes(_ app: Application) {
app.get("version") { _ in
"\(server.classifierVersion)"
}
// Add or change a cap
app.postCatching("cap") { request in
try authorize(request)
guard let buffer = request.body.data else {
log("Invalid body data")
throw CapError.invalidBody
}
let cap = try decoder.decode(Cap.self, from: buffer)
try server.addOrUpdate(cap)
}
// Upload an image
app.postCatching("images", ":n") { request in
try authorize(request)
guard let cap = request.parameters.get("n", as: Int.self) else {
log("Invalid parameter for cap")
throw Abort(.badRequest)
}
guard let buffer = request.body.data else {
log("Missing body data: \(request.body.description)")
throw CapError.invalidBody
}
let data = Data(buffer: buffer)
try server.save(image: data, for: cap)
}
// Update the classifier
app.on(.POST, "classifier", ":version", body: .collect(maxSize: "50mb")) { request -> HTTPStatus in
try authorize(request)
guard let version = request.parameters.get("version", as: Int.self) else {
log("Invalid parameter for version")
throw Abort(.badRequest)
}
guard version > server.classifierVersion else {
throw Abort(.alreadyReported) // 208
}
guard let buffer = request.body.data else {
log("Missing body data: \(request.body.description)")
throw CapError.invalidBody
}
let data = Data(buffer: buffer)
try server.save(classifier: data, version: version)
return .ok
}
// Update the trained classes
app.postCatching("classes") { request in
try authorize(request)
guard let buffer = request.body.data else {
log("Missing body data: \(request.body.description)")
throw CapError.invalidBody
}
let data = Data(buffer: buffer)
guard let content = String(data: data, encoding: .utf8) else {
log("Invalid string body: \(request.body.description)")
throw CapError.invalidBody
}
server.updateTrainedClasses(content: content)
}
// Reset the changed images list
app.postCatching("changes") { request in
try authorize(request)
server.emptyChangedImageListFile()
}
}