Files
ezServer-MacOS/Sources/EzServerMac/LibraryAPI.swift
T

122 lines
4.9 KiB
Swift

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 }
}