Sesame-Server/Sources/App/routes.swift

66 lines
2.1 KiB
Swift
Raw Normal View History

2022-01-23 20:49:06 +01:00
import Vapor
2022-01-24 17:17:06 +01:00
extension PublicAPI {
var path: PathComponent {
.init(stringLiteral: rawValue)
}
var pathParameter: PathComponent {
.parameter(rawValue)
}
}
2022-04-07 23:53:25 +02:00
private func messageTransmission(_ req: Request) -> EventLoopFuture<DeviceResponse> {
2022-01-24 17:17:06 +01:00
guard let body = req.body.data else {
return req.eventLoop.makeSucceededFuture(.noBodyData)
2022-01-24 17:17:06 +01:00
}
2022-04-07 23:53:25 +02:00
guard let message = Message(decodeFrom: body) else {
return req.eventLoop.makeSucceededFuture(.invalidMessageData)
2022-01-24 17:17:06 +01:00
}
2022-04-07 23:53:25 +02:00
return deviceManager.sendMessageToDevice(message, on: req.eventLoop)
2022-01-24 17:17:06 +01:00
}
2022-01-23 20:49:06 +01:00
func routes(_ app: Application) throws {
2022-01-24 17:17:06 +01:00
/**
Get the connection status of the device.
The response is a string of either "1" (connected) or "0" (disconnected)
*/
app.get(PublicAPI.getDeviceStatus.path) { req -> String in
2022-04-07 23:53:25 +02:00
deviceManager.deviceStatus
2022-01-24 17:17:06 +01:00
}
/**
Post a key to the device for unlocking.
2022-04-07 23:53:25 +02:00
The request returns one or `Message.length+1` bytes of data, where the first byte is the raw value of a `MessageResult`,
and the optional following bytes contain the response message of the device. This request does not complete until either the device responds or the request times out. The timeout is specified by `KeyManagement.deviceTimeout`.
2022-01-24 17:17:06 +01:00
*/
2022-04-07 23:53:25 +02:00
app.post(PublicAPI.postMessage.path) { req in
messageTransmission(req).map {
Response(status: .ok, body: .init(data: $0.encoded))
}
2022-01-23 20:49:06 +01:00
}
/**
Start a new websocket connection for the client to receive table updates from the server
- Returns: Nothing
- Note: The first (and only) message from the client over the connection must be a valid session token.
*/
2022-01-24 17:17:06 +01:00
app.webSocket(PublicAPI.socket.path) { req, socket in
socket.onBinary { _, data in
2022-04-07 23:53:25 +02:00
deviceManager.processDeviceResponse(data)
2022-01-23 20:49:06 +01:00
}
2022-01-24 17:17:06 +01:00
socket.onText { _, text in
2022-04-07 23:53:25 +02:00
deviceManager.authenticateDevice(psk: text)
2022-01-23 20:49:06 +01:00
}
2022-01-24 17:17:06 +01:00
_ = socket.onClose.always { _ in
2022-04-07 23:53:25 +02:00
deviceManager.didCloseDeviceSocket()
2022-01-23 20:49:06 +01:00
}
2022-04-07 23:53:25 +02:00
deviceManager.createNewDeviceConnection(socket)
2022-01-23 20:49:06 +01:00
}
}