Serve image lists and DICOM study UID lookup for EzDent
This commit is contained in:
1 parent
3cd0fde571
commit
9487744f33
3 files changed
+156
-2
No files matched your search
@@ -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<String> = ["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..<width {
|
||||
let index = little ? start + width - 1 - position : start + position
|
||||
result = (result << 8) | Int(bytes[index])
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
while offset + 8 <= bytes.count {
|
||||
if meta && number(offset, 2, little: true) != 2 { meta = false }
|
||||
if !meta && transferSyntax == "1.2.840.10008.1.2.1.99" { return }
|
||||
let little = meta || transferSyntax != "1.2.840.10008.1.2.2"
|
||||
let group = number(offset, 2, little: little)
|
||||
let element = number(offset + 2, 2, little: little)
|
||||
let explicit = meta || transferSyntax != "1.2.840.10008.1.2"
|
||||
var header = 8
|
||||
let length: Int
|
||||
if explicit {
|
||||
let vr = String(decoding: bytes[offset + 4..<offset + 6], as: UTF8.self)
|
||||
if longVRs.contains(vr) {
|
||||
guard offset + 12 <= bytes.count else { return }
|
||||
header = 12
|
||||
length = number(offset + 8, 4, little: little)
|
||||
} else {
|
||||
length = number(offset + 6, 2, little: little)
|
||||
}
|
||||
} else {
|
||||
length = number(offset + 4, 4, little: little)
|
||||
}
|
||||
let start = offset + header
|
||||
guard length <= bytes.count - start else { return }
|
||||
if (group == 2 && element == 16) || (group == 8 && element == 96)
|
||||
|| (group == 32 && element == 13) {
|
||||
let value = String(decoding: bytes[start..<start + length], as: UTF8.self)
|
||||
.trimmingCharacters(in: .whitespacesAndNewlines.union(CharacterSet(charactersIn: "\0")))
|
||||
if group == 2 { transferSyntax = value }
|
||||
else if group == 8 { modality = value }
|
||||
else { studyUID = value }
|
||||
}
|
||||
if !studyUID.isEmpty { return }
|
||||
offset = start + length
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -192,6 +192,37 @@ final class ServerStore {
|
||||
return record
|
||||
}
|
||||
|
||||
struct LegacyImage {
|
||||
let id: Int64
|
||||
let patientID: Int64
|
||||
let chartNumber: String
|
||||
let name: String
|
||||
let importedAt: Date
|
||||
let dicomCount: Int?
|
||||
let firstFile: URL
|
||||
}
|
||||
|
||||
func legacyImages(chartNumber: String? = nil, offset: Int = 0, limit: Int = -1) throws -> [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() }
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user