Simplify EzServer menu and serve original Web Console
This commit is contained in:
1 parent
ee7e18490f
commit
d748f7cc69
16 files changed
+290
-245
No files matched your search
@@ -2,13 +2,15 @@
|
||||
|
||||
Нативный сервер для macOS 13 и новее, Intel и Apple Silicon. Распакуйте `EzServerMac-universal.zip`, переместите `EzServer.app` в «Программы» и откройте приложение. В строке меню появится значок диска. HTTP-служба запускается при открытии приложения и по умолчанию слушает `127.0.0.1:55005`.
|
||||
|
||||
Из панели можно остановить службу, изменить порт и запустить её снова, включить запуск при входе в macOS, открыть хранилище, скопировать токен, создать карточку, добавить файлы, экспортировать оригиналы и удалить вложение. Данные пациентов и индекс файлов хранятся в SQLite, а оригиналы — в отдельной папке `Files` внутри серверного хранилища. По умолчанию это `~/Library/Application Support/EzServerMac`.
|
||||
В строке меню доступны запуск и остановка, выбор порта, выбор папки снимков и кнопка для открытия `/webconsole`. Путь и порт меняются при остановленной службе. При выборе папки EzServer копирует снимки в новый подкаталог `Files` и сохраняет прежнюю копию. По умолчанию SQLite и снимки находятся в `~/Library/Application Support/EzServerMac`. Для командной строки отдельную папку снимков можно задать абсолютным путём в `EZSERVER_IMAGES_PARENT`.
|
||||
|
||||
Оригинальная Web Console извлекается из `webapps/webconsole` установщика. Её HTML, JavaScript и CSS входят в сборку, если ресурсы подготовлены через `server/prepare.sh`. Консоль оригинала использует PHP API для входа и настроек сервера. Эти операции ещё требуют переноса, поэтому доступна загрузка самой консоли.
|
||||
|
||||
## Импорт из EzDent
|
||||
|
||||
Нажмите «Импорт EzDent…» и выберите папку с `patients.json`. Для локального EzDent это обычно `~/Library/Application Support/EzDent/Library`. Сервер копирует карточки и оригиналы в своё хранилище. Повторный импорт добавляет отсутствующие карточки и вложения. При конфликте номера карты импорт откатывается. После импорта SQLite является источником данных сервера.
|
||||
Остановите сервер и запустите `EzServerMac --import-library /абсолютный/путь`, указав каталог с `patients.json`. Для локального EzDent это обычно `~/Library/Application Support/EzDent/Library`. Сервер копирует карточки и оригиналы в своё хранилище. Повторный импорт добавляет отсутствующие карточки и вложения. При конфликте номера карты импорт откатывается. После импорта SQLite является источником данных сервера.
|
||||
|
||||
Чтобы сделать копию хранилища, завершите EzServer и скопируйте серверный каталог целиком. При восстановлении копируйте каталог при остановленном сервере.
|
||||
Чтобы сделать копию хранилища, завершите EzServer и скопируйте серверный каталог и отдельную папку снимков, если она настроена. При восстановлении копируйте каталог при остановленном сервере.
|
||||
|
||||
## Командная строка
|
||||
|
||||
@@ -47,3 +49,12 @@
|
||||
## Сборка
|
||||
|
||||
`./scripts/build-server.sh` создаёт `dist/EzServer.app` и `dist/EzServerMac-universal.zip`. Нужны Swift 5.9+ и Xcode Command Line Tools.
|
||||
|
||||
### Чтение карточки через оригинальный PHP
|
||||
|
||||
Для тестирования `GET /api/v1/e2ds/patientsByChartNo?chartno=…` задайте два абсолютных пути перед запуском `server/run.sh`:
|
||||
|
||||
- `EZSERVER_SQLITE` — отдельный файл SQLite для PHP. При первом запуске создаётся таблица `e2_pat`. Старое хранилище Swift несовместимо с этой схемой и отклоняется.
|
||||
- `EZSERVER_JWT_KEY_FILE` — локальный файл с ключом подписи HS256 длиной от 32 байт. Оригинальный контроллер проверяет Bearer JWT. Выдача JWT через пользовательский вход и импорт карточек в эту базу пока не реализованы.
|
||||
|
||||
Маршрут проверен на тестовой карточке, заранее добавленной в SQLite. Приложение в строке меню продолжает работать на Swift.
|
||||
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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-символов."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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() }
|
||||
|
||||
+3
-2
@@ -14,7 +14,7 @@
|
||||
|
||||
## Что работает сейчас
|
||||
|
||||
- Swift-приложение в строке меню управляет локальным HTTP-сервером, портом и запуском при входе. По умолчанию сервер слушает `127.0.0.1:55005`.
|
||||
- В строке меню предусмотрены только запуск/остановка, порт, выбор папки снимков и кнопка `/webconsole`. При смене папки снимки копируются в новый каталог `Files`. Импорт доступен через CLI. По умолчанию сервер слушает `127.0.0.1:55005`.
|
||||
- Swift-сервер хранит метаданные в SQLite, оригиналы в `Files`, поддерживает импорт библиотеки EzDent, создание карточек и загрузку, экспорт и удаление вложений. API `/mac/v1` использует Bearer-токен. Каталог данных по умолчанию — `~/Library/Application Support/EzServerMac`. Панель, тестовый импорт и побайтовая выдача оригинала после перезапуска уже проверены.
|
||||
- `server/run.sh` и `server/router.php` — отдельный запуск извлечённого PHP через nginx и PHP-FPM на Unix-сокете для информационных маршрутов. На Apple Silicon с PHP 8.6 оба маршрута версий вернули 3.0.6 через nginx и PHP-FPM. Оригинальный PHP также вернул `Pong` по `/api/v1/auth/ping` и `/api/index.php/v1/auth/ping`. Оригинальный PHP пишет предупреждение об устаревшем E_STRICT. Авторизация оригинала и перенос его схемы в SQLite ещё не проверены сквозным тестом. EzDent Mac пока проверяет TCP-подключение и открывает локальную библиотеку.
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
|
||||
Относительно извлечённого `www/ezwebserver/src`:
|
||||
|
||||
- Оригинальные статические ресурсы Web Console находятся в `webapps/webconsole` установщика. Они используют API входа и настроек.
|
||||
- `public/api/index.php` — точка входа, `application/config/routes.php` — маршруты. Версия API в комплекте — 3.0.6.
|
||||
- `application/controllers/v1/E2Ds.php` — оригинальные операции с карточками, включая `POST /api/v1/e2ds/patients` с полем `strChartNo` и `GET /api/v1/e2ds/patientsByChartNo?chartno=…`.
|
||||
- `application/config/database.php` — конфигурация групп БД. В `vendor/codeigniter/framework/system/database/drivers/` есть драйверы SQLite3 и PDO SQLite. При переносе проверить модели пациентов и групп данных на PostgreSQL-специфичные запросы. Схема текущего Swift-хранилища и схема оригинала требуют отдельного сопоставления.
|
||||
@@ -31,4 +32,4 @@
|
||||
|
||||
## Следующая техническая проверка
|
||||
|
||||
Адаптировать схему и конфигурацию SQLite, затем проверить на тестовых данных вход, чтение карточки и выдачу оригинала файла через PHP. Текущие маршруты Swift описаны в README.
|
||||
Проверен оригинальный PHP GET карточки по номеру через отдельную SQLite с таблицей `e2_pat` и оригинальной проверкой JWT с локальным ключом. См. README для параметров запуска. Следующие шаги — выдача JWT через оригинальный вход, запись и поиск карточек, перенос файловых моделей и запуск из меню приложения. Текущие маршруты Swift описаны в README.
|
||||
@@ -22,6 +22,10 @@ xcrun lipo -create "$arm64_bin/EzServerMac" "$x86_64_bin/EzServerMac" -output "$
|
||||
xcrun lipo "$binary" -verify_arch arm64 x86_64
|
||||
cp Packaging/Info.plist "$app/Contents/Info.plist"
|
||||
cp README.md "$app/Contents/Resources/README.md"
|
||||
runtime="${EZSERVER_RUNTIME:-$PWD/.build/ezserver-macos/runtime}"
|
||||
if [[ -f "$runtime/webconsole/index.html" ]]; then
|
||||
ditto "$runtime/webconsole" "$app/Contents/Resources/webconsole"
|
||||
fi
|
||||
codesign --force --sign - "$app"
|
||||
codesign --verify --deep --strict "$app"
|
||||
ditto -c -k --keepParent "$app" "$stage/EzServerMac-universal.zip"
|
||||
|
||||
@@ -55,7 +55,10 @@ def stage_web_service(extracted, runtime):
|
||||
)
|
||||
for name in ("application/cache/sessions", "application/logs"):
|
||||
(destination / name).mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(extracted / "webapps" / "index.html", runtime / "index.html")
|
||||
webapps = extracted / "webapps"
|
||||
shutil.copy2(webapps / "index.html", runtime / "index.html")
|
||||
shutil.copytree(webapps / "webconsole", runtime / "webconsole",
|
||||
ignore=shutil.ignore_patterns("*.map"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
// Initialize the original PHP API database. The Swift database uses a separate schema.
|
||||
if (PHP_SAPI !== 'cli' || $argc !== 2) {
|
||||
exit(1);
|
||||
}
|
||||
|
||||
umask(0077);
|
||||
try {
|
||||
$db = new PDO('sqlite:' . $argv[1], null, null, [PDO::ATTR_TIMEOUT => 5]);
|
||||
$db->exec('BEGIN IMMEDIATE');
|
||||
$applicationId = (int) $db->query('PRAGMA application_id')->fetchColumn();
|
||||
$version = (int) $db->query('PRAGMA user_version')->fetchColumn();
|
||||
// "EZSV" in SQLite's application header.
|
||||
if ($applicationId === 1163547478 && $version === 1) {
|
||||
$db->exec('COMMIT');
|
||||
exit(0);
|
||||
}
|
||||
$objects = (int) $db->query("SELECT count(*) FROM sqlite_schema WHERE name NOT GLOB 'sqlite_*'")->fetchColumn();
|
||||
if ($applicationId !== 0 || $version !== 0 || $objects !== 0) {
|
||||
throw new RuntimeException('Expected a new database or an EzServer PHP database at schema version 1.');
|
||||
}
|
||||
$schema = file_get_contents(__DIR__ . '/patients.sqlite.sql');
|
||||
if ($schema === false) {
|
||||
throw new RuntimeException('Could not read the patient schema.');
|
||||
}
|
||||
$db->exec($schema);
|
||||
$db->exec('PRAGMA application_id = 1163547478');
|
||||
$db->exec('PRAGMA user_version = 1');
|
||||
$db->exec('COMMIT');
|
||||
} catch (Throwable $error) {
|
||||
// SQLite rolls back an open transaction when the connection closes.
|
||||
fwrite(STDERR, 'SQLite initialization failed: ' . $error->getMessage() . PHP_EOL);
|
||||
exit(1);
|
||||
}
|
||||
@@ -12,6 +12,26 @@ http {
|
||||
server_tokens off;
|
||||
server {
|
||||
listen 127.0.0.1:@PORT@;
|
||||
if ($http_host !~* "^(127\.0\.0\.1|localhost)(:[0-9]{1,5})?$") {
|
||||
return 400;
|
||||
}
|
||||
location = /webconsole {
|
||||
return 302 /webconsole/;
|
||||
}
|
||||
location ^~ /webconsole/ {
|
||||
root @STAGE@;
|
||||
index index.html;
|
||||
types {
|
||||
text/html html;
|
||||
text/css css;
|
||||
application/javascript js;
|
||||
application/json json;
|
||||
image/x-icon ico;
|
||||
image/png png;
|
||||
text/plain txt;
|
||||
}
|
||||
try_files $uri $uri/ =404;
|
||||
}
|
||||
location / {
|
||||
fastcgi_param SCRIPT_FILENAME @STAGE@/router.php;
|
||||
fastcgi_param SCRIPT_NAME /router.php;
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
CREATE TABLE e2_pat (
|
||||
pat_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
pat_chartno TEXT NOT NULL UNIQUE,
|
||||
pat_lastname TEXT,
|
||||
pat_firstname TEXT,
|
||||
pat_middlename TEXT,
|
||||
pat_gender TEXT,
|
||||
pat_birthdate TEXT,
|
||||
pat_email TEXT,
|
||||
pat_socialid TEXT,
|
||||
pat_registered_datetime TEXT,
|
||||
pat_photo_filename TEXT,
|
||||
pat_chosung TEXT,
|
||||
pat_note TEXT,
|
||||
pat_phone TEXT,
|
||||
pat_zipcode TEXT,
|
||||
pat_address TEXT,
|
||||
pat_mobile TEXT,
|
||||
pat_source_type TEXT DEFAULT 'Unknown',
|
||||
pat_source_id TEXT,
|
||||
pat_last_access TEXT,
|
||||
pat_user_defined_1 INTEGER,
|
||||
pat_user_defined_2 INTEGER,
|
||||
pat_user_defined_3 REAL,
|
||||
pat_user_defined_4 REAL,
|
||||
pat_user_defined_5 INTEGER,
|
||||
pat_user_defined_6 INTEGER,
|
||||
pat_user_defined_7 TEXT,
|
||||
pat_user_defined_8 TEXT,
|
||||
pat_user_defined_9 TEXT,
|
||||
pat_user_defined_10 BLOB,
|
||||
pat_job TEXT,
|
||||
oth_race_id INTEGER,
|
||||
oth_class_id INTEGER,
|
||||
pat_last_updated TEXT
|
||||
);
|
||||
@@ -7,6 +7,8 @@ listen.mode = 0600
|
||||
pm = ondemand
|
||||
pm.max_children = 2
|
||||
env[EZSERVER_RUNTIME] = $EZSERVER_RUNTIME
|
||||
env[EZSERVER_SQLITE] = $EZSERVER_SQLITE
|
||||
env[EZSERVER_JWT_KEY_FILE] = $EZSERVER_JWT_KEY_FILE
|
||||
php_admin_flag[display_errors] = off
|
||||
php_admin_flag[expose_php] = off
|
||||
php_admin_value[session.save_path] = @STAGE@
|
||||
+4
-2
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
// Launch the original API front controller for the verified, database-independent routes.
|
||||
// Launch the original API front controller for the verified routes.
|
||||
function failRequest($status, $message)
|
||||
{
|
||||
http_response_code($status);
|
||||
@@ -28,7 +28,9 @@ if ($path === '/') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!preg_match('~\A/api(?:/index\.php)?(?:/v1/(?:auth/ping|info/(?:versions|versionsbyname)))?/?\z~i', $path ?? '')) {
|
||||
$patientLookup = getenv('EZSERVER_SQLITE')
|
||||
&& preg_match('~\A/api(?:/index\.php)?/v1/e2ds/patientsbychartno/?\z~i', $path ?? '');
|
||||
if (!$patientLookup && !preg_match('~\A/api(?:/index\.php)?(?:/v1/(?:auth/ping|info/(?:versions|versionsbyname)))?/?\z~i', $path ?? '')) {
|
||||
failRequest(404, 'Route is unavailable in the macOS preview');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -54,6 +54,32 @@ foreach (["intl", "mbstring", "session", "pdo_sqlite"] as $extension) {
|
||||
}
|
||||
}
|
||||
'
|
||||
if [[ -n "${EZSERVER_SQLITE:-}" ]]; then
|
||||
if [[ "$EZSERVER_SQLITE" != /* || "${EZSERVER_JWT_KEY_FILE:-}" != /* ||
|
||||
! -f "$EZSERVER_JWT_KEY_FILE" || ! -r "$EZSERVER_JWT_KEY_FILE" ]]; then
|
||||
printf '%s\n' 'Set EZSERVER_SQLITE and EZSERVER_JWT_KEY_FILE to absolute paths.' >&2
|
||||
exit 1
|
||||
fi
|
||||
cp "$EZSERVER_JWT_KEY_FILE" "$stage/jwt-key"
|
||||
chmod 600 "$stage/jwt-key"
|
||||
export EZSERVER_JWT_KEY_FILE="$stage/jwt-key"
|
||||
"$php" -r '
|
||||
if (strlen(trim(file_get_contents($argv[1]))) < 32) {
|
||||
fwrite(STDERR, "The JWT signing key must contain at least 32 bytes." . PHP_EOL);
|
||||
exit(1);
|
||||
}
|
||||
' "$EZSERVER_JWT_KEY_FILE"
|
||||
"$php" "$server_dir/init-sqlite.php" "$EZSERVER_SQLITE"
|
||||
cp -R "$EZSERVER_RUNTIME" "$stage/runtime"
|
||||
export EZSERVER_RUNTIME="$stage/runtime"
|
||||
config="$EZSERVER_RUNTIME/www/ezwebserver/src/application/config/production"
|
||||
mkdir -p "$config"
|
||||
cp "$server_dir/sqlite-database.php" "$config/database.php"
|
||||
cp "$server_dir/sqlite-rest.php" "$config/rest.php"
|
||||
fi
|
||||
if [[ -f "$EZSERVER_RUNTIME/webconsole/index.html" ]]; then
|
||||
ln -s "$EZSERVER_RUNTIME/webconsole" "$stage/webconsole"
|
||||
fi
|
||||
"$nginx" -e stderr -p "$stage/" -c nginx.conf -t
|
||||
"$fpm" -F -y "$stage/php-fpm.conf" &
|
||||
fpm_pid=$!
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
defined('BASEPATH') or exit('No direct script access allowed');
|
||||
|
||||
$active_group = 'E2DB';
|
||||
$query_builder = true;
|
||||
$db['E2DB'] = [
|
||||
'dbdriver' => 'pdo',
|
||||
'subdriver' => 'sqlite',
|
||||
'dsn' => 'sqlite:' . getenv('EZSERVER_SQLITE'),
|
||||
'db_debug' => false,
|
||||
'options' => [
|
||||
// PostgreSQL returns lowercase names for the original models' unquoted columns.
|
||||
PDO::ATTR_CASE => PDO::CASE_LOWER,
|
||||
PDO::ATTR_TIMEOUT => 5,
|
||||
],
|
||||
];
|
||||
@@ -0,0 +1,6 @@
|
||||
<?php
|
||||
|
||||
defined('BASEPATH') or exit('No direct script access allowed');
|
||||
|
||||
// Preserve the original JWT validation with a deployment-specific signing key.
|
||||
$config['jwt_key'] = trim(file_get_contents(getenv('EZSERVER_JWT_KEY_FILE')));
|
||||
Reference in new issue
Block a user