Remove the non-original Mac HTTP API
This commit is contained in:
1 parent
9487744f33
commit
69f70d0325
6 files changed
+22
-244
No files matched your search
@@ -33,8 +33,7 @@ func runCommandLine(_ arguments: [String]) {
|
||||
print("Imported new patients: \(imported)")
|
||||
}
|
||||
|
||||
let api = LibraryAPI(store: configuration.store, secret: configuration.token)
|
||||
let server = try LocalServer(port: configuration.port, library: api)
|
||||
let server = try LocalServer(port: configuration.port, configuration: configuration)
|
||||
server.start { state in
|
||||
switch state {
|
||||
case let .success(port):
|
||||
|
||||
@@ -1,121 +0,0 @@
|
||||
import CryptoKit
|
||||
import EzDentStorage
|
||||
import Foundation
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
struct LibraryAPI {
|
||||
struct Listing: Encodable {
|
||||
let patients: [PatientSummary]
|
||||
let total: Int
|
||||
let offset: Int
|
||||
let limit: Int
|
||||
}
|
||||
|
||||
struct PatientSummary: Encodable {
|
||||
let id: UUID
|
||||
let name: String
|
||||
let chartNumber: String
|
||||
let imageCount: Int
|
||||
|
||||
init(_ patient: PatientRecord, imageCount: Int) {
|
||||
id = patient.id
|
||||
name = patient.name
|
||||
chartNumber = patient.chartNumber
|
||||
self.imageCount = imageCount
|
||||
}
|
||||
}
|
||||
|
||||
struct File {
|
||||
let handle: FileHandle
|
||||
let bytes: Int
|
||||
let contentType: String
|
||||
let filename: String
|
||||
}
|
||||
|
||||
enum Result {
|
||||
case listing(Listing)
|
||||
case patient(PatientRecord)
|
||||
case file(File)
|
||||
case invalidRequest
|
||||
case unauthorized
|
||||
case notFound
|
||||
case unavailable
|
||||
}
|
||||
|
||||
let store: ServerStore
|
||||
private let token: SHA256.Digest
|
||||
|
||||
init(store: ServerStore, secret: String) {
|
||||
self.store = store
|
||||
token = SHA256.hash(data: Data(secret.utf8))
|
||||
}
|
||||
|
||||
func isAuthorized(_ authorization: String?) -> Bool {
|
||||
guard let authorization, authorization.hasPrefix("Bearer ") else { return false }
|
||||
let candidate = SHA256.hash(data: Data(authorization.dropFirst(7).utf8))
|
||||
return zip(candidate, token).reduce(UInt8(0)) { $0 | ($1.0 ^ $1.1) } == 0
|
||||
}
|
||||
|
||||
func response(path: [String], query: [URLQueryItem], authorization: String?) -> Result {
|
||||
guard isAuthorized(authorization) else { return .unauthorized }
|
||||
do {
|
||||
if path.isEmpty { return try list(store.patients(), query: query) }
|
||||
guard let patientID = UUID(uuidString: path[0]),
|
||||
let patient = try store.patient(patientID) else { return .notFound }
|
||||
if path.count == 1 { return .patient(patient) }
|
||||
|
||||
guard path.count == 3 || path.count == 5, path[1] == "images",
|
||||
let imageID = UUID(uuidString: path[2]),
|
||||
let image = patient.images.first(where: { $0.id == imageID }) else { return .notFound }
|
||||
if path.count == 3, image.dicomCount == nil {
|
||||
return .file(try openFile(store.attachment(image.id),
|
||||
filename: image.name))
|
||||
}
|
||||
if path.count == 5, path[3] == "slices", let number = Int(path[4]),
|
||||
let count = image.dicomCount, (1...4096).contains(count), (1...count).contains(number) {
|
||||
return .file(try openFile(store.slice(number, of: image.id),
|
||||
filename: "slice-\(number).dcm", contentType: "application/dicom"))
|
||||
}
|
||||
return .notFound
|
||||
} catch FileError.notFound {
|
||||
return .notFound
|
||||
} catch {
|
||||
return .unavailable
|
||||
}
|
||||
}
|
||||
|
||||
private func list(_ patients: [PatientRecord], query: [URLQueryItem]) throws -> Result {
|
||||
let search = query.first { $0.name == "q" }?.value?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
|
||||
let offset = query.first { $0.name == "offset" }?.value ?? "0"
|
||||
let limit = query.first { $0.name == "limit" }?.value ?? "50"
|
||||
guard let offset = Int(offset), offset >= 0, let limit = Int(limit),
|
||||
(1...200).contains(limit), search.count <= 200 else { return .invalidRequest }
|
||||
let selected = patients.filter {
|
||||
search.isEmpty || $0.name.localizedStandardContains(search)
|
||||
|| $0.chartNumber.localizedStandardContains(search)
|
||||
}
|
||||
let start = min(offset, selected.count)
|
||||
let results = try selected.dropFirst(start).prefix(limit).map {
|
||||
PatientSummary($0, imageCount: try store.imageCount($0.id))
|
||||
}
|
||||
return .listing(Listing(patients: results, total: selected.count, offset: offset, limit: limit))
|
||||
}
|
||||
|
||||
private func openFile(_ url: URL, filename: String = "", contentType: String? = nil) throws -> File {
|
||||
guard url.deletingLastPathComponent().resolvingSymlinksInPath().path
|
||||
== url.deletingLastPathComponent().path else { throw FileError.notFound }
|
||||
let descriptor = open(url.path, O_RDONLY | O_NOFOLLOW | O_NONBLOCK)
|
||||
guard descriptor >= 0 else { throw FileError.notFound }
|
||||
var metadata = stat()
|
||||
guard fstat(descriptor, &metadata) == 0, metadata.st_mode & S_IFMT == S_IFREG else {
|
||||
close(descriptor)
|
||||
throw FileError.notFound
|
||||
}
|
||||
let mime = UTType(filenameExtension: (filename as NSString).pathExtension)?.preferredMIMEType
|
||||
return File(handle: FileHandle(fileDescriptor: descriptor, closeOnDealloc: true),
|
||||
bytes: Int(metadata.st_size), contentType: contentType ?? mime ?? "application/octet-stream",
|
||||
filename: filename)
|
||||
}
|
||||
|
||||
private enum FileError: Error { case notFound }
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import CryptoKit
|
||||
import Foundation
|
||||
import Network
|
||||
import OSLog
|
||||
@@ -29,7 +30,8 @@ final class LocalServer {
|
||||
private let queue = DispatchQueue(label: "ezserver.http")
|
||||
private let maxHeaderSize = 8192
|
||||
private let diagnostics = Logger(subsystem: "EzServerMac", category: "HTTP")
|
||||
private let library: LibraryAPI
|
||||
private let store: ServerStore
|
||||
private let diskSpaceToken: SHA256.Digest
|
||||
private let webConsole = WebConsoleAPI()
|
||||
private var connections: [ObjectIdentifier: NWConnection] = [:]
|
||||
private var diagnosticRoutes: [ObjectIdentifier: String] = [:]
|
||||
@@ -38,8 +40,9 @@ final class LocalServer {
|
||||
"implantds", "iosensor", "orthods", "thirdparty", "device", "pay",
|
||||
]
|
||||
|
||||
init(port: UInt16, library: LibraryAPI) throws {
|
||||
self.library = library
|
||||
init(port: UInt16, configuration: ServerConfiguration) throws {
|
||||
store = configuration.store
|
||||
diskSpaceToken = SHA256.hash(data: Data(configuration.token.utf8))
|
||||
let parameters = NWParameters.tcp
|
||||
(parameters.defaultProtocolStack.internetProtocol as? NWProtocolIP.Options)?.version = .v4
|
||||
parameters.requiredLocalEndpoint = .hostPort(host: "0.0.0.0", port: NWEndpoint.Port(rawValue: port)!)
|
||||
@@ -150,7 +153,7 @@ final class LocalServer {
|
||||
let reply: (Data) -> Void = { [self] body in
|
||||
let response = webConsole.reply(path: route, method: method, body: body,
|
||||
authorization: bearer, query: target.queryItems ?? [],
|
||||
queryPathLast: segments.last, store: library.store)
|
||||
queryPathLast: segments.last, store: store)
|
||||
guard let json = try? JSONSerialization.data(withJSONObject: response.body) else {
|
||||
connection.cancel()
|
||||
return
|
||||
@@ -172,16 +175,6 @@ final class LocalServer {
|
||||
return
|
||||
}
|
||||
}
|
||||
if segments.starts(with: ["mac", "v1", "patients"]) {
|
||||
let path = Array(segments.dropFirst(3))
|
||||
if method == "GET" {
|
||||
serveLibrary(path: path, query: target.queryItems ?? [], authorization: bearer, on: connection)
|
||||
} else {
|
||||
mutateLibrary(method: method, path: path, query: target.queryItems ?? [], authorization: bearer,
|
||||
headers: headers, initialBody: initialBody, on: connection)
|
||||
}
|
||||
return
|
||||
}
|
||||
guard method == "GET" else {
|
||||
send(["error": "Only GET is supported"], status: "405 Method Not Allowed",
|
||||
extraHeaders: "Allow: GET\r\n", on: connection)
|
||||
@@ -216,8 +209,8 @@ final class LocalServer {
|
||||
case "api/v1/auth/ping", "api/index.php/v1/auth/ping":
|
||||
send(LegacyPing(), on: connection)
|
||||
case "api/v1/fs/sysinfofordiskspace", "api/index.php/v1/fs/sysinfofordiskspace":
|
||||
guard library.isAuthorized(bearer) else { sendUnauthorized(on: connection); return }
|
||||
let values = try? library.store.directory.resourceValues(forKeys: [
|
||||
guard isAuthorizedForDiskSpace(bearer) else { sendUnauthorized(on: connection); return }
|
||||
let values = try? store.directory.resourceValues(forKeys: [
|
||||
.volumeTotalCapacityKey, .volumeAvailableCapacityKey
|
||||
])
|
||||
guard let total = values?.volumeTotalCapacity, let free = values?.volumeAvailableCapacity else {
|
||||
@@ -280,42 +273,15 @@ final class LocalServer {
|
||||
})
|
||||
}
|
||||
|
||||
private func serveLibrary(path: [String], query: [URLQueryItem], authorization: String?,
|
||||
on connection: NWConnection) {
|
||||
switch library.response(path: path, query: query, authorization: authorization) {
|
||||
case let .listing(listing):
|
||||
send(listing, on: connection)
|
||||
case let .patient(patient):
|
||||
send(patient, on: connection)
|
||||
case let .file(file):
|
||||
let safeName = file.filename.addingPercentEncoding(withAllowedCharacters: CharacterSet(
|
||||
charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
|
||||
)) ?? "image"
|
||||
let headers = responseHeaders(status: "200 OK", type: file.contentType, bytes: file.bytes,
|
||||
extra: "Content-Disposition: attachment; filename*=UTF-8''\(safeName)\r\n")
|
||||
connection.send(content: headers, completion: .contentProcessed { [weak self] error in
|
||||
guard let self, error == nil else { connection.cancel(); return }
|
||||
self.stream(file.handle, remaining: file.bytes, on: connection)
|
||||
})
|
||||
case .unauthorized:
|
||||
sendUnauthorized(on: connection)
|
||||
case .invalidRequest:
|
||||
send(["error": "Invalid limit, offset or search query"], status: "400 Bad Request", on: connection)
|
||||
case .notFound:
|
||||
send(["error": "Patient or image not found"], status: "404 Not Found", on: connection)
|
||||
case .unavailable:
|
||||
send(["error": "Could not read patient library"], status: "503 Service Unavailable", on: connection)
|
||||
}
|
||||
}
|
||||
|
||||
private struct LegacyPing: Encodable {
|
||||
let errorCode = 0
|
||||
let message = "Pong"
|
||||
}
|
||||
|
||||
private struct PatientInput: Decodable {
|
||||
let name: String
|
||||
let chartNumber: String
|
||||
private func isAuthorizedForDiskSpace(_ authorization: String?) -> Bool {
|
||||
guard let authorization, authorization.hasPrefix("Bearer ") else { return false }
|
||||
let candidate = SHA256.hash(data: Data(authorization.dropFirst(7).utf8))
|
||||
return zip(candidate, diskSpaceToken).reduce(UInt8(0)) { $0 | ($1.0 ^ $1.1) } == 0
|
||||
}
|
||||
|
||||
private func sendUnauthorized(on connection: NWConnection) {
|
||||
@@ -323,61 +289,6 @@ final class LocalServer {
|
||||
extraHeaders: "WWW-Authenticate: Bearer\r\n", on: connection)
|
||||
}
|
||||
|
||||
private func mutateLibrary(method: String, path: [String], query: [URLQueryItem], authorization: String?,
|
||||
headers: [String: [String]], initialBody: Data, on connection: NWConnection) {
|
||||
guard library.isAuthorized(authorization) else { sendUnauthorized(on: connection); return }
|
||||
if method == "POST", path.isEmpty {
|
||||
acceptBody(headers, initial: initialBody, maximum: 32 * 1024, on: connection) { url in
|
||||
guard let input = try? JSONDecoder().decode(PatientInput.self, from: Data(contentsOf: url)) else {
|
||||
throw StoreError.invalid
|
||||
}
|
||||
let patient = try self.library.store.createPatient(name: input.name, chartNumber: input.chartNumber)
|
||||
self.send(patient, status: "201 Created", on: connection)
|
||||
}
|
||||
return
|
||||
}
|
||||
guard path.count == 3, path[1] == "images", let patient = UUID(uuidString: path[0]),
|
||||
let image = UUID(uuidString: path[2]) else {
|
||||
send(["error": "Route or method unavailable"], status: "404 Not Found", on: connection)
|
||||
return
|
||||
}
|
||||
if method == "DELETE" {
|
||||
do {
|
||||
try library.store.deleteFile(patient: patient, imageID: image)
|
||||
send(["status": "deleted"], on: connection)
|
||||
} catch {
|
||||
sendMutationError(error, on: connection)
|
||||
}
|
||||
} else if method == "PUT" {
|
||||
guard let name = query.first(where: { $0.name == "name" })?.value, !name.isEmpty else {
|
||||
sendMutationError(StoreError.invalid, on: connection)
|
||||
return
|
||||
}
|
||||
let dicom = headers["content-type"]?.first?.lowercased() == "application/dicom"
|
||||
acceptBody(headers, initial: initialBody, maximum: 2 * 1024 * 1024 * 1024, on: connection) { url in
|
||||
let item = try self.library.store.addFile(from: url, patient: patient, imageID: image,
|
||||
name: name, dicom: dicom)
|
||||
self.send(item, status: "201 Created", on: connection)
|
||||
}
|
||||
} else {
|
||||
send(["error": "Method unavailable"], status: "405 Method Not Allowed",
|
||||
extraHeaders: "Allow: GET, PUT, DELETE\r\n", on: connection)
|
||||
}
|
||||
}
|
||||
|
||||
private func sendMutationError(_ error: Error, on connection: NWConnection) {
|
||||
switch error {
|
||||
case StoreError.invalid:
|
||||
send(["error": "Invalid patient or file"], status: "400 Bad Request", on: connection)
|
||||
case StoreError.notFound:
|
||||
send(["error": "Patient or file not found"], status: "404 Not Found", on: connection)
|
||||
case StoreError.conflict:
|
||||
send(["error": "Duplicate chart number or file identifier"], status: "409 Conflict", on: connection)
|
||||
default:
|
||||
send(["error": "Could not update storage"], status: "503 Service Unavailable", on: connection)
|
||||
}
|
||||
}
|
||||
|
||||
private func acceptBody(_ headers: [String: [String]], initial: Data, maximum: Int, on connection: NWConnection,
|
||||
finish: @escaping (URL) throws -> Void) {
|
||||
guard headers["transfer-encoding"] == nil, let lengths = headers["content-length"],
|
||||
@@ -390,7 +301,7 @@ final class LocalServer {
|
||||
return
|
||||
}
|
||||
do {
|
||||
let upload = try IncomingFile(in: library.store.directory)
|
||||
let upload = try IncomingFile(in: store.directory)
|
||||
let timeout = DispatchWorkItem { [weak connection] in connection?.cancel() }
|
||||
queue.asyncAfter(deadline: .now() + 300, execute: timeout)
|
||||
if headers["expect"]?.first?.lowercased() == "100-continue" {
|
||||
@@ -399,7 +310,7 @@ final class LocalServer {
|
||||
}
|
||||
receiveBody(upload, chunk: initial, remaining: length, on: connection, timeout: timeout, finish: finish)
|
||||
} catch {
|
||||
sendMutationError(error, on: connection)
|
||||
send(["error": "Could not read request body"], status: "503 Service Unavailable", on: connection)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -426,7 +337,7 @@ final class LocalServer {
|
||||
}
|
||||
} catch {
|
||||
timeout.cancel()
|
||||
sendMutationError(error, on: connection)
|
||||
send(["error": "Could not read request body"], status: "503 Service Unavailable", on: connection)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -81,8 +81,7 @@ private final class ServerControl: ObservableObject {
|
||||
return
|
||||
}
|
||||
do {
|
||||
let api = LibraryAPI(store: configuration.store, secret: configuration.token)
|
||||
let server = try LocalServer(port: portValue, library: api)
|
||||
let server = try LocalServer(port: portValue, configuration: configuration)
|
||||
self.server = server
|
||||
starting = true
|
||||
notice = nil
|
||||
|
||||
Reference in new issue
Block a user