Connect EzDent to the original EzServer API
This commit is contained in:
1 parent
8d93e526c3
commit
b11a8f62f9
13 files changed
+855
-108
No files matched your search
+2
-1
@@ -6,7 +6,8 @@ let package = Package(
|
||||
platforms: [.macOS(.v13)],
|
||||
products: [.executable(name: "EzDent", targets: ["EzDent"])],
|
||||
targets: [
|
||||
.systemLibrary(name: "CArchive"),
|
||||
.target(name: "EzDentStorage"),
|
||||
.executableTarget(name: "EzDent", dependencies: ["EzDentStorage"])
|
||||
.executableTarget(name: "EzDent", dependencies: ["CArchive", "EzDentStorage"])
|
||||
]
|
||||
)
|
||||
@@ -16,6 +16,12 @@
|
||||
<string>1</string>
|
||||
<key>LSMinimumSystemVersion</key>
|
||||
<string>13.0</string>
|
||||
<key>NSAppTransportSecurity</key>
|
||||
<dict>
|
||||
<key>NSAllowsLocalNetworking</key>
|
||||
<true/>
|
||||
</dict>
|
||||
|
||||
<key>NSLocalNetworkUsageDescription</key>
|
||||
<string>EzDent подключается к указанному вами серверу в локальной сети.</string>
|
||||
<key>NSHighResolutionCapable</key>
|
||||
|
||||
@@ -29,7 +29,7 @@ open dist/EzDent.app
|
||||
|
||||
Из справки Windows-версии взяты сценарии поиска и редактирования карточек, импорта и просмотра снимков и настройки яркости и контраста. Отчёты и захват с оборудования пока не реализованы.
|
||||
|
||||
В настройках приложения (`⌘,`) можно сохранить хост и порт ezServer и проверить TCP-подключение к этому адресу. Клиент пока не выполняет авторизацию и запросы к API.
|
||||
Откройте настройки приложения (`⌘,`), укажите хост, порт, имя пользователя и пароль оригинального EzServer, затем нажмите «Подключиться к EzServer». По умолчанию клиент использует AppLogInR2. Для сервера с предыдущим вариантом входа можно выбрать AppLogIn. JWT действует в текущем сеансе приложения. Кнопка «Локальный режим» возвращает к библиотеке на Mac.
|
||||
|
||||
## Что выяснилось из установщика EzDent-i 3.1.11
|
||||
|
||||
@@ -48,4 +48,10 @@ open dist/EzDent.app
|
||||
|
||||
## EzServer для macOS
|
||||
|
||||
Сервер разрабатывается и собирается в отдельном репозитории [ezServer-MacOS](https://git.anidev.ru/SantaSpeen/ezServer-MacOS). Клиент EzDent использует локальную библиотеку. Сервер может читать её через общий формат хранения.
|
||||
Клиент обращается к оригинальному API `/api/v1`. При пустом поле поиска он показывает недавно полученные карточки. Поиск по имени и номеру использует `POST e2ds/patientsforcondition`. Если на сервере этот маршрут отсутствует, клиент явно показывает ограничение и использует `GET e2ds/patientsbychartno?chartno=…` для поиска по точному номеру.
|
||||
|
||||
Для просмотра клиент получает метаданные через `POST e2ds/imagesbychartno`, 2D-оригинал через `GET fs/filesbytypeandpath?type=IMG&path=…`, а архив КТ через `GET fs/ctfilesbypath?path=…`. Обычные изображения и отдельные 2D DICOM передаются через `POST fs/filesbychartno` в `multipart/form-data` с частью `attachedFile`. Приложение проверяет HTTP-статус и прикладной `errorCode`.
|
||||
|
||||
Загрузка КТ пока недоступна в клиенте. Оригинальный `POST fs/ctfilesbychartno` ожидает `multipart/form-data` с ZIP-архивом DICOM под расширением `.CT` в части `attachedFile` и полями `chartNo`, `attachedFileName`, `eGroupingMode`, `eSourceType`, `studyInstanceUID` и необязательным `acqTime`. Успех возвращает `errorCode: 0`, `updatedFileType: "CT"` и `updatedFileName`. Для проверки нужен сервер, который принимает такой архив и полностью отдаёт его через `GET fs/ctfilesbypath`.
|
||||
|
||||
Тестовый сервер из отдельного репозитория поддерживает вход, чтение и создание карточек и чтение метаданных. На проверенной сборке файловые запросы `GET fs/filesbytypeandpath` и `GET fs/ctfilesbypath` вернули HTTP 404, а `POST fs/filesbychartno` вернул HTTP 405. [ezServer-MacOS](https://git.anidev.ru/SantaSpeen/ezServer-MacOS)
|
||||
@@ -0,0 +1,24 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
// These public libarchive functions are exported by macOS. The SDK ships the
|
||||
// library interface but omits the headers, so declare the subset used here.
|
||||
struct archive;
|
||||
struct archive_entry;
|
||||
|
||||
enum {
|
||||
ARCHIVE_EOF = 1,
|
||||
ARCHIVE_OK = 0
|
||||
};
|
||||
|
||||
struct archive *archive_read_new(void);
|
||||
int archive_read_support_format_zip(struct archive *);
|
||||
int archive_read_open_filename(struct archive *, const char *, size_t);
|
||||
int archive_read_free(struct archive *);
|
||||
int archive_read_next_header(struct archive *, struct archive_entry **);
|
||||
ssize_t archive_read_data(struct archive *, void *, size_t);
|
||||
mode_t archive_entry_filetype(struct archive_entry *);
|
||||
int64_t archive_entry_size(struct archive_entry *);
|
||||
const char *archive_entry_hardlink(struct archive_entry *);
|
||||
@@ -0,0 +1,5 @@
|
||||
module CArchive [system] {
|
||||
header "archive.h"
|
||||
link "archive"
|
||||
export *
|
||||
}
|
||||
@@ -25,7 +25,8 @@ struct DICOMVolume {
|
||||
guard !urls.isEmpty, urls.count <= 4096 else { throw DICOMError.geometry }
|
||||
let first = try DICOMImage(url: urls[0])
|
||||
let planeSize = first.width * first.height
|
||||
guard planeSize <= 64_000_000 / urls.count else { throw DICOMError.unsupported }
|
||||
let voxelLimit = urls.count == 1 ? 64_000_000 : 96_000_000
|
||||
guard planeSize <= voxelLimit / urls.count else { throw DICOMError.unsupported }
|
||||
size = SIMD3(first.width, first.height, urls.count == 1 ? first.frames : urls.count)
|
||||
window = first.window
|
||||
inverted = first.monochrome1
|
||||
@@ -56,7 +57,13 @@ struct DICOMVolume {
|
||||
}
|
||||
let sorted = try Self.sortSlices(geometry)
|
||||
spacing = sorted.spacing
|
||||
pixels = sorted.order.flatMap { slices[$0] }
|
||||
var ordered: [Float] = []
|
||||
ordered.reserveCapacity(planeSize * urls.count)
|
||||
for index in sorted.order {
|
||||
ordered.append(contentsOf: slices[index])
|
||||
slices[index].removeAll()
|
||||
}
|
||||
pixels = ordered
|
||||
}
|
||||
minimum = pixels.min() ?? 0
|
||||
maximum = pixels.max() ?? 1
|
||||
|
||||
@@ -4,16 +4,20 @@ import SwiftUI
|
||||
struct EzDentApp: App {
|
||||
@StateObject private var library = PatientLibrary()
|
||||
|
||||
@StateObject private var connection = ServerConnection()
|
||||
|
||||
var body: some Scene {
|
||||
WindowGroup {
|
||||
PatientWorkspace()
|
||||
PatientWorkspace(server: connection.active?.api)
|
||||
.id(connection.active?.id)
|
||||
.environmentObject(connection)
|
||||
.environmentObject(library)
|
||||
.frame(minWidth: 920, minHeight: 480)
|
||||
}
|
||||
.defaultSize(width: 1050, height: 680)
|
||||
|
||||
Settings {
|
||||
ServerSettings()
|
||||
ServerSettings().environmentObject(connection)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,33 @@
|
||||
import EzDentStorage
|
||||
import AppKit
|
||||
import ImageIO
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
struct PatientWorkspace: View {
|
||||
let server: ServerAPI?
|
||||
@EnvironmentObject private var connection: ServerConnection
|
||||
@State private var serverPatients: [PatientRecord] = []
|
||||
@State private var serverChart: ServerAPI.Chart?
|
||||
@State private var nextPatientPage: Int?
|
||||
@State private var exactChartOnly = false
|
||||
@State private var isSearching = false
|
||||
@State private var searchError: String?
|
||||
@State private var searchRevision = 0
|
||||
@State private var detailError: String?
|
||||
@State private var detailRevision = 0
|
||||
@EnvironmentObject private var library: PatientLibrary
|
||||
@State private var search = ""
|
||||
@State private var patientID: PatientRecord.ID?
|
||||
@State private var imageID: PatientImage.ID?
|
||||
@State private var editor: PatientEditor?
|
||||
@State private var importPatientID: PatientRecord.ID?
|
||||
@State private var importPatient: PatientRecord?
|
||||
@State private var showImporter = false
|
||||
@State private var isImporting = false
|
||||
@State private var errorMessage: String?
|
||||
|
||||
private var filteredPatients: [PatientRecord] {
|
||||
if server != nil { return serverPatients }
|
||||
let query = search.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
return library.patients.filter {
|
||||
query.isEmpty || $0.name.localizedStandardContains(query)
|
||||
@@ -23,7 +36,8 @@ struct PatientWorkspace: View {
|
||||
}
|
||||
|
||||
private var patient: PatientRecord? {
|
||||
library.patients.first { $0.id == patientID }
|
||||
if server != nil { return serverChart?.patient.id == patientID ? serverChart?.patient : nil }
|
||||
return library.patients.first { $0.id == patientID }
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
@@ -43,11 +57,20 @@ struct PatientWorkspace: View {
|
||||
.background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 8))
|
||||
.padding(12)
|
||||
|
||||
if filteredPatients.isEmpty, !search.isEmpty {
|
||||
if isSearching {
|
||||
ProgressView().controlSize(.small).padding(.bottom, 8)
|
||||
} else if let searchError {
|
||||
Text(searchError).foregroundStyle(.secondary).padding(.horizontal, 12)
|
||||
Button("Повторить поиск") { searchRevision += 1 }
|
||||
} else if filteredPatients.isEmpty, !search.isEmpty {
|
||||
Text("Пациенты не найдены")
|
||||
.foregroundStyle(.secondary)
|
||||
.padding(.bottom, 12)
|
||||
}
|
||||
if exactChartOnly {
|
||||
Text("EzServer поддерживает только поиск по точному номеру карты.")
|
||||
.font(.caption).foregroundStyle(.secondary).padding(.horizontal, 12)
|
||||
}
|
||||
List(filteredPatients, selection: $patientID) { record in
|
||||
Label {
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
@@ -62,6 +85,14 @@ struct PatientWorkspace: View {
|
||||
}
|
||||
.listStyle(.sidebar)
|
||||
|
||||
if let page = nextPatientPage {
|
||||
Button("Показать ещё") {
|
||||
let query = search
|
||||
Task { await searchServer(query, page: page) }
|
||||
}
|
||||
.disabled(isSearching)
|
||||
.padding(.bottom, 8)
|
||||
}
|
||||
Divider()
|
||||
Button { newPatient() } label: {
|
||||
Label("Новый пациент", systemImage: "plus")
|
||||
@@ -69,13 +100,24 @@ struct PatientWorkspace: View {
|
||||
}
|
||||
.controlSize(.large)
|
||||
.padding(12)
|
||||
.disabled(library.loadError != nil)
|
||||
.disabled(server == nil && library.loadError != nil)
|
||||
}
|
||||
.navigationTitle("Пациенты")
|
||||
.navigationTitle(server == nil ? "Пациенты" : "Пациенты EzServer")
|
||||
.navigationSplitViewColumnWidth(min: 220, ideal: 260)
|
||||
} detail: {
|
||||
if let patient {
|
||||
patientDetail(patient)
|
||||
} else if server != nil {
|
||||
if let detailError {
|
||||
emptyState("Карточка недоступна", detail: detailError, icon: "exclamationmark.triangle") {
|
||||
Button("Повторить") { detailRevision += 1 }
|
||||
}
|
||||
} else if patientID != nil {
|
||||
ProgressView("Загрузка карточки…")
|
||||
} else {
|
||||
emptyState("Выберите пациента", detail: "Найдите на EzServer карточку по имени или номеру.",
|
||||
icon: "person.crop.rectangle")
|
||||
}
|
||||
} else if let error = library.loadError {
|
||||
emptyState("Библиотека недоступна", detail: error, icon: "exclamationmark.triangle")
|
||||
} else if library.patients.isEmpty {
|
||||
@@ -88,20 +130,42 @@ struct PatientWorkspace: View {
|
||||
emptyState("Выберите пациента", detail: "Найдите карточку по имени или номеру.", icon: "person.crop.rectangle")
|
||||
}
|
||||
}
|
||||
.toolbar {
|
||||
if server != nil {
|
||||
Button("Локальный режим") { connection.active = nil }
|
||||
.disabled(isImporting || editor != nil)
|
||||
}
|
||||
}
|
||||
.task(id: SearchRequest(query: search, revision: searchRevision)) {
|
||||
await searchServer(search)
|
||||
}
|
||||
.task(id: DetailRequest(patient: patientID, revision: detailRevision)) {
|
||||
await loadServerPatient(patientID)
|
||||
}
|
||||
.onChange(of: patientID) { _ in
|
||||
imageID = patient?.images.first?.id
|
||||
detailError = nil
|
||||
}
|
||||
.sheet(item: $editor) { draft in
|
||||
PatientEditorSheet(draft: draft) { name, chart in
|
||||
let id = try library.savePatient(id: draft.patientID, name: name, chartNumber: chart)
|
||||
search = ""
|
||||
patientID = id
|
||||
if let server {
|
||||
let record = try await server.create(name: name, chartNumber: chart)
|
||||
serverChart = ServerAPI.Chart(patient: record, images: [])
|
||||
serverPatients.insert(record, at: 0)
|
||||
search = record.chartNumber
|
||||
searchRevision += 1
|
||||
patientID = record.id
|
||||
} else {
|
||||
let id = try library.savePatient(id: draft.patientID, name: name, chartNumber: chart)
|
||||
search = ""
|
||||
patientID = id
|
||||
}
|
||||
}
|
||||
}
|
||||
.fileImporter(isPresented: $showImporter, allowedContentTypes: [.data, .folder], allowsMultipleSelection: true,
|
||||
onCompletion: { result in
|
||||
guard let patient = importPatientID else { return }
|
||||
importPatientID = nil
|
||||
guard let patient = importPatient else { return }
|
||||
importPatient = nil
|
||||
isImporting = true
|
||||
Task {
|
||||
defer { isImporting = false }
|
||||
@@ -126,10 +190,12 @@ struct PatientWorkspace: View {
|
||||
Text("Карта № \(record.chartNumber)").foregroundStyle(.secondary)
|
||||
}
|
||||
Spacer()
|
||||
Button { editor = PatientEditor(record) } label: {
|
||||
Label("Править карточку", systemImage: "pencil")
|
||||
if server == nil {
|
||||
Button { editor = PatientEditor(record) } label: {
|
||||
Label("Править карточку", systemImage: "pencil")
|
||||
}
|
||||
}
|
||||
Button { chooseImages(for: record.id) } label: {
|
||||
Button { chooseImages(for: record) } label: {
|
||||
Label("Добавить снимки…", systemImage: "plus")
|
||||
}
|
||||
.buttonStyle(.borderedProminent)
|
||||
@@ -142,7 +208,8 @@ struct PatientWorkspace: View {
|
||||
Divider()
|
||||
|
||||
if record.images.isEmpty {
|
||||
emptyState("Снимков пока нет", detail: "Выберите изображение или все DICOM-срезы одной серии.",
|
||||
emptyState("Снимков пока нет", detail: server == nil ? "Выберите изображение или все DICOM-срезы одной серии."
|
||||
: "Выберите изображение или 2D-файл DICOM.",
|
||||
icon: "photo.on.rectangle")
|
||||
} else {
|
||||
let selected = record.images.first { $0.id == imageID } ?? record.images[0]
|
||||
@@ -150,8 +217,10 @@ struct PatientWorkspace: View {
|
||||
List(record.images, selection: $imageID) { image in
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text(image.name).lineLimit(2)
|
||||
Text(image.importedAt.formatted(date: .abbreviated, time: .shortened))
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
if image.importedAt != .distantPast {
|
||||
Text(image.importedAt.formatted(date: .abbreviated, time: .shortened))
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
.padding(.vertical, 5)
|
||||
.tag(image.id)
|
||||
@@ -159,7 +228,9 @@ struct PatientWorkspace: View {
|
||||
.frame(width: 200)
|
||||
Divider()
|
||||
Group {
|
||||
if selected.dicomCount != nil {
|
||||
if let server, let image = serverChart?.images.first(where: { $0.id == selected.id }) {
|
||||
ServerImagePreview(api: server, image: image) { errorMessage = $0 }
|
||||
} else if selected.dicomCount != nil {
|
||||
DICOMViewer(urls: library.dicomURLs(for: selected), name: selected.name)
|
||||
} else {
|
||||
ImageViewer(image: selected, url: library.url(for: selected)) { message in
|
||||
@@ -178,12 +249,13 @@ struct PatientWorkspace: View {
|
||||
editor = PatientEditor(nil)
|
||||
}
|
||||
|
||||
private func chooseImages(for id: UUID) {
|
||||
importPatientID = id
|
||||
private func chooseImages(for patient: PatientRecord) {
|
||||
importPatient = patient
|
||||
showImporter = true
|
||||
}
|
||||
|
||||
private func importImages(_ result: Result<[URL], Error>, for importPatientID: UUID) async {
|
||||
private func importImages(_ result: Result<[URL], Error>, for targetChart: PatientRecord) async {
|
||||
let importPatientID = targetChart.id
|
||||
do {
|
||||
var errors: [String] = []
|
||||
var firstImported: UUID?
|
||||
@@ -197,7 +269,19 @@ struct PatientWorkspace: View {
|
||||
|
||||
for series in files.series {
|
||||
do {
|
||||
let image = try await library.importDICOM(from: series, for: importPatientID)
|
||||
let image: PatientImage
|
||||
if let server {
|
||||
guard series.count == 1 else { throw ServerError.seriesUpload }
|
||||
let source = series[0]
|
||||
let frames = try await Task.detached(priority: .userInitiated) {
|
||||
try DICOMVolume(urls: [source]).size.z
|
||||
}.value
|
||||
guard frames == 1 else { throw ServerError.seriesUpload }
|
||||
let uploaded = try await server.upload(source, chart: targetChart.chartNumber, dicom: true)
|
||||
image = uploaded.record
|
||||
} else {
|
||||
image = try await library.importDICOM(from: series, for: importPatientID)
|
||||
}
|
||||
firstImported = firstImported ?? image.id
|
||||
} catch {
|
||||
errors.append("\(series[0].lastPathComponent) — \(error.localizedDescription)")
|
||||
@@ -205,14 +289,33 @@ struct PatientWorkspace: View {
|
||||
}
|
||||
for url in files.images {
|
||||
do {
|
||||
let image = try library.importImage(from: url, for: importPatientID)
|
||||
let image: PatientImage
|
||||
if let server {
|
||||
guard let source = CGImageSourceCreateWithURL(url as CFURL, nil),
|
||||
CGImageSourceGetCount(source) > 0,
|
||||
CGImageSourceCopyPropertiesAtIndex(source, 0, nil) != nil else {
|
||||
throw ServerError.invalidFile
|
||||
}
|
||||
let uploaded = try await server.upload(url, chart: targetChart.chartNumber, dicom: false)
|
||||
image = uploaded.record
|
||||
} else {
|
||||
image = try library.importImage(from: url, for: importPatientID)
|
||||
}
|
||||
firstImported = firstImported ?? image.id
|
||||
} catch {
|
||||
errors.append("\(url.lastPathComponent) — \(error.localizedDescription)")
|
||||
}
|
||||
}
|
||||
if patientID == importPatientID, let firstImported {
|
||||
imageID = firstImported
|
||||
if let server {
|
||||
do {
|
||||
let updated = try await server.chartImages(for: targetChart)
|
||||
if patientID == importPatientID { serverChart = updated }
|
||||
} catch {
|
||||
errors.append("Обновление списка снимков — \(error.localizedDescription)")
|
||||
}
|
||||
}
|
||||
if patientID == importPatientID { imageID = firstImported }
|
||||
}
|
||||
if files.images.isEmpty, files.series.isEmpty {
|
||||
errors.append("В выбранных папках нет поддерживаемых снимков.")
|
||||
@@ -223,6 +326,62 @@ struct PatientWorkspace: View {
|
||||
}
|
||||
}
|
||||
|
||||
private struct SearchRequest: Equatable {
|
||||
let query: String
|
||||
let revision: Int
|
||||
}
|
||||
|
||||
private struct DetailRequest: Equatable {
|
||||
let patient: UUID?
|
||||
let revision: Int
|
||||
}
|
||||
|
||||
private func searchServer(_ query: String, page: Int = 0) async {
|
||||
guard let server, search == query, page == 0 || !isSearching else { return }
|
||||
let revision = searchRevision
|
||||
if page == 0 {
|
||||
nextPatientPage = nil
|
||||
exactChartOnly = false
|
||||
}
|
||||
isSearching = true
|
||||
searchError = nil
|
||||
do {
|
||||
if page == 0 { try await Task.sleep(for: .milliseconds(250)) }
|
||||
let listing = try await server.search(query, page: page)
|
||||
try Task.checkCancellation()
|
||||
guard search == query, revision == searchRevision else { return }
|
||||
let existing = page == 0 ? Set<UUID>() : Set(serverPatients.map(\.id))
|
||||
let newPatients = listing.patients.filter { !existing.contains($0.id) }
|
||||
if page == 0 {
|
||||
serverPatients = newPatients
|
||||
} else {
|
||||
serverPatients += newPatients
|
||||
}
|
||||
nextPatientPage = listing.hasNextPage && !newPatients.isEmpty ? page + 1 : nil
|
||||
exactChartOnly = listing.exactChartOnly
|
||||
} catch {
|
||||
guard !Task.isCancelled, search == query, revision == searchRevision else { return }
|
||||
searchError = error.localizedDescription
|
||||
}
|
||||
isSearching = false
|
||||
}
|
||||
|
||||
private func loadServerPatient(_ id: UUID?) async {
|
||||
guard let server, let id, serverChart?.patient.id != id,
|
||||
let summary = serverPatients.first(where: { $0.id == id }) else { return }
|
||||
do {
|
||||
let chart = try await server.chart(summary.chartNumber)
|
||||
try Task.checkCancellation()
|
||||
guard patientID == id else { return }
|
||||
serverChart = chart
|
||||
imageID = chart.patient.images.first?.id
|
||||
detailError = nil
|
||||
} catch {
|
||||
guard !Task.isCancelled, patientID == id else { return }
|
||||
detailError = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
private func emptyState(
|
||||
_ title: String, detail: String, icon: String,
|
||||
@ViewBuilder action: () -> some View = { EmptyView() }
|
||||
@@ -309,9 +468,10 @@ private struct PatientEditorSheet: View {
|
||||
@State private var chartNumber: String
|
||||
@State private var error: String?
|
||||
let isNew: Bool
|
||||
let save: (String, String) throws -> Void
|
||||
@State private var isSaving = false
|
||||
let save: (String, String) async throws -> Void
|
||||
|
||||
init(draft: PatientEditor, save: @escaping (String, String) throws -> Void) {
|
||||
init(draft: PatientEditor, save: @escaping (String, String) async throws -> Void) {
|
||||
_name = State(initialValue: draft.name)
|
||||
_chartNumber = State(initialValue: draft.chartNumber)
|
||||
isNew = draft.patientID == nil
|
||||
@@ -328,17 +488,21 @@ private struct PatientEditorSheet: View {
|
||||
if let error { Text(error).foregroundStyle(.red) }
|
||||
HStack {
|
||||
Spacer()
|
||||
Button("Отмена") { dismiss() }.keyboardShortcut(.cancelAction)
|
||||
Button("Отмена") { dismiss() }.keyboardShortcut(.cancelAction).disabled(isSaving)
|
||||
Button("Сохранить") {
|
||||
do {
|
||||
try save(name, chartNumber)
|
||||
dismiss()
|
||||
} catch {
|
||||
self.error = error.localizedDescription
|
||||
isSaving = true
|
||||
Task {
|
||||
defer { isSaving = false }
|
||||
do {
|
||||
try await save(name, chartNumber)
|
||||
dismiss()
|
||||
} catch {
|
||||
self.error = error.localizedDescription
|
||||
}
|
||||
}
|
||||
}
|
||||
.keyboardShortcut(.defaultAction)
|
||||
.disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||
.disabled(isSaving || name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||
|| chartNumber.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
|
||||
}
|
||||
}
|
||||
@@ -346,3 +510,44 @@ private struct PatientEditorSheet: View {
|
||||
.frame(width: 440)
|
||||
}
|
||||
}
|
||||
|
||||
private struct ServerImagePreview: View {
|
||||
let api: ServerAPI
|
||||
let image: ServerAPI.ServerImage
|
||||
let reportError: (String) -> Void
|
||||
|
||||
@State private var originals: ServerOriginals?
|
||||
@State private var error: String?
|
||||
@State private var retry = 0
|
||||
|
||||
var body: some View {
|
||||
Group {
|
||||
if let originals {
|
||||
if originals.isDICOM {
|
||||
DICOMViewer(urls: originals.urls, name: image.record.name)
|
||||
} else {
|
||||
ImageViewer(image: image.record, url: originals.urls[0], reportError: reportError)
|
||||
}
|
||||
} else if let error {
|
||||
VStack(spacing: 12) {
|
||||
Text(error)
|
||||
Button("Повторить загрузку") { retry += 1 }
|
||||
}
|
||||
} else {
|
||||
ProgressView("Загрузка оригиналов с EzServer…")
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.task(id: retry) {
|
||||
error = nil
|
||||
do {
|
||||
let downloaded = try await api.download(image)
|
||||
try Task.checkCancellation()
|
||||
originals = downloaded
|
||||
} catch {
|
||||
guard !Task.isCancelled else { return }
|
||||
self.error = error.localizedDescription
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
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 {
|
||||
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
|
||||
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)
|
||||
}
|
||||
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 == "IMG" else {
|
||||
throw ServerError.invalidResponse
|
||||
}
|
||||
return ServerImage(strImgFileName: uploaded.updatedFileName, modality: modality,
|
||||
dtAcqTime: ISO8601DateFormatter().string(from: Date()))
|
||||
}
|
||||
|
||||
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, seriesUpload, 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 .seriesUpload: return "Загрузка КТ требует архива .CT и маршрута fs/ctfilesbychartno."
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import CArchive
|
||||
import Foundation
|
||||
|
||||
final class ServerOriginals: @unchecked Sendable {
|
||||
let directory = FileManager.default.temporaryDirectory.appendingPathComponent("EzDent-\(UUID())", isDirectory: true)
|
||||
// Written during the download and read only after it completes.
|
||||
var urls: [URL] = []
|
||||
var isDICOM = false
|
||||
|
||||
init() throws {
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false,
|
||||
attributes: [.posixPermissions: 0o700])
|
||||
}
|
||||
|
||||
deinit { try? FileManager.default.removeItem(at: directory) }
|
||||
|
||||
func unpackCT(at file: URL) throws {
|
||||
guard let archive = archive_read_new() else { throw ServerError.invalidArchive }
|
||||
defer { _ = archive_read_free(archive) }
|
||||
guard archive_read_support_format_zip(archive) == ARCHIVE_OK,
|
||||
archive_read_open_filename(archive, file.path, 64 * 1024) == ARCHIVE_OK else {
|
||||
throw ServerError.invalidArchive
|
||||
}
|
||||
|
||||
var files: [URL] = []
|
||||
var bytesRemaining: Int64 = 2 * 1024 * 1024 * 1024
|
||||
var buffer = Data(count: 64 * 1024)
|
||||
for index in 0..<8192 {
|
||||
try Task.checkCancellation()
|
||||
var entry: OpaquePointer?
|
||||
let status = archive_read_next_header(archive, &entry)
|
||||
if status == ARCHIVE_EOF {
|
||||
guard !files.isEmpty else { throw ServerError.invalidArchive }
|
||||
urls = files
|
||||
isDICOM = true
|
||||
try FileManager.default.removeItem(at: file)
|
||||
return
|
||||
}
|
||||
guard status == ARCHIVE_OK, let entry else { throw ServerError.invalidArchive }
|
||||
guard archive_entry_filetype(entry) == S_IFREG, archive_entry_hardlink(entry) == nil else { continue }
|
||||
guard (0...bytesRemaining).contains(archive_entry_size(entry)), files.count < 4096 else {
|
||||
throw ServerError.invalidArchive
|
||||
}
|
||||
|
||||
// Use our own filenames, so archive paths and link targets are never interpreted.
|
||||
let slice = directory.appendingPathComponent("slice-\(index + 1).dcm")
|
||||
try Data().write(to: slice)
|
||||
let output = try FileHandle(forWritingTo: slice)
|
||||
defer { try? output.close() }
|
||||
while true {
|
||||
try Task.checkCancellation()
|
||||
let bytes = buffer.withUnsafeMutableBytes {
|
||||
archive_read_data(archive, $0.baseAddress, $0.count)
|
||||
}
|
||||
guard bytes >= 0, bytes <= bytesRemaining else { throw ServerError.invalidArchive }
|
||||
if bytes == 0 { break }
|
||||
bytesRemaining -= Int64(bytes)
|
||||
try output.write(contentsOf: buffer.prefix(bytes))
|
||||
}
|
||||
try output.close()
|
||||
if DICOMImage.recognizes(slice) {
|
||||
files.append(slice)
|
||||
} else {
|
||||
try FileManager.default.removeItem(at: slice)
|
||||
}
|
||||
}
|
||||
throw ServerError.invalidArchive
|
||||
}
|
||||
}
|
||||
@@ -1,92 +1,111 @@
|
||||
import Network
|
||||
import SwiftUI
|
||||
|
||||
@MainActor
|
||||
final class ServerConnection: ObservableObject {
|
||||
struct Active {
|
||||
let id = UUID()
|
||||
let api: ServerAPI
|
||||
}
|
||||
|
||||
@Published var active: Active?
|
||||
}
|
||||
|
||||
struct ServerSettings: View {
|
||||
@EnvironmentObject private var connection: ServerConnection
|
||||
@AppStorage("ezServerHost") private var host = ""
|
||||
@AppStorage("ezServerPort") private var port = "43112"
|
||||
@StateObject private var probe = ServerProbe()
|
||||
@AppStorage("ezServerHTTPS") private var https = false
|
||||
@AppStorage("ezServerUsername") private var username = ""
|
||||
@AppStorage("ezServerLoginMethod") private var method = ServerAPI.LoginMethod.r2
|
||||
@State private var password = ""
|
||||
@State private var status: String?
|
||||
@State private var check: Task<Void, Never>?
|
||||
|
||||
private var address: URL? {
|
||||
let hostname = host.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
|
||||
let allowed = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyz0123456789.-")
|
||||
guard !hostname.isEmpty, hostname.unicodeScalars.allSatisfy(allowed.contains),
|
||||
let number = UInt16(port.trimmingCharacters(in: .whitespacesAndNewlines)), number > 0 else { return nil }
|
||||
var components = URLComponents()
|
||||
components.scheme = https ? "https" : "http"
|
||||
components.host = hostname
|
||||
components.port = Int(number)
|
||||
return components.url
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
Form {
|
||||
TextField("Сервер", text: $host, prompt: Text("Имя хоста или IP-адрес"))
|
||||
TextField("Сервер", text: $host, prompt: Text("Имя хоста или IPv4-адрес"))
|
||||
TextField("Порт", text: $port)
|
||||
Button(probe.isChecking ? "Отменить" : "Проверить TCP") {
|
||||
if probe.isChecking {
|
||||
probe.reset()
|
||||
} else {
|
||||
probe.check(host: host, port: port)
|
||||
Toggle("HTTPS", isOn: $https)
|
||||
TextField("Пользователь EzServer", text: $username)
|
||||
SecureField("Пароль", text: $password)
|
||||
Picker("Вход", selection: $method) {
|
||||
ForEach(ServerAPI.LoginMethod.allCases) { method in
|
||||
Text(method.rawValue).tag(method)
|
||||
}
|
||||
}
|
||||
if let status = probe.status {
|
||||
Text(status)
|
||||
if !https {
|
||||
Text("При HTTP JWT и данные передаются без шифрования. Используйте доверенную сеть.")
|
||||
.foregroundStyle(.secondary)
|
||||
.textSelection(.enabled)
|
||||
}
|
||||
HStack {
|
||||
Button(check == nil ? "Подключиться к EzServer" : "Отменить") {
|
||||
if check == nil { connect() } else { cancelCheck() }
|
||||
}
|
||||
if connection.active != nil {
|
||||
Button("Перейти в локальный режим") {
|
||||
cancelCheck()
|
||||
connection.active = nil
|
||||
status = "Локальный режим."
|
||||
}
|
||||
}
|
||||
}
|
||||
if let status { Text(status).foregroundStyle(.secondary) }
|
||||
}
|
||||
.padding(24)
|
||||
.frame(width: 450)
|
||||
.onChange(of: host) { _ in probe.reset() }
|
||||
.onChange(of: port) { _ in probe.reset() }
|
||||
.onDisappear { probe.reset() }
|
||||
.frame(width: 500)
|
||||
.onChange(of: address) { _ in cancelCheck() }
|
||||
.onChange(of: username) { _ in cancelCheck() }
|
||||
.onChange(of: method) { _ in cancelCheck() }
|
||||
.onDisappear {
|
||||
cancelCheck()
|
||||
password = ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private final class ServerProbe: ObservableObject {
|
||||
@Published private(set) var status: String?
|
||||
@Published private(set) var isChecking = false
|
||||
|
||||
private var connection: NWConnection?
|
||||
private var timeout: Task<Void, Never>?
|
||||
|
||||
func check(host: String, port: String) {
|
||||
reset()
|
||||
let host = host.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !host.isEmpty,
|
||||
host.rangeOfCharacter(from: .whitespacesAndNewlines) == nil,
|
||||
!host.contains("/"),
|
||||
let number = UInt16(port.trimmingCharacters(in: .whitespacesAndNewlines)),
|
||||
number > 0, let endpointPort = NWEndpoint.Port(rawValue: number) else {
|
||||
status = "Укажите имя хоста или IP-адрес и порт от 1 до 65535."
|
||||
private func connect() {
|
||||
guard let address else {
|
||||
status = "Укажите имя хоста или IPv4-адрес и порт от 1 до 65535."
|
||||
return
|
||||
}
|
||||
|
||||
let connection = NWConnection(host: NWEndpoint.Host(host), port: endpointPort, using: .tcp)
|
||||
self.connection = connection
|
||||
isChecking = true
|
||||
status = "Подключение…"
|
||||
connection.stateUpdateHandler = { [weak self, weak connection] state in
|
||||
Task { @MainActor in
|
||||
guard let self, let connection, self.connection === connection else { return }
|
||||
switch state {
|
||||
case .ready:
|
||||
self.finish("TCP-порт доступен. Запросы к API не отправлялись.")
|
||||
case let .failed(error), let .waiting(error):
|
||||
self.finish("Подключение не удалось: \(error.localizedDescription)")
|
||||
default:
|
||||
break
|
||||
}
|
||||
let account = username.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !account.isEmpty else {
|
||||
status = "Введите имя пользователя EzServer."
|
||||
return
|
||||
}
|
||||
let secret = password
|
||||
let loginMethod = method
|
||||
status = "Проверка HTTP и вход в EzServer…"
|
||||
check = Task {
|
||||
do {
|
||||
let api = try await ServerAPI.connect(to: address, username: account, password: secret, method: loginMethod)
|
||||
try Task.checkCancellation()
|
||||
connection.active = ServerConnection.Active(api: api)
|
||||
password = ""
|
||||
status = "Подключено к \(address.absoluteString)."
|
||||
} catch {
|
||||
guard !Task.isCancelled else { return }
|
||||
status = error.localizedDescription
|
||||
}
|
||||
check = nil
|
||||
}
|
||||
timeout = Task {
|
||||
try? await Task.sleep(for: .seconds(5))
|
||||
guard !Task.isCancelled else { return }
|
||||
finish("Сервер не ответил за 5 секунд.")
|
||||
}
|
||||
connection.start(queue: .main)
|
||||
}
|
||||
|
||||
func reset() {
|
||||
finish(nil)
|
||||
}
|
||||
|
||||
private func finish(_ message: String?) {
|
||||
timeout?.cancel()
|
||||
timeout = nil
|
||||
connection?.stateUpdateHandler = nil
|
||||
connection?.cancel()
|
||||
connection = nil
|
||||
isChecking = false
|
||||
status = message
|
||||
private func cancelCheck() {
|
||||
guard let check else { return }
|
||||
check.cancel()
|
||||
self.check = nil
|
||||
status = nil
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,8 @@ cp "$gdcm_source/Utilities/gdcmzlib/LICENSE" "$licenses/zlib.txt"
|
||||
codesign --force --sign - "$app/Contents/Helpers/gdcmconv"
|
||||
cp Packaging/Info.plist "$app/Contents/Info.plist"
|
||||
xcrun lipo -create "$arm64_bin/EzDent" "$x86_64_bin/EzDent" -output "$executable"
|
||||
xcrun lipo "$executable" -verify_arch arm64 x86_64
|
||||
xcrun lipo "$executable" -verify_arch arm64
|
||||
xcrun lipo "$executable" -verify_arch x86_64
|
||||
codesign --force --sign - "$app"
|
||||
codesign --verify --deep --strict "$app"
|
||||
|
||||
|
||||
@@ -30,5 +30,6 @@ fi
|
||||
'-DCMAKE_OSX_ARCHITECTURES=arm64;x86_64' -DCMAKE_OSX_DEPLOYMENT_TARGET=13.0 \
|
||||
-DGDCM_BUILD_APPLICATIONS=ON -DGDCM_BUILD_TESTING=OFF -DGDCM_BUILD_SHARED_LIBS=OFF >&2
|
||||
"$cmake" --build "$build" --target gdcmconv --parallel "${EZDENT_BUILD_JOBS:-4}" >&2
|
||||
xcrun lipo "$build/bin/gdcmconv" -verify_arch arm64 x86_64
|
||||
xcrun lipo "$build/bin/gdcmconv" -verify_arch arm64
|
||||
xcrun lipo "$build/bin/gdcmconv" -verify_arch x86_64
|
||||
printf '%s\n' "$build/bin/gdcmconv"
|
||||
Reference in new issue
Block a user