diff --git a/Sources/EzServerMac/LegacyMultipart.swift b/Sources/EzServerMac/LegacyMultipart.swift new file mode 100644 index 0000000..c83bc67 --- /dev/null +++ b/Sources/EzServerMac/LegacyMultipart.swift @@ -0,0 +1,86 @@ +import Foundation + +struct LegacyMultipart { + let fields: [String: String] + let filename: String? + let file: Data + + static func boundary(in contentType: String) -> String? { + let parts = contentType.split(separator: ";").map { $0.trimmingCharacters(in: .whitespaces) } + guard parts.first?.lowercased() == "multipart/form-data", + let parameter = parts.dropFirst().first(where: { $0.lowercased().hasPrefix("boundary=") }) else { + return nil + } + let value = String(parameter.dropFirst(9)).trimmingCharacters(in: CharacterSet(charactersIn: "\"")) + guard (1...70).contains(value.utf8.count), + value.utf8.allSatisfy({ (33...126).contains($0) && $0 != 34 }) else { return nil } + return value + } + + init(url: URL, boundary: String) throws { + let data = try Data(contentsOf: url, options: .alwaysMapped) + let opening = Data("--\(boundary)\r\n".utf8) + let marker = Data("\r\n--\(boundary)".utf8) + let separator = Data("\r\n\r\n".utf8) + let newline = Data("\r\n".utf8) + let closing = Data("--".utf8) + guard data.starts(with: opening) else { throw StoreError.invalid } + var position = opening.count + var fields: [String: String] = [:] + var file: Data? + var filename: String? + var finished = false + + for _ in 0..<128 { + let headerLimit = min(data.count, position + 8192) + guard let headers = data.range(of: separator, in: position..? + var last = false + while let candidate = data.range(of: marker, in: scan.. String? { + guard let span = header.range(of: "(?:^|;)\\s*" + name + "=\"[^\"]*\"", + options: [.regularExpression, .caseInsensitive]), + let quote = header[span].firstIndex(of: "\"") else { return nil } + return String(header[header.index(after: quote)..= 2 { + let operation = route[1] + if method == "GET", ["filesbytypeandpath", "ctfilesbypath"].contains(operation) { + guard webConsole.isSignedIn(bearer) else { sendUnauthorized(on: connection); return } + var arguments: [String: String] = [:] + let tail = Array(segments.dropFirst(apiPrefix + 2)) + for index in stride(from: 0, to: max(0, tail.count - 1), by: 2) { + arguments[tail[index].lowercased()] = tail[index + 1] + } + for item in target.queryItems ?? [] { arguments[item.name.lowercased()] = item.value } + downloadLegacyFile(ct: operation == "ctfilesbypath", arguments: arguments, on: connection) + return + } + if method == "POST", route.count == 2, ["filesbychartno", "ctfilesbychartno"].contains(operation) { + guard webConsole.isSignedIn(bearer) else { sendUnauthorized(on: connection); return } + guard let type = headers["content-type"]?.first, let boundary = LegacyMultipart.boundary(in: type) else { + send(["errorCode": -1021], status: "400 Bad Request", on: connection) + return + } + acceptBody(headers, initial: initialBody, maximum: 2 * 1024 * 1024 * 1024, on: connection) { url in + self.uploadLegacyFile(url, boundary: boundary, ct: operation == "ctfilesbychartno", on: connection) + } + return + } + } if webConsole.handles(route, method: method) { guard localConsole || webConsole.allowsNetworkAccess(route, method: method) else { send(["error": "Web Console is local only"], status: "403 Forbidden", on: connection) @@ -289,6 +314,126 @@ final class LocalServer { extraHeaders: "WWW-Authenticate: Bearer\r\n", on: connection) } + private func uploadLegacyFile(_ url: URL, boundary: String, ct: Bool, on connection: NWConnection) { + do { + let form = try LegacyMultipart(url: url, boundary: boundary) + let fields = form.fields + guard let chart = fields["chartNo"], !chart.isEmpty, + ct || fields["fileType"]?.uppercased() == "IMG", + let suppliedName = fields["attachedFileName"] ?? form.filename else { throw StoreError.invalid } + guard let patient = try store.patient(chartNumber: chart) else { throw StoreError.notFound } + let rawExtension = ct ? "CT" : (suppliedName as NSString).pathExtension + let ext = rawExtension.isEmpty ? (fields["fileExt"] ?? "dcm").trimmingCharacters(in: CharacterSet(charactersIn: ".")) : rawExtension + guard ext.range(of: #"\A[A-Za-z0-9]{1,12}\z"#, options: .regularExpression) != nil else { throw StoreError.invalid } + if ct && !form.file.starts(with: [0x50, 0x4b, 0x03, 0x04]) { throw StoreError.invalid } + let file = try IncomingFile(in: store.directory) + try file.handle.write(contentsOf: form.file) + try file.handle.close() + if ct { + let zip = Process() + zip.executableURL = URL(fileURLWithPath: "/usr/bin/unzip") + zip.arguments = ["-Z", "-1", file.url.path] + zip.standardOutput = FileHandle.nullDevice + zip.standardError = FileHandle.nullDevice + try zip.run() + zip.waitUntilExit() + guard zip.terminationStatus == 0 else { throw StoreError.invalid } + } + let id = UUID() + let wireName = id.uuidString + "." + ext + let modality = ct ? "eCT" : (fields["modality"] ?? "") + let uid = fields["studyInstanceUID"] ?? "" + guard modality.utf8.count <= 64, uid.utf8.count <= 64, + !modality.contains("\0"), !uid.contains("\0") else { throw StoreError.invalid } + _ = try store.addFile(from: file.url, patient: patient.record.id, imageID: id, name: wireName, + dicom: !ct && ext.lowercased() == "dcm", studyUID: uid, modality: modality) + sendLegacyReply(["updatedFileType": ct ? "CT" : "IMG", "updatedFileName": wireName], + code: 0, status: "200 OK", on: connection) + } catch StoreError.invalid { + send(["errorCode": -1021], status: "400 Bad Request", on: connection) + } catch StoreError.notFound { + send(["errorCode": -100037], status: "404 Not Found", on: connection) + } catch { + send(["errorCode": -1005], status: "503 Service Unavailable", on: connection) + } + } + + private func sendLegacyReply(_ values: [String: String], code: Int, status: String, on connection: NWConnection) { + var response: [String: Any] = values + response["errorCode"] = code + guard let bytes = try? JSONSerialization.data(withJSONObject: response) else { connection.cancel(); return } + sendBody(bytes, status: status, on: connection) + } + + private func downloadLegacyFile(ct: Bool, arguments: [String: String], on connection: NWConnection) { + guard ct || arguments["type"]?.uppercased() == "IMG", + let raw = arguments["path"]?.removingPercentEncoding else { + send(["errorCode": -1021], status: "400 Bad Request", on: connection) + return + } + let basename = (raw.replacingOccurrences(of: "\\", with: "/") as NSString).lastPathComponent + let identifier = UUID(uuidString: (basename as NSString).deletingPathExtension) + do { + let matches = try store.legacyImages(imageID: identifier).filter { + (identifier == nil ? $0.name == basename : $0.wireName.caseInsensitiveCompare(basename) == .orderedSame) + && (ct == $0.wireName.uppercased().hasSuffix(".CT")) + } + guard matches.count == 1, let image = matches.first else { + send(["errorCode": -1002], status: "404 Not Found", on: connection) + return + } + if ct && (image.dicomCount ?? 0) > 1 { + DispatchQueue.global(qos: .utility).async { [self] in + do { + let directory = store.directory.appendingPathComponent(".ct-download-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + defer { try? FileManager.default.removeItem(at: directory) } + let archive = directory.appendingPathComponent(image.wireName) + let zip = Process() + zip.executableURL = URL(fileURLWithPath: "/usr/bin/zip") + zip.currentDirectoryURL = image.firstFile.deletingLastPathComponent() + zip.arguments = ["-q", "-0", "-r", archive.path, "."] + zip.standardError = FileHandle.nullDevice + try zip.run() + zip.waitUntilExit() + guard zip.terminationStatus == 0 else { throw StoreError.database } + let file = try Self.openTransfer(archive) + queue.async { self.sendLegacyFile(file, name: image.wireName, ct: true, on: connection) } + } catch { + queue.async { self.send(["errorCode": -1005], status: "503 Service Unavailable", on: connection) } + } + } + } else { + let file = try Self.openTransfer(image.firstFile) + sendLegacyFile(file, name: image.wireName, ct: ct, on: connection) + } + } catch { + send(["errorCode": -1002], status: "404 Not Found", on: connection) + } + } + + private static func openTransfer(_ url: URL) throws -> (handle: FileHandle, bytes: Int) { + let fd = open(url.path, O_RDONLY | O_NOFOLLOW | O_NONBLOCK) + guard fd >= 0 else { throw StoreError.notFound } + let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true) + var info = stat() + guard fstat(fd, &info) == 0, info.st_mode & S_IFMT == S_IFREG else { throw StoreError.notFound } + return (handle, Int(info.st_size)) + } + + private func sendLegacyFile(_ file: (handle: FileHandle, bytes: Int), name: String, ct: Bool, + on connection: NWConnection) { + let ext = (name as NSString).pathExtension + let type = ct ? "application/zip" : (UTType(filenameExtension: ext)?.preferredMIMEType ?? "application/octet-stream") + let safeName = name.addingPercentEncoding(withAllowedCharacters: .alphanumerics.union(CharacterSet(charactersIn: "-._"))) ?? "file" + let headers = responseHeaders(status: "200 OK", type: type, bytes: file.bytes, + extra: "Content-Disposition: attachment; filename=\(safeName)\r\n") + connection.send(content: headers, completion: .contentProcessed { [weak self] error in + guard let self, error == nil else { connection.cancel(); return } + self.stream(file.handle, remaining: file.bytes, on: connection) + }) + } + private func acceptBody(_ headers: [String: [String]], initial: Data, maximum: Int, on connection: NWConnection, finish: @escaping (URL) throws -> Void) { guard headers["transfer-encoding"] == nil, let lengths = headers["content-length"], diff --git a/Sources/EzServerMac/ServerStore.swift b/Sources/EzServerMac/ServerStore.swift index c93a4df..dd04375 100644 --- a/Sources/EzServerMac/ServerStore.swift +++ b/Sources/EzServerMac/ServerStore.swift @@ -60,6 +60,11 @@ final class ServerStore { patient_id TEXT PRIMARY KEY NOT NULL REFERENCES patients(id) ON DELETE CASCADE, fields TEXT NOT NULL ); + CREATE TABLE IF NOT EXISTS legacy_image_metadata ( + image_id TEXT PRIMARY KEY NOT NULL REFERENCES images(id) ON DELETE CASCADE, + study_uid TEXT NOT NULL, + modality TEXT NOT NULL + ); CREATE TABLE IF NOT EXISTS password_policy ( key TEXT PRIMARY KEY NOT NULL, value TEXT NOT NULL @@ -200,26 +205,39 @@ final class ServerStore { let importedAt: Date let dicomCount: Int? let firstFile: URL + let uuid: UUID + let studyUID: String + let modality: String + + var wireName: String { + let suffix = (name as NSString).pathExtension + let ext = (dicomCount ?? 0) > 1 ? "CT" : suffix + return uuid.uuidString + (ext.isEmpty ? "" : "." + ext) + } } - func legacyImages(chartNumber: String? = nil, offset: Int = 0, limit: Int = -1) throws -> [LegacyImage] { + func legacyImages(chartNumber: String? = nil, imageID: UUID? = 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 + images.name, images.imported_at, images.dicom_count, + legacy_image_metadata.study_uid, legacy_image_metadata.modality FROM images JOIN patients ON patients.id = images.patient_id - WHERE ? IS NULL OR patients.chart_number = ? COLLATE BINARY + LEFT JOIN legacy_image_metadata ON legacy_image_metadata.image_id = images.id + WHERE (? IS NULL OR patients.chart_number = ? COLLATE BINARY) AND (? IS NULL OR images.id = ?) 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 + imageID.map { .text($0.uuidString) } ?? .null, + imageID.map { .text($0.uuidString) } ?? .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)) + dicomCount: count, firstFile: count == nil ? self.attachment(id) : self.slice(1, of: id), + uuid: id, studyUID: self.text(row, 7), modality: self.text(row, 8)) } } @@ -252,7 +270,7 @@ final class ServerStore { return patient } - func addFile(from source: URL, patient id: UUID, imageID: UUID, name: String, dicom: Bool) throws -> PatientImage { + func addFile(from source: URL, patient id: UUID, imageID: UUID, name: String, dicom: Bool, studyUID: String = "", modality: String = "") throws -> PatientImage { guard (1...255).contains(name.count), name.rangeOfCharacter(from: .controlCharacters) == nil, !name.contains("/"), !name.contains("\\") else { throw StoreError.invalid } lock.lock() @@ -261,8 +279,19 @@ final class ServerStore { let image = PatientImage(id: imageID, name: name, importedAt: Date(), dicomCount: dicom ? 1 : nil) let destination = attachment(imageID) guard !FileManager.default.fileExists(atPath: destination.path) else { throw StoreError.conflict } - try transaction { - try persist(image, patient: id, from: source, isSeries: false) + var stored = false + do { + try transaction { + try persist(image, patient: id, from: source, isSeries: false) + stored = true + if !studyUID.isEmpty || !modality.isEmpty { + try run("INSERT INTO legacy_image_metadata(image_id, study_uid, modality) VALUES (?, ?, ?)", + [.text(imageID.uuidString), .text(studyUID), .text(modality)]) + } + } + } catch { + if stored { try? FileManager.default.removeItem(at: destination) } + throw error } return image } diff --git a/Sources/EzServerMac/WebConsoleAPI.swift b/Sources/EzServerMac/WebConsoleAPI.swift index 3c8761d..c4a0cae 100644 --- a/Sources/EzServerMac/WebConsoleAPI.swift +++ b/Sources/EzServerMac/WebConsoleAPI.swift @@ -48,6 +48,7 @@ final class WebConsoleAPI { ("e2ds", "patientsbychartno", "GET"), ("e2ds", "patients", "POST"), ("e2ds", "imagesbychartno", "POST"), + ("e2ds", "patientsforcondition", "POST"), ("e2ds", "imagesbystudyuid", "GET"), ("fs", "sysfilesnoconversionbytypeandpath", "GET"), ("e2ds", "patientsbychartnoforimage", "POST"), @@ -79,7 +80,8 @@ final class WebConsoleAPI { switch (path, method) { case (["auth", "apploginr2"], "POST"), (["auth", "applogin"], "POST"), (["e2ds", "patientsbynumlistforrecentlyacquired"], "POST"), (["e2ds", "patients"], "POST"), - (["e2ds", "patientsbychartnoforimage"], "POST"), (["e2ds", "imagesbychartno"], "POST"): + (["e2ds", "patientsbychartnoforimage"], "POST"), (["e2ds", "imagesbychartno"], "POST"), + (["e2ds", "patientsforcondition"], "POST"): return true case (let route, "GET"): return route.starts(with: ["e2ds", "patientsbychartno"]) || isBootstrapRead(route) @@ -98,6 +100,12 @@ final class WebConsoleAPI { path == ["e2ds", "doctors"] } + func isSignedIn(_ authorization: String?) -> Bool { + guard let authorization, authorization.hasPrefix("Bearer "), + let session = sessions[String(authorization.dropFirst(7))] else { return false } + return session.expiry > Date() + } + func reply(path: [String], method: String, body: Data, authorization: String?, query: [URLQueryItem], queryPathLast: String?, store: ServerStore) -> Reply { if path == ["auth", "apploginr2"] || path == ["auth", "applogin"] { return login(body) @@ -111,7 +119,7 @@ final class WebConsoleAPI { || (method == "GET" && path.starts(with: ["e2ds", "patientsbychartno"])) || (method == "POST" && (path == ["e2ds", "patientsbynumlistforrecentlyacquired"] || path == ["e2ds", "patients"] || path == ["e2ds", "patientsbychartnoforimage"] - || path == ["e2ds", "imagesbychartno"])) + || path == ["e2ds", "imagesbychartno"] || path == ["e2ds", "patientsforcondition"])) guard session.administrator || applicationBootstrap else { return Reply(["errorMessage": "Administrator login required"], status: "403 Forbidden", errorCode: -1013) @@ -159,6 +167,30 @@ final class WebConsoleAPI { } catch { return Reply(status: "503 Service Unavailable", errorCode: -1005) } + case ("e2ds", "patientsforcondition", "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 search = input["searchCondition"] as? [String: Any], + search["eModality"] as? String == "eAnyModality", + (search["dtAcquisitionTime"] as? String ?? "").isEmpty, + let doctor = input["pairDoctorType"] as? [String: String], + ["eDoctorAccountAll", "eDoctorAccountNone", "eDoctorAccountName"].contains(doctor["second"] ?? ""), + page >= 0, (1...1000).contains(limit), page <= Int.max / limit else { + return Reply(status: "400 Bad Request", errorCode: -1021) + } + let term = (search["strCondition"] as? String ?? "").trimmingCharacters(in: .whitespacesAndNewlines) + do { + let matches = doctor["second"] == "eDoctorAccountName" ? [] : try store.patients().filter { + term.isEmpty || $0.chartNumber.localizedStandardContains(term) || $0.name.localizedStandardContains(term) + } + let items = matches.dropFirst(page * limit).prefix(limit).map { + ["strChartNo": $0.chartNumber, "strLastName": $0.name, "strFirstName": "", + "strMiddleName": "", "dtBirthdate": "", "strGender": ""] + } + return Reply(["searchedPatientList": items, "nCnt": items.count], errorCode: items.isEmpty ? -100037 : 0) + } 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 @@ -333,9 +365,12 @@ final class WebConsoleAPI { 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 uid = image.studyUID.isEmpty ? metadata.studyUID : image.studyUID + if let studyUID, uid != studyUID { return nil } let modality: String switch (metadata.modality, image.dicomCount ?? 0) { + case _ where !image.modality.isEmpty: modality = image.modality + case _ where image.wireName.uppercased().hasSuffix(".CT"): modality = "eCT" case ("CT", _), ("CBCT", _), (_, 2...): modality = "eCT" case ("PX", _): modality = "ePanorama" case ("CR", _), ("DX", _): @@ -344,8 +379,8 @@ final class WebConsoleAPI { } 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, + "strChartNo": image.chartNumber, "strImgFileName": image.wireName, "modality": modality, + "dtAcqTime": formatter.string(from: image.importedAt), "strStudyInstanceUID": uid, "strAcqMode": "", "strRawFileName": "", "strVPanoFileName": "", "dtUpdateDateTime": "", "strModelName": "", "strDeviceInfo": "", "strNote": "", "strDeviceSerialNumber": "", "fKvp": 0, "fMa": 0, "fDose": 0, "fExposureTime": 0,