2020-05-17 20:01:30 +02:00
|
|
|
import Vapor
|
2020-05-19 15:19:19 +02:00
|
|
|
|
2022-05-28 21:59:32 +02:00
|
|
|
/// The decoder to extract caps from JSON payloads given to the `cap` route.
|
|
|
|
private let decoder = JSONDecoder()
|
|
|
|
|
2022-05-27 09:25:41 +02:00
|
|
|
private func authorize(_ request: Request) throws {
|
2022-06-11 00:20:43 +02:00
|
|
|
guard let key = request.headers.first(name: "key") else {
|
|
|
|
throw Abort(.badRequest)
|
|
|
|
}
|
2022-05-27 09:25:41 +02:00
|
|
|
guard server.hasAuthorization(for: key) else {
|
|
|
|
throw Abort(.forbidden)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-20 11:36:35 +02:00
|
|
|
func routes(_ app: Application) throws {
|
2022-05-28 21:59:32 +02:00
|
|
|
|
|
|
|
// Add or change a cap
|
|
|
|
app.postCatching("cap") { request in
|
2022-05-27 09:25:41 +02:00
|
|
|
try authorize(request)
|
2022-05-28 21:59:32 +02:00
|
|
|
guard let buffer = request.body.data else {
|
2020-09-20 11:36:35 +02:00
|
|
|
log("Invalid body data")
|
2020-05-19 15:19:19 +02:00
|
|
|
throw CapError.invalidBody
|
|
|
|
}
|
2022-05-28 21:59:32 +02:00
|
|
|
let cap = try decoder.decode(Cap.self, from: buffer)
|
|
|
|
try server.addOrUpdate(cap)
|
2020-05-19 15:19:19 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Upload an image
|
2022-05-28 21:59:32 +02:00
|
|
|
app.postCatching("images", ":n") { request in
|
2022-05-27 09:25:41 +02:00
|
|
|
try authorize(request)
|
2020-09-20 11:36:35 +02:00
|
|
|
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 {
|
2022-06-11 00:46:37 +02:00
|
|
|
log("Missing body data: \(request.body.description)")
|
2020-05-19 15:19:19 +02:00
|
|
|
throw CapError.invalidBody
|
|
|
|
}
|
2020-09-20 11:36:35 +02:00
|
|
|
let data = Data(buffer: buffer)
|
2022-05-28 21:59:32 +02:00
|
|
|
try server.save(image: data, for: cap)
|
2020-05-17 20:01:30 +02:00
|
|
|
}
|
2022-06-23 20:39:00 +02:00
|
|
|
|
|
|
|
// Update the classifier versions from file on disk
|
|
|
|
app.getCatching("refresh") { _ in
|
|
|
|
let url = URL(fileURLWithPath: app.directory.resourcesDirectory)
|
|
|
|
.appendingPathComponent("classifier.trained")
|
|
|
|
server.updateClassifierCaps(from: url)
|
|
|
|
}
|
2020-05-17 20:01:30 +02:00
|
|
|
}
|