Simplify EzServer menu and serve original Web Console

This commit is contained in:
SantaSpeen committed 2026-11-22 03:12:27 +03:00
1 parent ee7e18490f
commit d748f7cc69
16 files changed
+290 -245

No files matched your search

+31 -1
View File
@@ -1,5 +1,6 @@
import Foundation
import Network
import UniformTypeIdentifiers
private struct APIVersion: Encodable {
let name: String
@@ -67,11 +68,12 @@ final class LocalServer {
listener.start(queue: queue)
}
func stop() {
func stop(completion: (() -> Void)? = nil) {
queue.async { [self] in
listener.cancel()
connections.values.forEach { $0.cancel() }
connections.removeAll()
completion?()
}
}
@@ -137,6 +139,11 @@ final class LocalServer {
return
}
if target.path == "/webconsole" || target.path.hasPrefix("/webconsole/") {
serveWebConsole(path: segments, on: connection)
return
}
let apiURL = "http://\(hosts[0])/api/v1"
let versions = [
"1.0.0", "1.0.1", "1.1.0", "1.2.0", "1.3.0", "1.3.1", "1.3.2", "2.0.0",
@@ -170,6 +177,29 @@ final class LocalServer {
}
}
private func serveWebConsole(path: [String], on connection: NWConnection) {
guard let root = Bundle.main.resourceURL?.appendingPathComponent("webconsole", isDirectory: true)
.resolvingSymlinksInPath() else {
send(["error": "Web Console assets are unavailable"], status: "404 Not Found", on: connection)
return
}
let components = path.count == 1 ? ["index.html"] : Array(path.dropFirst())
let file = components.reduce(root) { $0.appendingPathComponent($1) }.resolvingSymlinksInPath()
guard file.path.hasPrefix(root.path + "/"),
let metadata = try? file.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey]),
metadata.isRegularFile == true, let bytes = metadata.fileSize,
let handle = try? FileHandle(forReadingFrom: file) else {
send(["error": "Web Console asset not found"], status: "404 Not Found", on: connection)
return
}
let type = UTType(filenameExtension: file.pathExtension)?.preferredMIMEType ?? "application/octet-stream"
let headers = responseHeaders(status: "200 OK", type: type, bytes: bytes, extra: "")
connection.send(content: headers, completion: .contentProcessed { [weak self] error in
guard let self, error == nil else { connection.cancel(); return }
self.stream(handle, remaining: bytes, on: connection)
})
}
private func serveLibrary(path: [String], query: [URLQueryItem], authorization: String?,
on connection: NWConnection) {
switch library.response(path: path, query: query, authorization: authorization) {
+50 -229
View File
@@ -1,6 +1,4 @@
import AppKit
import EzDentStorage
import ServiceManagement
import SwiftUI
@MainActor
@@ -21,17 +19,10 @@ struct MenuBarServer: App {
private final class ServerControl: ObservableObject {
@Published var running = false
@Published var starting = false
@Published var stopping = false
@Published var copying = 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?
@@ -42,17 +33,20 @@ private final class ServerControl: ObservableObject {
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 ?? "" }
var imagesPath: String { configuration?.store.files.path ?? "" }
var canChangeImages: Bool {
!running && !starting && !stopping && !copying
&& ProcessInfo.processInfo.environment["EZSERVER_IMAGES_PARENT"] == nil
}
func start() {
guard server == nil, let configuration else { return }
guard server == nil, !stopping, !copying, let configuration else { return }
guard let portValue = UInt16(port), portValue > 0 else {
notice = "Укажите порт от 1 до 65535."
return
@@ -85,265 +79,92 @@ private final class ServerControl: ObservableObject {
}
func stop() {
guard let server, !stopping else { return }
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()
stopping = true
server.stop { [weak self] in
Task { @MainActor in
self?.server = nil
self?.stopping = false
}
} 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 }
func chooseImagesFolder() {
guard canChangeImages, let configuration else { return }
let panel = NSOpenPanel()
panel.canChooseFiles = false
panel.canChooseDirectories = true
panel.message = "Выберите папку библиотеки EzDent с файлом patients.json."
panel.canCreateDirectories = true
panel.message = "Выберите папку, в которой EzServer создаст каталог Files."
guard panel.runModal() == .OK, let url = panel.url else { return }
progress = true
let parent = url.resolvingSymlinksInPath().standardizedFileURL
guard parent.path != configuration.store.files.deletingLastPathComponent().path else { return }
guard !parent.path.hasPrefix(configuration.store.files.path + "/"),
parent.path != configuration.store.files.path else {
notice = "Выберите папку вне текущего каталога Files."
return
}
copying = true
notice = nil
Task {
defer { progress = false }
defer { copying = false }
do {
let count = try await Task.detached { try store.importLibrary(url) }.value
refreshPatients()
notice = "Импортировано новых карточек: \(count)."
let store = configuration.store
try await Task.detached { try store.copyImages(to: parent) }.value
self.configuration = try ServerConfiguration(imagesParent: parent)
UserDefaults.standard.set(parent.path, forKey: "imagesParent")
notice = "Снимки скопированы. Прежняя папка сохранена."
} 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
}
func openConsole() {
guard running, let port = UInt16(port),
let url = URL(string: "http://127.0.0.1:\(port)/webconsole") else { return }
NSWorkspace.shared.open(url)
}
}
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)
.disabled(model.running || model.starting || model.stopping)
.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)
.disabled(model.imagesPath.isEmpty || model.stopping || model.copying)
}
Divider()
HStack {
Label("SQLite", systemImage: "cylinder")
Text("Папка снимков")
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)
Button("Выбрать…", action: model.chooseImagesFolder)
.disabled(!model.canChangeImages || model.imagesPath.isEmpty)
}
Text(model.imagesPath)
.font(.caption)
.foregroundStyle(.secondary)
.textSelection(.enabled)
if model.copying { ProgressView("Копирование снимков…").controlSize(.small) }
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)
}
}
Button("Открыть Web Console", action: model.openConsole)
.disabled(!model.running)
}
.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
}
}
.frame(width: 360)
}
}
+17 -3
View File
@@ -6,7 +6,7 @@ struct ServerConfiguration {
let token: String
let port: UInt16
init(environment: [String: String] = ProcessInfo.processInfo.environment) throws {
init(environment: [String: String] = ProcessInfo.processInfo.environment, imagesParent: URL? = nil) throws {
let rawPort = environment["EZSERVER_PORT"] ?? "55005"
guard let port = UInt16(rawPort), port > 0 else { throw Failure.invalidPort }
self.port = port
@@ -17,7 +17,20 @@ struct ServerConfiguration {
} else {
directory = URL.applicationSupportDirectory.appendingPathComponent("EzServerMac", isDirectory: true)
}
store = try ServerStore(directory: directory.resolvingSymlinksInPath())
let imageStorage: URL?
if let path = environment["EZSERVER_IMAGES_PARENT"] {
guard path.hasPrefix("/") else { throw Failure.invalidImageDirectory }
imageStorage = URL(fileURLWithPath: path, isDirectory: true)
} else if let imagesParent {
imageStorage = imagesParent
} else if environment["EZSERVER_DATA"] == nil,
let saved = UserDefaults.standard.string(forKey: "imagesParent") {
imageStorage = URL(fileURLWithPath: saved, isDirectory: true)
} else {
imageStorage = nil
}
store = try ServerStore(directory: directory.resolvingSymlinksInPath(),
imagesParent: imageStorage?.resolvingSymlinksInPath())
if let configured = environment["EZSERVER_TOKEN"] {
guard Self.valid(configured) else { throw Failure.invalidToken }
@@ -63,11 +76,12 @@ struct ServerConfiguration {
}
private enum Failure: LocalizedError {
case invalidPort, invalidDirectory, invalidToken
case invalidPort, invalidDirectory, invalidImageDirectory, invalidToken
var errorDescription: String? {
switch self {
case .invalidPort: return "EZSERVER_PORT должен быть числом от 1 до 65535."
case .invalidDirectory: return "Укажите абсолютный путь в EZSERVER_DATA."
case .invalidImageDirectory: return "Укажите абсолютный путь в EZSERVER_IMAGES_PARENT."
case .invalidToken: return "Токен должен содержать от 32 до 1024 печатных ASCII-символов."
}
}
+21 -4
View File
@@ -5,17 +5,18 @@ import SQLite3
final class ServerStore {
let directory: URL
let database: URL
private let files: URL
let files: URL
private let pendingDeletes: URL
private let db: OpaquePointer
private let lock = NSRecursiveLock()
private static let transient = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
init(directory: URL) throws {
init(directory: URL, imagesParent: URL? = nil) throws {
self.directory = directory
database = directory.appendingPathComponent("EzServer.sqlite3")
files = directory.appendingPathComponent("Files", isDirectory: true)
pendingDeletes = directory.appendingPathComponent("PendingDeletion", isDirectory: true)
let storage = imagesParent ?? directory
files = storage.appendingPathComponent("Files", isDirectory: true)
pendingDeletes = storage.appendingPathComponent("PendingDeletion", isDirectory: true)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true,
attributes: [.posixPermissions: 0o700])
try FileManager.default.createDirectory(at: files, withIntermediateDirectories: true,
@@ -60,6 +61,22 @@ final class ServerStore {
deinit { sqlite3_close(db) }
func copyImages(to parent: URL) throws {
lock.lock()
defer { lock.unlock() }
guard parent != files.deletingLastPathComponent() else { return }
let destination = parent.appendingPathComponent("Files", isDirectory: true)
let manager = FileManager.default
guard !manager.fileExists(atPath: destination.path),
!manager.fileExists(atPath: parent.appendingPathComponent("PendingDeletion").path) else {
throw CocoaError(.fileWriteFileExists, userInfo: [NSFilePathErrorKey: destination.path])
}
let stage = parent.appendingPathComponent(".EzServer-\(UUID().uuidString)", isDirectory: true)
defer { try? manager.removeItem(at: stage) }
try manager.copyItem(at: files, to: stage)
try manager.moveItem(at: stage, to: destination)
}
func patients() throws -> [PatientRecord] {
lock.lock()
defer { lock.unlock() }