Upload CT studies through the original EzServer API
This commit is contained in:
1 parent
b11a8f62f9
commit
6eb601a4fe
3 files changed
+74
-22
No files matched your search
@@ -173,24 +173,48 @@ struct ServerAPI {
|
||||
}
|
||||
|
||||
func upload(_ file: URL, chart: String, dicom: Bool) async throws -> ServerImage {
|
||||
struct Uploaded: Decodable { let updatedFileName: String; let updatedFileType: String }
|
||||
let ext = dicom ? "dcm" : file.pathExtension.lowercased()
|
||||
guard !ext.isEmpty, ext.utf8.allSatisfy({ (48...57).contains($0) || (97...122).contains($0) }) else {
|
||||
throw ServerError.invalidFile
|
||||
}
|
||||
let filename = UUID().uuidString + "." + ext
|
||||
return try await upload(file, filename: filename, route: "fs/filesbychartno", type: "IMG",
|
||||
modality: "eFile", fields: [
|
||||
"chartNo": chart, "fileType": "IMG", "attachedFileName": filename,
|
||||
"fileExt": ext, "modality": "eFile", "acqMode": "", "isImported": "TRUE",
|
||||
"studyInstanceUID": "", "eSourceType": "eUnknownSourceType"
|
||||
])
|
||||
}
|
||||
|
||||
func uploadCT(_ sources: [URL], chart: String) async throws -> ServerImage {
|
||||
let staging = try ServerOriginals()
|
||||
let filename = UUID().uuidString + ".CT"
|
||||
let archive = staging.directory.appendingPathComponent(filename)
|
||||
let preparation = Task.detached(priority: .userInitiated) {
|
||||
try Self.makeCTArchive(at: archive, sources: sources)
|
||||
}
|
||||
try await withTaskCancellationHandler {
|
||||
try await preparation.value
|
||||
} onCancel: {
|
||||
preparation.cancel()
|
||||
}
|
||||
try Task.checkCancellation()
|
||||
defer { withExtendedLifetime(staging) {} }
|
||||
return try await upload(archive, filename: filename, route: "fs/ctfilesbychartno", type: "CT",
|
||||
modality: "eCT", fields: [
|
||||
"chartNo": chart, "attachedFileName": filename, "eGroupingMode": "eUnknownGroupingMode",
|
||||
"eSourceType": "eUnknownSourceType", "studyInstanceUID": ""
|
||||
])
|
||||
}
|
||||
|
||||
private func upload(_ file: URL, filename: String, route: String, type: String, modality: String,
|
||||
fields: [String: String]) async throws -> ServerImage {
|
||||
struct Uploaded: Decodable { let updatedFileName: String; let updatedFileType: String }
|
||||
let directory = try ServerOriginals()
|
||||
let body = directory.directory.appendingPathComponent("multipart")
|
||||
let boundary = UUID().uuidString
|
||||
let route = "fs/filesbychartno"
|
||||
var request = request(route, method: "POST")
|
||||
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
|
||||
let modality = "eFile"
|
||||
let fields = [
|
||||
"chartNo": chart, "fileType": "IMG", "attachedFileName": filename,
|
||||
"fileExt": ext, "modality": modality, "acqMode": "", "isImported": "TRUE",
|
||||
"studyInstanceUID": "", "eSourceType": "eUnknownSourceType"
|
||||
]
|
||||
let preparation = Task.detached(priority: .userInitiated) {
|
||||
try Self.writeMultipart(to: body, file: file, filename: filename, boundary: boundary, fields: fields)
|
||||
}
|
||||
@@ -203,13 +227,44 @@ struct ServerAPI {
|
||||
defer { withExtendedLifetime(directory) {} }
|
||||
let (data, response) = try await Self.session.upload(for: request, fromFile: body)
|
||||
let uploaded: Uploaded = try decode(data, response, route: route)
|
||||
guard !uploaded.updatedFileName.isEmpty, uploaded.updatedFileType == "IMG" else {
|
||||
guard !uploaded.updatedFileName.isEmpty, uploaded.updatedFileType == type else {
|
||||
throw ServerError.invalidResponse
|
||||
}
|
||||
return ServerImage(strImgFileName: uploaded.updatedFileName, modality: modality,
|
||||
dtAcqTime: ISO8601DateFormatter().string(from: Date()))
|
||||
}
|
||||
|
||||
private static func makeCTArchive(at archive: URL, sources: [URL]) throws {
|
||||
guard (1...4096).contains(sources.count) else { throw ServerError.archiveCreation }
|
||||
let folder = archive.deletingLastPathComponent()
|
||||
var filenames: [String] = []
|
||||
var bytesRemaining = 2 * 1024 * 1024 * 1024
|
||||
for (index, source) in sources.enumerated() {
|
||||
try Task.checkCancellation()
|
||||
let resolved = source.resolvingSymlinksInPath()
|
||||
let attributes = try resolved.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey])
|
||||
guard attributes.isRegularFile == true, let size = attributes.fileSize, size > 0, size <= bytesRemaining
|
||||
else { throw ServerError.archiveCreation }
|
||||
bytesRemaining -= size
|
||||
let filename = "slice-\(index + 1).dcm"
|
||||
// With no -y, zip stores the contents of each link under this controlled filename.
|
||||
try FileManager.default.createSymbolicLink(at: folder.appendingPathComponent(filename),
|
||||
withDestinationURL: resolved)
|
||||
filenames.append(filename)
|
||||
}
|
||||
let zip = Process()
|
||||
zip.executableURL = URL(fileURLWithPath: "/usr/bin/zip")
|
||||
zip.currentDirectoryURL = folder
|
||||
zip.environment = [:]
|
||||
zip.arguments = ["-q", "-X", "-0", archive.path] + filenames
|
||||
zip.standardOutput = FileHandle.nullDevice
|
||||
zip.standardError = FileHandle.nullDevice
|
||||
try zip.run()
|
||||
zip.waitUntilExit()
|
||||
try Task.checkCancellation()
|
||||
guard zip.terminationStatus == 0 else { throw ServerError.archiveCreation }
|
||||
}
|
||||
|
||||
func download(_ image: ServerImage) async throws -> ServerOriginals {
|
||||
let originals = try ServerOriginals()
|
||||
let route = image.isArchive ? "fs/ctfilesbypath" : "fs/filesbytypeandpath"
|
||||
@@ -366,7 +421,7 @@ struct ServerAPI {
|
||||
}
|
||||
|
||||
enum ServerError: LocalizedError {
|
||||
case invalidResponse, invalidFile, seriesUpload, patientMissing, invalidArchive
|
||||
case invalidResponse, invalidFile, archiveCreation, patientMissing, invalidArchive
|
||||
case http(Int, String), api(Int, String)
|
||||
|
||||
var isMissingRoute: Bool {
|
||||
@@ -378,7 +433,7 @@ enum ServerError: LocalizedError {
|
||||
switch self {
|
||||
case .invalidResponse: return "EzServer вернул неожиданный ответ."
|
||||
case .invalidFile: return "Выберите непустой файл снимка поддерживаемого формата."
|
||||
case .seriesUpload: return "Загрузка КТ требует архива .CT и маршрута fs/ctfilesbychartno."
|
||||
case .archiveCreation: return "Не удалось собрать архив КТ из выбранных DICOM-файлов."
|
||||
case .patientMissing: return "Карточка по этому номеру не найдена."
|
||||
case .invalidArchive: return "EzServer вернул повреждённый, защищённый или неподдерживаемый архив КТ."
|
||||
case .http(401, _), .api(-8001511, _): return "Доступ к EzServer отклонён. Войдите снова."
|
||||
|
||||
Reference in new issue
Block a user