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) { id = patient.id name = patient.name chartNumber = patient.chartNumber imageCount = patient.images.count } } 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 } private let directory: URL 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 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 } 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 } guard let index = try? openFile(directory.appendingPathComponent(LibraryPaths.index)) else { return .unavailable } 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) } guard let patientID = UUID(uuidString: path[0]), let patient = patients.first(where: { $0.id == 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), 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), filename: "slice-\(number).dcm", contentType: "application/dicom")) } return .notFound } catch FileError.notFound { return .notFound } catch { return .unavailable } } private func list(_ patients: [PatientRecord], query: [URLQueryItem]) -> 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 = selected.dropFirst(start).prefix(limit).map(PatientSummary.init) 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 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 } }