Implement EzDent patient search and original file transfers
This commit is contained in:
1 parent
69f70d0325
commit
017553f3db
4 files changed
+308
-13
No files matched your search
@@ -145,6 +145,31 @@ final class LocalServer {
|
||||
["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"].contains(method) {
|
||||
diagnosticRoutes[ObjectIdentifier(connection)] = "\(method) /api/v1/\(route[0])/\(route[1])"
|
||||
}
|
||||
if route.first == "fs", route.count >= 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"],
|
||||
|
||||
Reference in new issue
Block a user