From 69f70d0325fac9fb9f05b95a3f08f3f85f56147d Mon Sep 17 00:00:00 2001 From: SantaSpeen Date: Mon, 23 Nov 2026 17:11:05 +0300 Subject: [PATCH] Remove the non-original Mac HTTP API --- README.md | 12 +-- Sources/EzServerMac/CommandLine.swift | 3 +- Sources/EzServerMac/LibraryAPI.swift | 121 ------------------------ Sources/EzServerMac/LocalServer.swift | 121 ++++-------------------- Sources/EzServerMac/MenuBarServer.swift | 3 +- context.md | 6 +- 6 files changed, 22 insertions(+), 244 deletions(-) delete mode 100644 Sources/EzServerMac/LibraryAPI.swift diff --git a/README.md b/README.md index 0ab6638..f1421bf 100644 --- a/README.md +++ b/README.md @@ -26,17 +26,7 @@ Web Console приложения использует Material Design 3 и вх Проверка состояния и версии доступна по `GET /health`, `GET /api/v1/auth/ping`, `GET /api/v1/info/versions` и `GET /api/v1/info/versionsByName?name=3.0.6`. Запрос `GET /api/v1/fs/sysinfofordiskspace` возвращает ёмкость и свободное место диска и требует токен. -Маршруты `/mac/v1` требуют заголовок `Authorization: Bearer <токен>`. - -| Метод и путь | Действие | -| --- | --- | -| `GET /mac/v1/patients?q=...&offset=0&limit=50` | Поиск по имени и номеру карты с пагинацией. | -| `POST /mac/v1/patients` | Создание карточки из JSON с полями `name` и `chartNumber`. | -| `GET /mac/v1/patients/{patientID}` | Карточка и вложения. | -| `PUT /mac/v1/patients/{patientID}/images/{imageID}?name=...` | Загрузка оригинала с новым UUID. Передайте файл в теле с `Content-Length`. `Content-Type: application/dicom` сохраняет объект как DICOM. | -| `GET /mac/v1/patients/{patientID}/images/{imageID}` | Скачать обычный файл. | -| `GET /mac/v1/patients/{patientID}/images/{imageID}/slices/{number}` | Скачать DICOM-файл. Нумерация начинается с 1. | -| `DELETE /mac/v1/patients/{patientID}/images/{imageID}` | Удалить вложение и его оригиналы. | +Для EzDent используются оригинальные маршруты `/api/v1`. Вход приложения доступен через `POST /api/v1/auth/applogin` и `POST /api/v1/auth/apploginr2`. Защищённые маршруты карточек и снимков принимают выданный при входе JWT. ## Совместимость с EzServer 4.1.6 diff --git a/Sources/EzServerMac/CommandLine.swift b/Sources/EzServerMac/CommandLine.swift index e7cdbe0..d62bddb 100644 --- a/Sources/EzServerMac/CommandLine.swift +++ b/Sources/EzServerMac/CommandLine.swift @@ -33,8 +33,7 @@ func runCommandLine(_ arguments: [String]) { print("Imported new patients: \(imported)") } - let api = LibraryAPI(store: configuration.store, secret: configuration.token) - let server = try LocalServer(port: configuration.port, library: api) + let server = try LocalServer(port: configuration.port, configuration: configuration) server.start { state in switch state { case let .success(port): diff --git a/Sources/EzServerMac/LibraryAPI.swift b/Sources/EzServerMac/LibraryAPI.swift deleted file mode 100644 index f97a257..0000000 --- a/Sources/EzServerMac/LibraryAPI.swift +++ /dev/null @@ -1,121 +0,0 @@ -import CryptoKit -import EzDentStorage -import Foundation -import UniformTypeIdentifiers - -struct LibraryAPI { - struct Listing: Encodable { - let patients: [PatientSummary] - let total: Int - let offset: Int - let limit: Int - } - - struct PatientSummary: Encodable { - let id: UUID - let name: String - let chartNumber: String - let imageCount: Int - - init(_ patient: PatientRecord, imageCount: Int) { - id = patient.id - name = patient.name - chartNumber = patient.chartNumber - self.imageCount = imageCount - } - } - - struct File { - let handle: FileHandle - let bytes: Int - let contentType: String - let filename: String - } - - enum Result { - case listing(Listing) - case patient(PatientRecord) - case file(File) - case invalidRequest - case unauthorized - case notFound - case unavailable - } - - let store: ServerStore - private let token: SHA256.Digest - - init(store: ServerStore, secret: String) { - self.store = store - token = SHA256.hash(data: Data(secret.utf8)) - } - - func isAuthorized(_ authorization: String?) -> Bool { - guard let authorization, authorization.hasPrefix("Bearer ") else { return false } - let candidate = SHA256.hash(data: Data(authorization.dropFirst(7).utf8)) - return zip(candidate, token).reduce(UInt8(0)) { $0 | ($1.0 ^ $1.1) } == 0 - } - - func response(path: [String], query: [URLQueryItem], authorization: String?) -> Result { - guard isAuthorized(authorization) else { return .unauthorized } - do { - if path.isEmpty { return try list(store.patients(), query: query) } - guard let patientID = UUID(uuidString: path[0]), - let patient = try store.patient(patientID) else { return .notFound } - if path.count == 1 { return .patient(patient) } - - guard path.count == 3 || path.count == 5, path[1] == "images", - let imageID = UUID(uuidString: path[2]), - let image = patient.images.first(where: { $0.id == imageID }) else { return .notFound } - if path.count == 3, image.dicomCount == nil { - return .file(try openFile(store.attachment(image.id), - filename: image.name)) - } - if path.count == 5, path[3] == "slices", let number = Int(path[4]), - let count = image.dicomCount, (1...4096).contains(count), (1...count).contains(number) { - return .file(try openFile(store.slice(number, of: image.id), - filename: "slice-\(number).dcm", contentType: "application/dicom")) - } - return .notFound - } catch FileError.notFound { - return .notFound - } catch { - return .unavailable - } - } - - private func list(_ patients: [PatientRecord], query: [URLQueryItem]) throws -> Result { - let search = query.first { $0.name == "q" }?.value?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" - let offset = query.first { $0.name == "offset" }?.value ?? "0" - let limit = query.first { $0.name == "limit" }?.value ?? "50" - guard let offset = Int(offset), offset >= 0, let limit = Int(limit), - (1...200).contains(limit), search.count <= 200 else { return .invalidRequest } - let selected = patients.filter { - search.isEmpty || $0.name.localizedStandardContains(search) - || $0.chartNumber.localizedStandardContains(search) - } - let start = min(offset, selected.count) - let results = try selected.dropFirst(start).prefix(limit).map { - PatientSummary($0, imageCount: try store.imageCount($0.id)) - } - return .listing(Listing(patients: results, total: selected.count, offset: offset, limit: limit)) - } - - private func openFile(_ url: URL, filename: String = "", contentType: String? = nil) throws -> File { - guard url.deletingLastPathComponent().resolvingSymlinksInPath().path - == url.deletingLastPathComponent().path else { throw FileError.notFound } - let descriptor = open(url.path, O_RDONLY | O_NOFOLLOW | O_NONBLOCK) - guard descriptor >= 0 else { throw FileError.notFound } - var metadata = stat() - guard fstat(descriptor, &metadata) == 0, metadata.st_mode & S_IFMT == S_IFREG else { - close(descriptor) - throw FileError.notFound - } - let mime = UTType(filenameExtension: (filename as NSString).pathExtension)?.preferredMIMEType - return File(handle: FileHandle(fileDescriptor: descriptor, closeOnDealloc: true), - bytes: Int(metadata.st_size), contentType: contentType ?? mime ?? "application/octet-stream", - filename: filename) - } - - private enum FileError: Error { case notFound } -} diff --git a/Sources/EzServerMac/LocalServer.swift b/Sources/EzServerMac/LocalServer.swift index 7a80a3d..9d3f9ae 100644 --- a/Sources/EzServerMac/LocalServer.swift +++ b/Sources/EzServerMac/LocalServer.swift @@ -1,3 +1,4 @@ +import CryptoKit import Foundation import Network import OSLog @@ -29,7 +30,8 @@ final class LocalServer { private let queue = DispatchQueue(label: "ezserver.http") private let maxHeaderSize = 8192 private let diagnostics = Logger(subsystem: "EzServerMac", category: "HTTP") - private let library: LibraryAPI + private let store: ServerStore + private let diskSpaceToken: SHA256.Digest private let webConsole = WebConsoleAPI() private var connections: [ObjectIdentifier: NWConnection] = [:] private var diagnosticRoutes: [ObjectIdentifier: String] = [:] @@ -38,8 +40,9 @@ final class LocalServer { "implantds", "iosensor", "orthods", "thirdparty", "device", "pay", ] - init(port: UInt16, library: LibraryAPI) throws { - self.library = library + init(port: UInt16, configuration: ServerConfiguration) throws { + store = configuration.store + diskSpaceToken = SHA256.hash(data: Data(configuration.token.utf8)) let parameters = NWParameters.tcp (parameters.defaultProtocolStack.internetProtocol as? NWProtocolIP.Options)?.version = .v4 parameters.requiredLocalEndpoint = .hostPort(host: "0.0.0.0", port: NWEndpoint.Port(rawValue: port)!) @@ -150,7 +153,7 @@ final class LocalServer { let reply: (Data) -> Void = { [self] body in let response = webConsole.reply(path: route, method: method, body: body, authorization: bearer, query: target.queryItems ?? [], - queryPathLast: segments.last, store: library.store) + queryPathLast: segments.last, store: store) guard let json = try? JSONSerialization.data(withJSONObject: response.body) else { connection.cancel() return @@ -172,16 +175,6 @@ final class LocalServer { return } } - if segments.starts(with: ["mac", "v1", "patients"]) { - let path = Array(segments.dropFirst(3)) - if method == "GET" { - serveLibrary(path: path, query: target.queryItems ?? [], authorization: bearer, on: connection) - } else { - mutateLibrary(method: method, path: path, query: target.queryItems ?? [], authorization: bearer, - headers: headers, initialBody: initialBody, on: connection) - } - return - } guard method == "GET" else { send(["error": "Only GET is supported"], status: "405 Method Not Allowed", extraHeaders: "Allow: GET\r\n", on: connection) @@ -216,8 +209,8 @@ final class LocalServer { case "api/v1/auth/ping", "api/index.php/v1/auth/ping": send(LegacyPing(), on: connection) case "api/v1/fs/sysinfofordiskspace", "api/index.php/v1/fs/sysinfofordiskspace": - guard library.isAuthorized(bearer) else { sendUnauthorized(on: connection); return } - let values = try? library.store.directory.resourceValues(forKeys: [ + guard isAuthorizedForDiskSpace(bearer) else { sendUnauthorized(on: connection); return } + let values = try? store.directory.resourceValues(forKeys: [ .volumeTotalCapacityKey, .volumeAvailableCapacityKey ]) guard let total = values?.volumeTotalCapacity, let free = values?.volumeAvailableCapacity else { @@ -280,42 +273,15 @@ final class LocalServer { }) } - private func serveLibrary(path: [String], query: [URLQueryItem], authorization: String?, - on connection: NWConnection) { - switch library.response(path: path, query: query, authorization: authorization) { - case let .listing(listing): - send(listing, on: connection) - case let .patient(patient): - send(patient, on: connection) - case let .file(file): - let safeName = file.filename.addingPercentEncoding(withAllowedCharacters: CharacterSet( - charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~" - )) ?? "image" - let headers = responseHeaders(status: "200 OK", type: file.contentType, bytes: file.bytes, - extra: "Content-Disposition: attachment; filename*=UTF-8''\(safeName)\r\n") - connection.send(content: headers, completion: .contentProcessed { [weak self] error in - guard let self, error == nil else { connection.cancel(); return } - self.stream(file.handle, remaining: file.bytes, on: connection) - }) - case .unauthorized: - sendUnauthorized(on: connection) - case .invalidRequest: - send(["error": "Invalid limit, offset or search query"], status: "400 Bad Request", on: connection) - case .notFound: - send(["error": "Patient or image not found"], status: "404 Not Found", on: connection) - case .unavailable: - send(["error": "Could not read patient library"], status: "503 Service Unavailable", on: connection) - } - } - private struct LegacyPing: Encodable { let errorCode = 0 let message = "Pong" } - private struct PatientInput: Decodable { - let name: String - let chartNumber: String + private func isAuthorizedForDiskSpace(_ authorization: String?) -> Bool { + guard let authorization, authorization.hasPrefix("Bearer ") else { return false } + let candidate = SHA256.hash(data: Data(authorization.dropFirst(7).utf8)) + return zip(candidate, diskSpaceToken).reduce(UInt8(0)) { $0 | ($1.0 ^ $1.1) } == 0 } private func sendUnauthorized(on connection: NWConnection) { @@ -323,61 +289,6 @@ final class LocalServer { extraHeaders: "WWW-Authenticate: Bearer\r\n", on: connection) } - private func mutateLibrary(method: String, path: [String], query: [URLQueryItem], authorization: String?, - headers: [String: [String]], initialBody: Data, on connection: NWConnection) { - guard library.isAuthorized(authorization) else { sendUnauthorized(on: connection); return } - if method == "POST", path.isEmpty { - acceptBody(headers, initial: initialBody, maximum: 32 * 1024, on: connection) { url in - guard let input = try? JSONDecoder().decode(PatientInput.self, from: Data(contentsOf: url)) else { - throw StoreError.invalid - } - let patient = try self.library.store.createPatient(name: input.name, chartNumber: input.chartNumber) - self.send(patient, status: "201 Created", on: connection) - } - return - } - guard path.count == 3, path[1] == "images", let patient = UUID(uuidString: path[0]), - let image = UUID(uuidString: path[2]) else { - send(["error": "Route or method unavailable"], status: "404 Not Found", on: connection) - return - } - if method == "DELETE" { - do { - try library.store.deleteFile(patient: patient, imageID: image) - send(["status": "deleted"], on: connection) - } catch { - sendMutationError(error, on: connection) - } - } else if method == "PUT" { - guard let name = query.first(where: { $0.name == "name" })?.value, !name.isEmpty else { - sendMutationError(StoreError.invalid, on: connection) - return - } - let dicom = headers["content-type"]?.first?.lowercased() == "application/dicom" - acceptBody(headers, initial: initialBody, maximum: 2 * 1024 * 1024 * 1024, on: connection) { url in - let item = try self.library.store.addFile(from: url, patient: patient, imageID: image, - name: name, dicom: dicom) - self.send(item, status: "201 Created", on: connection) - } - } else { - send(["error": "Method unavailable"], status: "405 Method Not Allowed", - extraHeaders: "Allow: GET, PUT, DELETE\r\n", on: connection) - } - } - - private func sendMutationError(_ error: Error, on connection: NWConnection) { - switch error { - case StoreError.invalid: - send(["error": "Invalid patient or file"], status: "400 Bad Request", on: connection) - case StoreError.notFound: - send(["error": "Patient or file not found"], status: "404 Not Found", on: connection) - case StoreError.conflict: - send(["error": "Duplicate chart number or file identifier"], status: "409 Conflict", on: connection) - default: - send(["error": "Could not update storage"], status: "503 Service Unavailable", on: connection) - } - } - private func acceptBody(_ headers: [String: [String]], initial: Data, maximum: Int, on connection: NWConnection, finish: @escaping (URL) throws -> Void) { guard headers["transfer-encoding"] == nil, let lengths = headers["content-length"], @@ -390,7 +301,7 @@ final class LocalServer { return } do { - let upload = try IncomingFile(in: library.store.directory) + let upload = try IncomingFile(in: store.directory) let timeout = DispatchWorkItem { [weak connection] in connection?.cancel() } queue.asyncAfter(deadline: .now() + 300, execute: timeout) if headers["expect"]?.first?.lowercased() == "100-continue" { @@ -399,7 +310,7 @@ final class LocalServer { } receiveBody(upload, chunk: initial, remaining: length, on: connection, timeout: timeout, finish: finish) } catch { - sendMutationError(error, on: connection) + send(["error": "Could not read request body"], status: "503 Service Unavailable", on: connection) } } @@ -426,7 +337,7 @@ final class LocalServer { } } catch { timeout.cancel() - sendMutationError(error, on: connection) + send(["error": "Could not read request body"], status: "503 Service Unavailable", on: connection) } } diff --git a/Sources/EzServerMac/MenuBarServer.swift b/Sources/EzServerMac/MenuBarServer.swift index 9a74051..e281793 100644 --- a/Sources/EzServerMac/MenuBarServer.swift +++ b/Sources/EzServerMac/MenuBarServer.swift @@ -81,8 +81,7 @@ private final class ServerControl: ObservableObject { return } do { - let api = LibraryAPI(store: configuration.store, secret: configuration.token) - let server = try LocalServer(port: portValue, library: api) + let server = try LocalServer(port: portValue, configuration: configuration) self.server = server starting = true notice = nil diff --git a/context.md b/context.md index 7b678a8..9183113 100644 --- a/context.md +++ b/context.md @@ -3,7 +3,7 @@ ## Цель и принятые решения - Целевая связка на текущем этапе — EzDent для macOS и EzServer для macOS. Сервер должен работать нативно на Intel и Apple Silicon с macOS 13+, хранить данные в SQLite и использовать оригинальный PHP API EzServer 4.1.6 там, где это возможно. -- Переиспользовать контроллеры, модели и маршруты оригинального EzWebServer под `/api/v1`. Сохранять оригинальные методы, параметры и форматы ответов. `/mac/v1` — контракт раннего Swift-сервера, который подлежит замене при переносе. План запуска — нативные nginx и PHP-FPM под управлением EzServer.app. Адаптировать конфигурацию БД, схему, запросы с синтаксисом PostgreSQL и пути файлового хранилища. +- Переиспользовать контроллеры, модели и маршруты оригинального EzWebServer под `/api/v1`. Сохранять оригинальные методы, параметры и форматы ответов. План запуска — нативные nginx и PHP-FPM под управлением EzServer.app. Адаптировать конфигурацию БД, схему, запросы с синтаксисом PostgreSQL и пути файлового хранилища. - File Manager (55001) и Patch Manager (55011) исключены из текущего объёма по решению владельца. Для передачи файлов в целевой связке использовать HTTP. Совместимость с Windows-клиентом на этих портах не является условием приёмки. ## Репозитории и сборка @@ -15,7 +15,7 @@ ## Что работает сейчас - В строке меню предусмотрены только запуск/остановка, порт, выбор папки снимков и кнопка `/webconsole`. При смене папки снимки копируются в новый каталог `Files`. Импорт доступен через CLI. Swift и PHP по умолчанию слушают `0.0.0.0:43112`. Для одновременного запуска нужен отдельный порт для PHP. API доступен по IPv4-адресу Mac, страница административной Web Console доступна на loopback. Маршруты AppLogIn и AppLogInR2 открыты по сети и выдают JWT. -- Swift-сервер хранит метаданные в SQLite, оригиналы в `Files`, поддерживает импорт библиотеки EzDent, создание карточек и загрузку, экспорт и удаление вложений. API `/mac/v1` использует Bearer-токен. Каталог данных по умолчанию — `~/Library/Application Support/EzServerMac`. Панель, тестовый импорт и побайтовая выдача оригинала после перезапуска уже проверены. +- Swift-сервер хранит метаданные в SQLite, оригиналы в `Files`, поддерживает импорт библиотеки EzDent, создание карточек и загрузку, экспорт и удаление вложений. Каталог данных по умолчанию — `~/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-подключение и открывает локальную библиотеку. ## Где смотреть в оригинале @@ -34,4 +34,4 @@ Проверен оригинальный PHP GET карточки по номеру через отдельную SQLite с таблицей `e2_pat` и оригинальной проверкой JWT с локальным ключом. См. README для параметров запуска. Следующие шаги — выдача JWT через оригинальный вход, запись и поиск карточек, перенос файловых моделей и запуск из меню приложения. Текущие маршруты Swift описаны в README. -- Запущенный Swift-сервер обслуживает оригинальный `GET /api/v1/e2ds/patientsByChartNo?chartno=…` с JWT приложения. Чтение идёт из той же SQLite, что и `/mac/v1`. Импортированные из Mac записи хранят одно полное имя, оно выдаётся в `strLastName`. Снимки и остальные операции оригинального API требуют переноса. +- Запущенный Swift-сервер обслуживает оригинальный `GET /api/v1/e2ds/patientsByChartNo?chartno=…` с JWT приложения. Чтение идёт из SQLite приложения. Импортированные из Mac записи хранят одно полное имя, оно выдаётся в `strLastName`. Снимки и остальные операции оригинального API требуют переноса.