Build native EzServer menu app with SQLite and file storage
This commit is contained in:
1 parent
cf192a5f3c
commit
9298382abe
11 files changed
+1280
-297
No files matched your search
@@ -0,0 +1,349 @@
|
||||
import AppKit
|
||||
import EzDentStorage
|
||||
import ServiceManagement
|
||||
import SwiftUI
|
||||
|
||||
@MainActor
|
||||
struct MenuBarServer: App {
|
||||
@StateObject private var model = ServerControl()
|
||||
|
||||
var body: some Scene {
|
||||
MenuBarExtra {
|
||||
ServerPanel(model: model)
|
||||
} label: {
|
||||
Label("EzServer", systemImage: model.running ? "externaldrive.fill.badge.checkmark" : "externaldrive")
|
||||
}
|
||||
.menuBarExtraStyle(.window)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private final class ServerControl: ObservableObject {
|
||||
@Published var running = false
|
||||
@Published var starting = false
|
||||
@Published var port = "55005"
|
||||
@Published var progress = false
|
||||
@Published var notice: String?
|
||||
@Published var patients: [PatientRecord] = []
|
||||
@Published var selection: UUID? {
|
||||
didSet { refreshFiles() }
|
||||
}
|
||||
@Published var images: [PatientImage] = []
|
||||
@Published var loginStatus = SMAppService.mainApp.status
|
||||
@Published var name = ""
|
||||
@Published var chart = ""
|
||||
|
||||
private var configuration: ServerConfiguration?
|
||||
private var server: LocalServer?
|
||||
private var generation = UUID()
|
||||
|
||||
init() {
|
||||
do {
|
||||
let configuration = try ServerConfiguration()
|
||||
self.configuration = configuration
|
||||
port = UserDefaults.standard.string(forKey: "listenPort") ?? String(configuration.port)
|
||||
refreshPatients()
|
||||
start()
|
||||
} catch {
|
||||
notice = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
var dataPath: String { configuration?.store.directory.path ?? "" }
|
||||
|
||||
func start() {
|
||||
guard server == nil, let configuration else { return }
|
||||
guard let portValue = UInt16(port), portValue > 0 else {
|
||||
notice = "Укажите порт от 1 до 65535."
|
||||
return
|
||||
}
|
||||
do {
|
||||
let api = LibraryAPI(store: configuration.store, secret: configuration.token)
|
||||
let server = try LocalServer(port: portValue, library: api)
|
||||
self.server = server
|
||||
starting = true
|
||||
notice = nil
|
||||
generation = UUID()
|
||||
let generation = self.generation
|
||||
server.start { [weak self] result in
|
||||
Task { @MainActor in
|
||||
guard let self, self.generation == generation else { return }
|
||||
self.starting = false
|
||||
switch result {
|
||||
case .success:
|
||||
self.running = true
|
||||
UserDefaults.standard.set(String(portValue), forKey: "listenPort")
|
||||
case let .failure(error):
|
||||
self.stop()
|
||||
self.notice = error.localizedDescription
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
notice = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
func stop() {
|
||||
generation = UUID()
|
||||
server?.stop()
|
||||
server = nil
|
||||
starting = false
|
||||
running = false
|
||||
}
|
||||
|
||||
func refreshPatients() {
|
||||
guard let store = configuration?.store else { return }
|
||||
do {
|
||||
patients = try store.patients()
|
||||
if selection == nil || !patients.contains(where: { $0.id == selection }) {
|
||||
selection = patients.first?.id
|
||||
} else {
|
||||
refreshFiles()
|
||||
}
|
||||
} catch {
|
||||
notice = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
private func refreshFiles() {
|
||||
do {
|
||||
images = try selection.flatMap { try configuration?.store.patient($0)?.images } ?? []
|
||||
} catch {
|
||||
images = []
|
||||
notice = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
func addPatient() {
|
||||
guard let store = configuration?.store else { return }
|
||||
do {
|
||||
let patient = try store.createPatient(name: name, chartNumber: chart)
|
||||
name = ""
|
||||
chart = ""
|
||||
refreshPatients()
|
||||
selection = patient.id
|
||||
} catch {
|
||||
notice = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
func importLibrary() {
|
||||
guard let store = configuration?.store else { return }
|
||||
let panel = NSOpenPanel()
|
||||
panel.canChooseFiles = false
|
||||
panel.canChooseDirectories = true
|
||||
panel.message = "Выберите папку библиотеки EzDent с файлом patients.json."
|
||||
guard panel.runModal() == .OK, let url = panel.url else { return }
|
||||
progress = true
|
||||
Task {
|
||||
defer { progress = false }
|
||||
do {
|
||||
let count = try await Task.detached { try store.importLibrary(url) }.value
|
||||
refreshPatients()
|
||||
notice = "Импортировано новых карточек: \(count)."
|
||||
} catch {
|
||||
notice = error.localizedDescription
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func addFiles() {
|
||||
guard let store = configuration?.store, let patient = selection else { return }
|
||||
let panel = NSOpenPanel()
|
||||
panel.allowsMultipleSelection = true
|
||||
guard panel.runModal() == .OK else { return }
|
||||
let urls = panel.urls
|
||||
progress = true
|
||||
Task {
|
||||
defer { progress = false; refreshPatients() }
|
||||
let failures = await Task.detached {
|
||||
urls.compactMap { url -> String? in
|
||||
do {
|
||||
let dicom = ["dcm", "dicom"].contains(url.pathExtension.lowercased())
|
||||
_ = try store.addFile(from: url.resolvingSymlinksInPath(), patient: patient,
|
||||
imageID: UUID(), name: url.lastPathComponent, dicom: dicom)
|
||||
return nil
|
||||
} catch {
|
||||
return "\(url.lastPathComponent): \(error.localizedDescription)"
|
||||
}
|
||||
}
|
||||
}.value
|
||||
notice = failures.isEmpty ? "Файлы добавлены." : failures.joined(separator: "\n")
|
||||
}
|
||||
}
|
||||
|
||||
func exportFile(_ image: PatientImage) {
|
||||
guard let store = configuration?.store else { return }
|
||||
let source: URL
|
||||
let isDirectory: Bool
|
||||
if image.dicomCount == 1 {
|
||||
source = store.slice(1, of: image.id)
|
||||
isDirectory = false
|
||||
} else {
|
||||
source = store.attachment(image.id)
|
||||
isDirectory = image.dicomCount != nil
|
||||
}
|
||||
let panel = NSSavePanel()
|
||||
panel.nameFieldStringValue = image.name
|
||||
guard panel.runModal() == .OK, let target = panel.url else { return }
|
||||
do {
|
||||
if isDirectory {
|
||||
try FileManager.default.copyItem(at: source, to: target)
|
||||
} else {
|
||||
try Data(contentsOf: source, options: .mappedIfSafe).write(to: target, options: .atomic)
|
||||
}
|
||||
notice = "Оригинал экспортирован."
|
||||
} catch {
|
||||
notice = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
func deleteFile(_ image: PatientImage) {
|
||||
guard let store = configuration?.store, let patient = selection else { return }
|
||||
do {
|
||||
try store.deleteFile(patient: patient, imageID: image.id)
|
||||
refreshFiles()
|
||||
} catch {
|
||||
notice = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
func openStorage() {
|
||||
guard let directory = configuration?.store.directory else { return }
|
||||
NSWorkspace.shared.activateFileViewerSelecting([directory])
|
||||
}
|
||||
|
||||
func copyToken() {
|
||||
guard let token = configuration?.token else { return }
|
||||
NSPasteboard.general.clearContents()
|
||||
NSPasteboard.general.setString(token, forType: .string)
|
||||
notice = "Токен скопирован."
|
||||
}
|
||||
|
||||
func toggleLogin() {
|
||||
do {
|
||||
if loginStatus == .enabled || loginStatus == .requiresApproval {
|
||||
try SMAppService.mainApp.unregister()
|
||||
} else {
|
||||
try SMAppService.mainApp.register()
|
||||
}
|
||||
loginStatus = SMAppService.mainApp.status
|
||||
if loginStatus == .requiresApproval { SMAppService.openSystemSettingsLoginItems() }
|
||||
} catch {
|
||||
notice = error.localizedDescription
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct ServerPanel: View {
|
||||
@ObservedObject var model: ServerControl
|
||||
@State private var showNewPatient = false
|
||||
@State private var pendingDelete: PatientImage?
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
HStack {
|
||||
Label("EzServer", systemImage: "externaldrive")
|
||||
.font(.title3.weight(.semibold))
|
||||
Spacer()
|
||||
Text(model.starting ? "Запуск…" : model.running ? "Работает" : "Остановлен")
|
||||
.foregroundStyle(model.running ? Color.green : Color.secondary)
|
||||
}
|
||||
HStack {
|
||||
Text("Порт")
|
||||
TextField("55005", text: $model.port)
|
||||
.frame(width: 75)
|
||||
.disabled(model.running || model.starting)
|
||||
.accessibilityLabel("Порт HTTP")
|
||||
if model.running { Text("127.0.0.1:\(model.port)").font(.caption).textSelection(.enabled) }
|
||||
Spacer()
|
||||
Button(model.running || model.starting ? "Остановить" : "Запустить") {
|
||||
if model.running || model.starting { model.stop() } else { model.start() }
|
||||
}
|
||||
.disabled(model.dataPath.isEmpty)
|
||||
}
|
||||
Divider()
|
||||
HStack {
|
||||
Label("SQLite", systemImage: "cylinder")
|
||||
Spacer()
|
||||
Button("Хранилище в Finder", action: model.openStorage)
|
||||
Button("Скопировать токен", action: model.copyToken)
|
||||
}
|
||||
|
||||
HStack {
|
||||
Picker("Пациент", selection: $model.selection) {
|
||||
if model.patients.isEmpty { Text("Карточек пока нет").tag(nil as UUID?) }
|
||||
ForEach(model.patients) { patient in
|
||||
Text("\(patient.name) · \(patient.chartNumber)").tag(Optional(patient.id))
|
||||
}
|
||||
}
|
||||
Button { showNewPatient.toggle() } label: { Image(systemName: "person.badge.plus") }
|
||||
.help("Новый пациент")
|
||||
.disabled(model.progress)
|
||||
Button { model.addFiles() } label: { Image(systemName: "plus") }
|
||||
.help("Добавить файлы")
|
||||
.disabled(model.selection == nil || model.progress)
|
||||
}
|
||||
if showNewPatient {
|
||||
HStack {
|
||||
TextField("Имя", text: $model.name)
|
||||
TextField("Номер карты", text: $model.chart)
|
||||
Button("Создать", action: model.addPatient)
|
||||
.disabled(model.name.isEmpty || model.chart.isEmpty)
|
||||
}
|
||||
}
|
||||
if model.images.isEmpty {
|
||||
Text("Файлов пока нет").foregroundStyle(.secondary)
|
||||
} else {
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
ForEach(model.images) { image in
|
||||
HStack {
|
||||
Image(systemName: image.dicomCount == nil ? "doc" : "square.stack.3d.up")
|
||||
Text(image.name).lineLimit(1)
|
||||
Spacer()
|
||||
Menu {
|
||||
Button("Экспорт оригинала…") { model.exportFile(image) }
|
||||
Button("Удалить…", role: .destructive) { pendingDelete = image }
|
||||
} label: { Image(systemName: "ellipsis.circle") }
|
||||
.menuStyle(.borderlessButton)
|
||||
.fixedSize()
|
||||
.accessibilityLabel("Действия с файлом \(image.name)")
|
||||
}
|
||||
}
|
||||
}
|
||||
}.frame(maxHeight: 144)
|
||||
}
|
||||
if let notice = model.notice {
|
||||
Text(notice).font(.caption).foregroundStyle(.secondary).textSelection(.enabled)
|
||||
}
|
||||
Divider()
|
||||
HStack {
|
||||
Button("Импорт EzDent…", action: model.importLibrary).disabled(model.progress)
|
||||
Button("Обновить", action: model.refreshPatients)
|
||||
if model.progress { ProgressView().controlSize(.small) }
|
||||
Spacer()
|
||||
Toggle("При входе", isOn: Binding(
|
||||
get: { model.loginStatus == .enabled || model.loginStatus == .requiresApproval },
|
||||
set: { _ in model.toggleLogin() }
|
||||
)).toggleStyle(.checkbox)
|
||||
Button("Выйти") {
|
||||
model.stop()
|
||||
NSApplication.shared.terminate(nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(16)
|
||||
.frame(width: 470)
|
||||
.confirmationDialog("Удалить файл из хранилища?", isPresented: Binding(
|
||||
get: { pendingDelete != nil },
|
||||
set: { if !$0 { pendingDelete = nil } }
|
||||
), titleVisibility: .visible, presenting: pendingDelete) { image in
|
||||
Button("Удалить", role: .destructive) {
|
||||
model.deleteFile(image)
|
||||
pendingDelete = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user