Files

455 lines
22 KiB
Swift

import CommonCrypto
import CryptoKit
import EzDentStorage
import Foundation
struct ServerAPI {
private static let session = URLSession(configuration: .ephemeral, delegate: NoRedirects(), delegateQueue: nil)
private static let noData = -100037
static let pageSize = 50
enum LoginMethod: String, CaseIterable, Identifiable {
case r2 = "AppLogInR2"
case legacy = "AppLogIn"
var id: Self { self }
}
struct Listing {
let patients: [PatientRecord]
let hasNextPage: Bool
var exactChartOnly = false
}
struct Chart {
var patient: PatientRecord
let images: [ServerImage]
}
struct ServerImage: Decodable {
let strImgFileName: String
let modality: String
let dtAcqTime: String?
private var filename: String {
strImgFileName.replacingOccurrences(of: "\\", with: "/").components(separatedBy: "/").last ?? strImgFileName
}
var isArchive: Bool {
let ext = (filename as NSString).pathExtension.lowercased()
return ["ct", "ctx"].contains(ext) || (modality == "eCT" && !["dcm", "dicom"].contains(ext))
}
var id: UUID { ServerAPI.id("image:" + strImgFileName) }
var record: PatientImage {
let date = dtAcqTime.flatMap(Self.parseDate)
return PatientImage(id: id, name: filename,
importedAt: date ?? .distantPast)
}
private static func parseDate(_ date: String) -> Date? {
if let result = ISO8601DateFormatter().date(from: date) { return result }
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
for format in ["yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss", "yyyyMMddHHmmss"] {
formatter.dateFormat = format
if let result = formatter.date(from: date) { return result }
}
return nil
}
}
private struct Patient: Decodable {
let strChartNo: String
let strLastName: String?
let strFirstName: String?
let strMiddleName: String?
var record: PatientRecord {
let name = [strLastName, strFirstName, strMiddleName].compactMap { $0 }
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }
.joined(separator: " ")
return PatientRecord(id: ServerAPI.id("patient:" + strChartNo), name: name.isEmpty ? strChartNo : name,
chartNumber: strChartNo)
}
}
private struct Envelope: Decodable {
let errorCode: Int
}
let address: URL
private var token: String?
static func connect(to address: URL, username: String, password: String, method: LoginMethod) async throws -> Self {
struct Ping: Decodable { let message: String }
struct Login: Decodable { let token: String }
var api = Self(address: address, token: nil)
let ping: Ping = try await api.fetch(api.request("auth/ping"), route: "auth/ping")
guard ping.message == "Pong" else { throw ServerError.invalidResponse }
let route = "auth/" + method.rawValue.lowercased()
let payload = try loginPayload(username: username, password: password)
let request = try api.jsonRequest(route, ["data": payload])
let login: Login = try await api.fetch(request, route: route, acceptedCodes: method == .r2 ? [-8001022] : [])
guard login.token.split(separator: ".").count == 3 else { throw ServerError.invalidResponse }
api.token = login.token
return api
}
func search(_ input: String, page: Int = 0) async throws -> Listing {
struct Result: Decodable { let searchedPatientList: [Patient]? }
let query = input.trimmingCharacters(in: .whitespacesAndNewlines)
let route: String
var fields: [String: Any] = ["pageNum": page, "numItems": Self.pageSize]
let doctor = ["first": "", "second": "eDoctorAccountAll"]
if query.isEmpty {
route = "e2ds/patientsbynumlistforrecentlyacquired"
fields["DoctorNameAccountTypePair"] = doctor
} else {
route = "e2ds/patientsforcondition"
fields["searchCondition"] = ["strCondition": query, "eModality": "eAnyModality", "dtAcquisitionTime": ""]
fields["pairDoctorType"] = doctor
}
do {
let result: Result = try await fetch(jsonRequest(route, fields), route: route, acceptedCodes: [Self.noData])
let records = result.searchedPatientList?.map(\.record) ?? []
return Listing(patients: records, hasNextPage: records.count == Self.pageSize)
} catch let error as ServerError where error.isMissingRoute && !query.isEmpty && page == 0 {
let patient = try await findChart(query)
return Listing(patients: patient.map { [$0] } ?? [], hasNextPage: false, exactChartOnly: true)
}
}
private func findChart(_ chartNumber: String) async throws -> PatientRecord? {
struct ChartResponse: Decodable { let patientInfo: Patient }
let route = "e2ds/patientsbychartno"
let request = request(route, query: [decodedAgain("chartno", chartNumber)])
do {
let response: ChartResponse = try await fetch(request, route: route)
return response.patientInfo.record
} catch ServerError.api(Self.noData, _) {
return nil
}
}
func chart(_ chartNumber: String) async throws -> Chart {
guard let patient = try await findChart(chartNumber) else { throw ServerError.patientMissing }
return try await chartImages(for: patient)
}
func chartImages(for patient: PatientRecord) async throws -> Chart {
struct Images: Decodable { let vecImageInfo: [ServerImage]? }
let route = "e2ds/imagesbychartno"
var images: [ServerImage] = []
var paths = Set<String>()
var page = 0
while true {
let request = try jsonRequest(route, ["strChartNo": patient.chartNumber, "pageNum": page,
"numItems": Self.pageSize])
let response: Images = try await fetch(request, route: route, acceptedCodes: [Self.noData])
let items = response.vecImageInfo ?? []
let unique = items.filter { !$0.strImgFileName.isEmpty && paths.insert($0.strImgFileName).inserted }
images += unique
guard items.count == Self.pageSize, !unique.isEmpty else { break }
page += 1
}
var record = patient
record.images = images.map(\.record)
return Chart(patient: record, images: images)
}
func create(name: String, chartNumber: String) async throws -> PatientRecord {
let name = name.trimmingCharacters(in: .whitespacesAndNewlines)
let chart = chartNumber.trimmingCharacters(in: .whitespacesAndNewlines)
let route = "e2ds/patients"
let fields = [
"strChartNo": chart, "strLastName": name, "strFirstName": "", "strMiddleName": "",
"strEmail": "", "strSocialID": "", "strPhone": "", "strMobile": "", "strZipCode": "",
"strAddress": "", "strPhotoIDName": "", "strGender": "O", "eSourceType": "eUnknownSourceType"
]
let _: Envelope = try await fetch(jsonRequest(route, fields), route: route)
return PatientRecord(id: Self.id("patient:" + chart), name: name, chartNumber: chart)
}
func upload(_ file: URL, chart: String, dicom: Bool) async throws -> ServerImage {
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
var request = request(route, method: "POST")
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let preparation = Task.detached(priority: .userInitiated) {
try Self.writeMultipart(to: body, file: file, filename: filename, boundary: boundary, fields: fields)
}
try await withTaskCancellationHandler {
try await preparation.value
} onCancel: {
preparation.cancel()
}
try Task.checkCancellation()
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 == 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"
var query = [decodedAgain("path", image.strImgFileName)]
if !image.isArchive { query.append(URLQueryItem(name: "type", value: "IMG")) }
let (file, response) = try await Self.session.download(for: request(route, query: query))
defer { try? FileManager.default.removeItem(at: file) }
let http = try validate(response, route: route)
if http.mimeType == "application/json" {
let body = try FileHandle(forReadingFrom: file)
defer { try? body.close() }
let data = try body.read(upToCount: 65536) ?? Data()
let _: Envelope = try decode(data, http, route: route)
throw ServerError.invalidResponse
}
try Task.checkCancellation()
let destination = originals.directory.appendingPathComponent(image.isArchive ? "study.CT" : "original")
try FileManager.default.moveItem(at: file, to: destination)
if image.isArchive {
let extraction = Task.detached(priority: .userInitiated) {
try originals.unpackCT(at: destination)
}
try await withTaskCancellationHandler {
try await extraction.value
} onCancel: {
extraction.cancel()
}
} else {
originals.urls = [destination]
originals.isDICOM = DICOMImage.recognizes(destination)
|| ["dcm", "dicom"].contains((image.record.name as NSString).pathExtension.lowercased())
}
return originals
}
private func decodedAgain(_ name: String, _ value: String) -> URLQueryItem {
let unreserved = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~")
return URLQueryItem(name: name, value: value.addingPercentEncoding(withAllowedCharacters: unreserved))
}
private func request(_ route: String, method: String = "GET", query: [URLQueryItem] = []) -> URLRequest {
var components = URLComponents()
components.scheme = address.scheme
components.host = address.host
components.port = address.port
components.path = "/api/v1/" + route
if !query.isEmpty { components.queryItems = query }
var request = URLRequest(url: components.url!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 30)
request.httpMethod = method
if let token { request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") }
return request
}
private func jsonRequest(_ route: String, _ fields: [String: Any]) throws -> URLRequest {
var request = request(route, method: "POST")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try JSONSerialization.data(withJSONObject: fields)
return request
}
private func fetch<T: Decodable>(_ request: URLRequest, route: String, acceptedCodes: Set<Int> = []) async throws -> T {
let (data, response) = try await Self.session.data(for: request)
return try decode(data, response, route: route, acceptedCodes: acceptedCodes)
}
private func decode<T: Decodable>(_ data: Data, _ response: URLResponse, route: String,
acceptedCodes: Set<Int> = []) throws -> T {
let decoder = JSONDecoder()
let envelope = try? decoder.decode(Envelope.self, from: data)
do {
_ = try validate(response, route: route)
} catch {
if let envelope, envelope.errorCode != 0, (response as? HTTPURLResponse)?.statusCode == 401 {
throw ServerError.api(envelope.errorCode, route)
}
throw error
}
guard let envelope else { throw ServerError.invalidResponse }
guard envelope.errorCode == 0 || acceptedCodes.contains(envelope.errorCode) else {
throw ServerError.api(envelope.errorCode, route)
}
guard let result = try? decoder.decode(T.self, from: data) else { throw ServerError.invalidResponse }
return result
}
@discardableResult
private func validate(_ response: URLResponse, route: String) throws -> HTTPURLResponse {
guard let response = response as? HTTPURLResponse else { throw ServerError.invalidResponse }
guard (200..<300).contains(response.statusCode) else { throw ServerError.http(response.statusCode, route) }
return response
}
private static func id(_ value: String) -> UUID {
let bytes = Array(SHA256.hash(data: Data(value.utf8)).prefix(16))
return UUID(uuid: (bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15]))
}
private static func loginPayload(username: String, password: String) throws -> String {
// Protocol constants from the original EzServer authentication implementation.
let key = Data(base64Encoded: "fCVpkpDy3QII1bJ0uklkvQ==")!
let iv = Data(base64Encoded: "p+O8XWH7eWQw1xifYtxx5Q==")!
var plain = try JSONSerialization.data(withJSONObject: [
"ver": "1.0.0", "client": ["name": "EzDent macOS", "ver": "0.1.0"],
"auth": ["enc": "b64", "usr": Data(username.utf8).base64EncodedString(),
"sec": Data(password.utf8).base64EncodedString(),
"exp": Int(Date().addingTimeInterval(8 * 3600).timeIntervalSince1970)]
])
// ISO/IEC 9797-1 method 2 always adds the marker and pads to a block boundary.
plain.append(0x80)
while !plain.count.isMultiple(of: kCCBlockSizeAES128) { plain.append(0) }
let capacity = plain.count
var result = Data(count: capacity)
var written = 0
let status = result.withUnsafeMutableBytes { output in
plain.withUnsafeBytes { input in
key.withUnsafeBytes { keyBytes in
iv.withUnsafeBytes { ivBytes in
CCCrypt(CCOperation(kCCEncrypt), CCAlgorithm(kCCAlgorithmAES), 0,
keyBytes.baseAddress, key.count, ivBytes.baseAddress,
input.baseAddress, capacity, output.baseAddress, capacity, &written)
}
}
}
}
guard status == kCCSuccess, written == capacity else { throw ServerError.invalidResponse }
return result.base64EncodedString()
}
private static func writeMultipart(to body: URL, file: URL, filename: String, boundary: String,
fields: [String: String]) throws {
let size = try file.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey])
guard size.isRegularFile == true, (size.fileSize ?? 0) > 0 else { throw ServerError.invalidFile }
try Data().write(to: body)
let output = try FileHandle(forWritingTo: body)
let input = try FileHandle(forReadingFrom: file)
defer {
try? input.close()
try? output.close()
}
for (name, value) in fields {
let field = "--\(boundary)\r\nContent-Disposition: form-data; name=\"\(name)\"\r\n\r\n\(value)\r\n"
try output.write(contentsOf: Data(field.utf8))
}
let header = "--\(boundary)\r\nContent-Disposition: form-data; name=\"attachedFile\"; filename=\"\(filename)\"\r\n"
+ "Content-Type: application/octet-stream\r\n\r\n"
try output.write(contentsOf: Data(header.utf8))
while let chunk = try input.read(upToCount: 256 * 1024), !chunk.isEmpty {
try Task.checkCancellation()
try output.write(contentsOf: chunk)
}
try output.write(contentsOf: Data("\r\n--\(boundary)--\r\n".utf8))
}
}
enum ServerError: LocalizedError {
case invalidResponse, invalidFile, archiveCreation, patientMissing, invalidArchive
case http(Int, String), api(Int, String)
var isMissingRoute: Bool {
if case let .http(status, _) = self { return [404, 405, 501].contains(status) }
return false
}
var errorDescription: String? {
switch self {
case .invalidResponse: return "EzServer вернул неожиданный ответ."
case .invalidFile: return "Выберите непустой файл снимка поддерживаемого формата."
case .archiveCreation: return "Не удалось собрать архив КТ из выбранных DICOM-файлов."
case .patientMissing: return "Карточка по этому номеру не найдена."
case .invalidArchive: return "EzServer вернул повреждённый, защищённый или неподдерживаемый архив КТ."
case .http(401, _), .api(-8001511, _): return "Доступ к EzServer отклонён. Войдите снова."
case .api(-8001001, _): return "EzServer не принял имя пользователя или пароль."
case .api(-100029, _): return "Карточка с таким номером уже существует."
case let .http(status, route): return "EzServer /api/v1/\(route): HTTP \(status)."
case let .api(code, route): return "EzServer /api/v1/\(route): код \(code)."
}
}
}
private final class NoRedirects: NSObject, URLSessionTaskDelegate {
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void) {
completionHandler(nil)
}
}