From 9487744f337544d189fb2148021aafb2315929f8 Mon Sep 17 00:00:00 2001 From: SantaSpeen Date: Sun, 22 Nov 2026 21:25:51 +0300 Subject: [PATCH] Serve image lists and DICOM study UID lookup for EzDent --- Sources/EzServerMac/LegacyDICOMMetadata.swift | 63 ++++++++++++++++++ Sources/EzServerMac/ServerStore.swift | 31 +++++++++ Sources/EzServerMac/WebConsoleAPI.swift | 64 ++++++++++++++++++- 3 files changed, 156 insertions(+), 2 deletions(-) create mode 100644 Sources/EzServerMac/LegacyDICOMMetadata.swift diff --git a/Sources/EzServerMac/LegacyDICOMMetadata.swift b/Sources/EzServerMac/LegacyDICOMMetadata.swift new file mode 100644 index 0000000..743623d --- /dev/null +++ b/Sources/EzServerMac/LegacyDICOMMetadata.swift @@ -0,0 +1,63 @@ +import Foundation + +struct LegacyDICOMMetadata { + var studyUID = "" + var modality = "" + + init(file: URL) { + guard let handle = try? FileHandle(forReadingFrom: file) else { return } + defer { try? handle.close() } + guard let data = try? handle.read(upToCount: 256 * 1024), + data.count >= 132, data[128..<132].elementsEqual([68, 73, 67, 77]) else { return } + + let bytes = [UInt8](data) + let longVRs: Set = ["OB", "OD", "OF", "OL", "OV", "OW", "SQ", "SV", "UC", "UN", "UR", "UT", "UV"] + var offset = 132 + var transferSyntax = "1.2.840.10008.1.2" + var meta = true + + func number(_ start: Int, _ width: Int, little: Bool) -> Int { + var result = 0 + for position in 0.. [LegacyImage] { + lock.lock() + defer { lock.unlock() } + return try query(""" + SELECT images.rowid, patients.rowid, patients.chart_number, images.id, + images.name, images.imported_at, images.dicom_count + FROM images JOIN patients ON patients.id = images.patient_id + WHERE ? IS NULL OR patients.chart_number = ? COLLATE BINARY + ORDER BY images.imported_at DESC, images.id + LIMIT ? OFFSET ? + """, values: [chartNumber.map { .text($0) } ?? .null, chartNumber.map { .text($0) } ?? .null, + .integer(limit), .integer(offset)]) { row in + guard let id = UUID(uuidString: self.text(row, 3)) else { throw StoreError.database } + let count = sqlite3_column_type(row, 6) == SQLITE_NULL ? nil : Int(sqlite3_column_int(row, 6)) + return LegacyImage(id: sqlite3_column_int64(row, 0), patientID: sqlite3_column_int64(row, 1), + chartNumber: self.text(row, 2), name: self.text(row, 4), + importedAt: Date(timeIntervalSinceReferenceDate: sqlite3_column_double(row, 5)), + dicomCount: count, firstFile: count == nil ? self.attachment(id) : self.slice(1, of: id)) + } + } + func imageCount(_ patient: UUID) throws -> Int { lock.lock() defer { lock.unlock() } diff --git a/Sources/EzServerMac/WebConsoleAPI.swift b/Sources/EzServerMac/WebConsoleAPI.swift index 14a8751..3c8761d 100644 --- a/Sources/EzServerMac/WebConsoleAPI.swift +++ b/Sources/EzServerMac/WebConsoleAPI.swift @@ -47,6 +47,9 @@ final class WebConsoleAPI { ("e2ds", "useraccountsfornames", "GET"), ("e2ds", "patientsbychartno", "GET"), ("e2ds", "patients", "POST"), + ("e2ds", "imagesbychartno", "POST"), + ("e2ds", "imagesbystudyuid", "GET"), + ("fs", "sysfilesnoconversionbytypeandpath", "GET"), ("e2ds", "patientsbychartnoforimage", "POST"), ("e2ds", "reportsbychartno", "GET"), ("e2ds", "trresultbychartno", "GET"), @@ -76,7 +79,7 @@ final class WebConsoleAPI { switch (path, method) { case (["auth", "apploginr2"], "POST"), (["auth", "applogin"], "POST"), (["e2ds", "patientsbynumlistforrecentlyacquired"], "POST"), (["e2ds", "patients"], "POST"), - (["e2ds", "patientsbychartnoforimage"], "POST"): + (["e2ds", "patientsbychartnoforimage"], "POST"), (["e2ds", "imagesbychartno"], "POST"): return true case (let route, "GET"): return route.starts(with: ["e2ds", "patientsbychartno"]) || isBootstrapRead(route) @@ -86,6 +89,8 @@ final class WebConsoleAPI { } private func isBootstrapRead(_ path: [String]) -> Bool { + path.starts(with: ["e2ds", "imagesbystudyuid"]) || + path.starts(with: ["fs", "sysfilesnoconversionbytypeandpath"]) || path.starts(with: ["e2ds", "useraccountsbynamer2"]) || path.starts(with: ["e2ds", "smartpayaccountsbyidandqueryuserid"]) || path.starts(with: ["e2ds", "reportsbychartno"]) || @@ -105,7 +110,8 @@ final class WebConsoleAPI { let applicationBootstrap = (method == "GET" && isBootstrapRead(path)) || (method == "GET" && path.starts(with: ["e2ds", "patientsbychartno"])) || (method == "POST" && (path == ["e2ds", "patientsbynumlistforrecentlyacquired"] - || path == ["e2ds", "patients"] || path == ["e2ds", "patientsbychartnoforimage"])) + || path == ["e2ds", "patients"] || path == ["e2ds", "patientsbychartnoforimage"] + || path == ["e2ds", "imagesbychartno"])) guard session.administrator || applicationBootstrap else { return Reply(["errorMessage": "Administrator login required"], status: "403 Forbidden", errorCode: -1013) @@ -153,6 +159,33 @@ final class WebConsoleAPI { } catch { return Reply(status: "503 Service Unavailable", errorCode: -1005) } + case ("e2ds", "imagesbychartno", "POST") where path.count == 2: + let page = input["pageNum"] as? Int ?? (input["pageNum"] as? String).flatMap(Int.init) ?? 0 + let limit = input["numItems"] as? Int ?? (input["numItems"] as? String).flatMap(Int.init) ?? 50 + guard let chart = input["strChartNo"] as? String, !chart.isEmpty, + page >= 0, (1...1000).contains(limit), page <= Int.max / limit else { + return Reply(status: "400 Bad Request", errorCode: -1021) + } + do { + return Self.imageList(try store.legacyImages(chartNumber: chart, offset: page * limit, limit: limit)) + } catch { + return Reply(status: "503 Service Unavailable", errorCode: -1005) + } + case ("e2ds", "imagesbystudyuid", "GET"): + let uid = query.first(where: { $0.name == "studyuid" })?.value + ?? (path.count == 4 && path[2] == "studyuid" ? queryPathLast : nil) + ?? "" + guard uid.range(of: #"\A[0-9]+(?:\.[0-9]+)*\z"#, options: .regularExpression) != nil, + uid.utf8.count <= 64 else { return Reply(status: "400 Bad Request", errorCode: -1021) } + do { + return Self.imageList(try store.legacyImages(), studyUID: uid) + } catch { + return Reply(status: "503 Service Unavailable", errorCode: -1005) + } + case ("fs", "sysfilesnoconversionbytypeandpath", "GET"): + // Windows-specific templates and settings are absent from the Mac file store. + return Reply(["errorMessage": "No such file or directory exists"], + status: "400 Bad Request", errorCode: -1002) case ("e2ds", "patients", "POST") where path.count == 2: guard let chartNumber = input["strChartNo"] as? String, !chartNumber.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { @@ -296,6 +329,33 @@ final class WebConsoleAPI { } } + private static func imageList(_ images: [ServerStore.LegacyImage], studyUID: String? = nil) -> Reply { + let formatter = ISO8601DateFormatter() + let items: [[String: Any]] = images.compactMap { image in + let metadata = LegacyDICOMMetadata(file: image.firstFile) + if let studyUID, metadata.studyUID != studyUID { return nil } + let modality: String + switch (metadata.modality, image.dicomCount ?? 0) { + case ("CT", _), ("CBCT", _), (_, 2...): modality = "eCT" + case ("PX", _): modality = "ePanorama" + case ("CR", _), ("DX", _): + modality = image.name.uppercased().hasPrefix("CEPH") ? "eCephalo" : "ePanorama" + default: modality = "eFile" + } + return [ + "nImageID": image.id, "nPatID": image.patientID, "nRecordID": 0, + "strChartNo": image.chartNumber, "strImgFileName": image.name, "modality": modality, + "dtAcqTime": formatter.string(from: image.importedAt), "strStudyInstanceUID": metadata.studyUID, + "strAcqMode": "", "strRawFileName": "", "strVPanoFileName": "", "dtUpdateDateTime": "", + "strModelName": "", "strDeviceInfo": "", "strNote": "", "strDeviceSerialNumber": "", + "fKvp": 0, "fMa": 0, "fDose": 0, "fExposureTime": 0, + "bIsImported": true, "bPaidImage": true, "bIsThirdPartyGroupImage": false, + "eImageType": "eNormalDeviceImage", "eSourceType": "eUnknownSourceType", + ] + } + return Reply(["vecImageInfo": items], errorCode: items.isEmpty ? -100037 : 0) + } + private static func chartNumber(query: [URLQueryItem], path: [String], last: String?) -> String { let value = query.first(where: { $0.name == "chartno" })?.value ?? (path.count == 4 && path[2] == "chartno" ? last : nil)