Build native EzServer menu app with SQLite and file storage

This commit is contained in:
SantaSpeen committed 2026-11-22 02:32:33 +03:00
1 parent cf192a5f3c
commit 9298382abe
11 files changed
+1280 -297

No files matched your search

+19 -47
View File
@@ -17,11 +17,11 @@ struct LibraryAPI {
let chartNumber: String
let imageCount: Int
init(_ patient: PatientRecord) {
init(_ patient: PatientRecord, imageCount: Int) {
id = patient.id
name = patient.name
chartNumber = patient.chartNumber
imageCount = patient.images.count
self.imageCount = imageCount
}
}
@@ -42,58 +42,38 @@ struct LibraryAPI {
case unavailable
}
private let directory: URL
let store: ServerStore
private let token: SHA256.Digest
init?(environment: [String: String]) throws {
let path = environment["EZSERVER_LIBRARY"]
let secret = environment["EZSERVER_TOKEN"]
guard path != nil || secret != nil else { return nil }
guard let path, path.hasPrefix("/"), let secret, secret.utf8.count >= 32,
secret.utf8.allSatisfy({ (33...126).contains($0) }) else {
throw ConfigurationError.incomplete
}
let directory = URL(fileURLWithPath: path, isDirectory: true).resolvingSymlinksInPath()
let index = directory.appendingPathComponent(LibraryPaths.index)
guard (try? index.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey]))
.map({ $0.isRegularFile == true && $0.isSymbolicLink != true }) == true else {
throw ConfigurationError.invalidIndex
}
self.directory = directory
init(store: ServerStore, secret: String) {
self.store = store
token = SHA256.hash(data: Data(secret.utf8))
}
func response(path: [String], query: [URLQueryItem], authorization: String?) -> Result {
guard let authorization, authorization.hasPrefix("Bearer ") else { return .unauthorized }
func isAuthorized(_ authorization: String?) -> Bool {
guard let authorization, authorization.hasPrefix("Bearer ") else { return false }
let candidate = SHA256.hash(data: Data(authorization.dropFirst(7).utf8))
let mismatch = zip(candidate, token).reduce(UInt8(0)) { $0 | ($1.0 ^ $1.1) }
guard mismatch == 0 else { return .unauthorized }
return zip(candidate, token).reduce(UInt8(0)) { $0 | ($1.0 ^ $1.1) } == 0
}
guard let index = try? openFile(directory.appendingPathComponent(LibraryPaths.index)) else {
return .unavailable
}
func response(path: [String], query: [URLQueryItem], authorization: String?) -> Result {
guard isAuthorized(authorization) else { return .unauthorized }
do {
defer { try? index.handle.close() }
guard index.bytes <= 32 * 1024 * 1024 else { return .unavailable }
let data = try index.handle.readToEnd() ?? Data()
let patients = try JSONDecoder().decode([PatientRecord].self, from: data)
if path.isEmpty { return list(patients, query: query) }
if path.isEmpty { return try list(store.patients(), query: query) }
guard let patientID = UUID(uuidString: path[0]),
let patient = patients.first(where: { $0.id == patientID }) else { return .notFound }
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(LibraryPaths.attachment(image.id, in: directory),
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(LibraryPaths.slice(number, of: image.id, in: directory),
return .file(try openFile(store.slice(number, of: image.id),
filename: "slice-\(number).dcm", contentType: "application/dicom"))
}
return .notFound
@@ -104,7 +84,7 @@ struct LibraryAPI {
}
}
private func list(_ patients: [PatientRecord], query: [URLQueryItem]) -> Result {
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"
@@ -115,7 +95,9 @@ struct LibraryAPI {
|| $0.chartNumber.localizedStandardContains(search)
}
let start = min(offset, selected.count)
let results = selected.dropFirst(start).prefix(limit).map(PatientSummary.init)
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))
}
@@ -135,15 +117,5 @@ struct LibraryAPI {
filename: filename)
}
private enum ConfigurationError: LocalizedError {
case incomplete, invalidIndex
var errorDescription: String? {
switch self {
case .incomplete: return "Set EZSERVER_LIBRARY to an absolute path and EZSERVER_TOKEN to at least 32 printable ASCII characters."
case .invalidIndex: return "EZSERVER_LIBRARY must contain an EzDent patients.json index."
}
}
}
private enum FileError: Error { case notFound }
}