Add native EzServer macOS compatibility preview

This commit is contained in:
SantaSpeen committed 2026-11-22 02:04:07 +03:00
1 parent 6b95fbb1fc
commit 9d8b2fcbb1
10 files changed
+396 -3

No files matched your search

+8 -2
View File
@@ -4,6 +4,12 @@ import PackageDescription
let package = Package(
name: "EzDent",
platforms: [.macOS(.v13)],
products: [.executable(name: "EzDent", targets: ["EzDent"])],
targets: [.executableTarget(name: "EzDent")]
products: [
.executable(name: "EzDent", targets: ["EzDent"]),
.executable(name: "EzServerMac", targets: ["EzServerMac"])
],
targets: [
.executableTarget(name: "EzDent"),
.executableTarget(name: "EzServerMac")
]
)
+4
View File
@@ -45,3 +45,7 @@ open dist/EzDent.app
- Во встроенном 3D-просмотрщике можно вращать и масштабировать объём, менять порог поверхности и переключаться на проекцию максимальной интенсивности (MIP). Для 3D текстура уменьшается до 256 вокселей по длинной стороне.
- Встроенный GDCM 3.2.3 декодирует JPEG, JPEG-LS, JPEG 2000 и RLE и нормализует Big Endian и Deflated. EzDent отображает целочисленные монохромные кадры и 8-битные цветные RGB/YBR. Покадровая геометрия реализована для согласованных серий. Видео DICOM, объекты без пиксельных данных и построение объёма из нерегулярных серий не поддерживаются. Совместимость с клиническими сериями ezServer ещё не проверялась.
- В установщике Ez3D-i 5.5.12.3 найдены отдельные модули DICOM, MPR и VolumeViz. Приложение macOS реализует эти сценарии средствами SwiftUI, Metal и [GDCM](https://github.com/malaterre/GDCM). Геометрия и покадровые группы строятся по [DICOM PS3.3](https://dicom.nema.org/medical/dicom/current/output/chtml/part03/sect_C.7.6.16.html), декодирование использует [DICOM PS3.5, раздел A](https://dicom.nema.org/medical/dicom/current/output/chtml/part05/chapter_A.html).
## EzServer для macOS
Серверный эксперимент собирается отдельно командой `./scripts/build-server.sh`. Он запускается на `127.0.0.1:55005` и отвечает на информационные запросы EzWebServer. Состав Windows-установщика, запуск и ограничения описаны в [server/README.md](server/README.md).
+152
View File
@@ -0,0 +1,152 @@
import Foundation
import Network
private struct APIVersion: Encodable {
let name: String
let url: String
let supportStatus: String
}
private struct VersionList: Encodable {
let errorCode = 0
let serverName = "EzWebServer"
let currentVersionName = "3.0.6"
let currentStageVersionName = "0"
let versions: [APIVersion]
}
private struct VersionMatch: Encodable {
let errorCode = 0
let serverName = "EzWebServer"
let clientVersion: APIVersion
let serverVersion: APIVersion
}
private final class LocalServer {
private let listener: NWListener
private let queue = DispatchQueue(label: "ezserver.loopback")
private let maxHeaderSize = 8192
init(port: UInt16) throws {
let parameters = NWParameters.tcp
parameters.requiredLocalEndpoint = .hostPort(host: "127.0.0.1", port: NWEndpoint.Port(rawValue: port)!)
listener = try NWListener(using: parameters)
}
func start() {
listener.stateUpdateHandler = { state in
switch state {
case .ready:
if let port = self.listener.port {
print("EzServer Mac preview is listening on http://127.0.0.1:\(port)")
fflush(stdout)
}
case let .failed(error):
FileHandle.standardError.write(Data("Could not start EzServer: \(error)\n".utf8))
exit(EXIT_FAILURE)
default:
break
}
}
listener.newConnectionHandler = { [weak self] connection in
guard let self else { connection.cancel(); return }
connection.start(queue: self.queue)
self.queue.asyncAfter(deadline: .now() + 5) { [weak connection] in connection?.cancel() }
self.receive(on: connection, buffer: Data())
}
listener.start(queue: queue)
}
private func receive(on connection: NWConnection, buffer: Data) {
connection.receive(minimumIncompleteLength: 1, maximumLength: maxHeaderSize - buffer.count) {
[weak self] data, _, complete, failure in
guard let self, failure == nil else { connection.cancel(); return }
var request = buffer
if let data { request.append(data) }
if let boundary = request.range(of: Data("\r\n\r\n".utf8)) {
self.handle(request.prefix(upTo: boundary.lowerBound), on: connection)
} else if request.count >= self.maxHeaderSize {
self.send(["error": "Request header too large"], status: "431 Request Header Fields Too Large", on: connection)
} else if complete {
connection.cancel()
} else {
self.receive(on: connection, buffer: request)
}
}
}
private func handle(_ request: Data, on connection: NWConnection) {
let lines = String(decoding: request, as: UTF8.self).components(separatedBy: "\r\n")
let requestLine = lines[0].split(separator: " ", omittingEmptySubsequences: false)
let hosts = lines.dropFirst().compactMap { line -> String? in
let parts = line.split(separator: ":", maxSplits: 1, omittingEmptySubsequences: false)
guard parts.count == 2, parts[0].lowercased() == "host" else { return nil }
return parts[1].trimmingCharacters(in: .whitespaces)
}
guard requestLine.count == 3, ["HTTP/1.0", "HTTP/1.1"].contains(requestLine[2]),
requestLine[1].hasPrefix("/"), !requestLine[1].hasPrefix("//"),
let target = URLComponents(string: String(requestLine[1])),
hosts.count == 1,
hosts[0].range(of: #"\A(?:127\.0\.0\.1|localhost)(?::[0-9]{1,5})?\z"#,
options: [.regularExpression, .caseInsensitive]) != nil else {
send(["error": "Invalid request or host"], status: "400 Bad Request", on: connection)
return
}
guard requestLine[0] == "GET" else {
send(["error": "Only GET is supported"], status: "405 Method Not Allowed",
extraHeaders: "Allow: GET\r\n", 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",
"3.0.0", "3.0.1", "3.0.2", "3.0.3", "3.0.4", "3.0.5", "3.0.6"
].map { APIVersion(name: $0, url: apiURL, supportStatus: "supported") }
let listing = VersionList(versions: versions)
let path = target.path.lowercased().trimmingCharacters(in: CharacterSet(charactersIn: "/"))
switch path {
case "", "health":
send(["service": "EzServer Mac preview", "status": "ok"], on: connection)
case "api/v1/info/versions", "api/index.php/v1/info/versions":
send(listing, on: connection)
case "api/v1/info/versionsbyname", "api/index.php/v1/info/versionsbyname":
let name = target.queryItems?.first(where: { $0.name == "name" })?.value ?? ""
let match = versions.first { $0.name == name } ?? APIVersion(name: name, url: "", supportStatus: "unknown")
send(VersionMatch(clientVersion: match, serverVersion: versions[versions.count - 1]), on: connection)
default:
send(["error": "Route is unavailable in the macOS preview"], status: "404 Not Found", on: connection)
}
}
private func send<Response: Encodable>(_ response: Response, status: String = "200 OK",
extraHeaders: String = "", on connection: NWConnection) {
guard let body = try? JSONEncoder().encode(response) else { connection.cancel(); return }
let headers = """
HTTP/1.1 \(status)\r
Content-Type: application/json; charset=utf-8\r
Content-Length: \(body.count)\r
Cache-Control: no-store\r
Connection: close\r
\(extraHeaders)\r
"""
connection.send(content: Data(headers.utf8) + body, completion: .contentProcessed { _ in
connection.cancel()
})
}
}
let servicePort = ProcessInfo.processInfo.environment["EZSERVER_PORT"] ?? "55005"
guard let port = UInt16(servicePort), port > 0 else {
FileHandle.standardError.write(Data("EZSERVER_PORT must be between 1 and 65535.\n".utf8))
exit(EXIT_FAILURE)
}
do {
let server = try LocalServer(port: port)
server.start()
withExtendedLifetime(server) { dispatchMain() }
} catch {
FileHandle.standardError.write(Data("Could not start EzServer: \(error)\n".utf8))
exit(EXIT_FAILURE)
}
+1 -1
View File
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")/.."
build_for_arch() {
local arch="$1"
local scratch_path=".build/$arch"
swift build -c release --arch "$arch" --scratch-path "$scratch_path" >&2 || return
swift build -c release --product EzDent --arch "$arch" --scratch-path "$scratch_path" >&2 || return
swift build -c release --arch "$arch" --scratch-path "$scratch_path" --show-bin-path
}
+28
View File
@@ -0,0 +1,28 @@
#!/bin/bash
set -euo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")/.."
build_for_arch() {
local arch="$1"
local scratch=".build/server-$arch"
swift build -c release --product EzServerMac --arch "$arch" --scratch-path "$scratch" >&2 || return
swift build -c release --arch "$arch" --scratch-path "$scratch" --show-bin-path
}
arm64_bin="$(build_for_arch arm64)"
x86_64_bin="$(build_for_arch x86_64)"
mkdir -p dist
stage="$(mktemp -d dist/.EzServer.XXXXXX)"
trap 'rm -rf "$stage"' EXIT
package="$stage/EzServerMac"
mkdir "$package"
binary="$package/EzServerMac"
xcrun lipo -create "$arm64_bin/EzServerMac" "$x86_64_bin/EzServerMac" -output "$binary"
xcrun lipo "$binary" -verify_arch arm64 x86_64
codesign --force --sign - "$binary"
codesign --verify --strict "$binary"
cp server/README.md "$package/README.md"
ditto -c -k --keepParent "$package" "$stage/EzServerMac-universal.zip"
mv "$stage/EzServerMac-universal.zip" dist/EzServerMac-universal.zip
printf '%s\n' "$PWD/dist/EzServerMac-universal.zip"
+19
View File
@@ -0,0 +1,19 @@
# EzServer для macOS
Экспериментальная серверная сборка для macOS 13 и новее, Intel и Apple Silicon. Распакуйте архив, откройте терминал в этой папке и запустите `./EzServerMac`. Сервер слушает только `127.0.0.1:55005`. Чтобы выбрать другой порт, запустите, например, `EZSERVER_PORT=55105 ./EzServerMac`.
```sh
curl http://127.0.0.1:55005/health
curl http://127.0.0.1:55005/api/v1/info/versions
curl 'http://127.0.0.1:55005/api/v1/info/versionsByName?name=3.0.6'
```
Два запроса версий используют поля и значения из EzWebServer в установщике EzServer 4.1.6. Версия API в нём — 3.0.6. Сборка предназначена для проверки подключения и обнаружения API. Вход, PostgreSQL, карточки, снимки, Windows File Manager и Patch Manager пока не перенесены.
## Сборка из репозитория
`./scripts/build-server.sh` создаёт `dist/EzServerMac-universal.zip`. Нужны Swift и Xcode Command Line Tools. Готовый исполняемый файл работает без PHP, PostgreSQL и Windows.
## Эксперимент с оригинальным PHP
В репозитории отдельно есть средства для извлечения оригинального EzWebServer из вашего установщика. `server/prepare.sh` использует Python 3, 7-Zip и unshield. Путь к установщику можно передать первым аргументом. Если команды называются иначе, укажите их через `EZSERVER_7ZIP` и `EZSERVER_UNSHIELD`. Затем `server/run.sh` пробует запустить веб-компонент на PHP CLI с расширениями intl, mbstring и session. Этот режим ограничен локальными информационными маршрутами и требует отдельной проверки совместимости PHP.
+67
View File
@@ -0,0 +1,67 @@
"""Extract the EzServer cabinet records from a 7-Zip InstallShield overlay."""
from pathlib import Path
import shutil
import sys
CABINETS = {b"data1.hdr", b"data1.cab", b"data2.cab"}
def read_field(stream):
value = bytearray()
for _ in range(1024):
byte = stream.read(1)
if byte == b"\0":
return bytes(value)
if not byte:
break
value.extend(byte)
raise ValueError("Incomplete InstallShield record")
def extract(overlay, output):
missing = CABINETS.copy()
with overlay.open("rb") as stream:
while missing:
name = read_field(stream)
read_field(stream) # Path on the installation media.
read_field(stream) # File version.
size = int(read_field(stream))
end = stream.tell() + size
if size < 0 or end > overlay.stat().st_size:
raise ValueError("Invalid InstallShield record size")
if name in missing:
with (output / name.decode("ascii")).open("wb") as destination:
remaining = size
while remaining:
chunk = stream.read(min(remaining, 1024 * 1024))
if not chunk:
raise ValueError("Truncated cabinet")
destination.write(chunk)
remaining -= len(chunk)
missing.remove(name)
stream.seek(end)
def stage_web_service(extracted, runtime):
source = extracted / "www" / "ezwebserver" / "src"
destination = runtime / "www" / "ezwebserver" / "src"
for folder in ("application", "public", "vendor"):
shutil.copytree(
source / folder,
destination / folder,
ignore=shutil.ignore_patterns(
"*.exe", "*.dll", "*.bat", "*.cmd", "*.msi", "dbconfig.ini", "config_base.ini"
),
)
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")
if __name__ == "__main__":
if sys.argv[1] == "cabinet":
extract(Path(sys.argv[2]), Path(sys.argv[3]))
elif sys.argv[1] == "stage":
stage_web_service(Path(sys.argv[2]), Path(sys.argv[3]))
else:
raise SystemExit("Unknown extraction operation")
+39
View File
@@ -0,0 +1,39 @@
#!/bin/bash
set -euo pipefail
umask 077
server_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
project_dir="$(dirname "$server_dir")"
installer="${1:-$project_dir/_source/EzServer V4.1.6 Setup.exe}"
runtime="${EZSERVER_RUNTIME:-$project_dir/.build/ezserver-macos/runtime}"
unshield="${EZSERVER_UNSHIELD:-unshield}"
archive_tool="${EZSERVER_7ZIP:-7z}"
if [[ ! -f "$installer" ]]; then
printf 'EzServer installer not found: %s\n' "$installer" >&2
exit 1
fi
for dependency in "$unshield" "$archive_tool" python3; do
if ! command -v "$dependency" >/dev/null; then
printf 'Missing extraction tool: %s\n' "$dependency" >&2
exit 1
fi
done
if [[ -e "$runtime" ]]; then
printf 'EzServer runtime already exists: %s\n' "$runtime" >&2
exit 1
fi
parent="$(dirname "$runtime")"
mkdir -p "$parent"
stage="$(mktemp -d "$parent/.prepare.XXXXXX")"
trap 'rm -rf "$stage"' EXIT
"$archive_tool" e -y "-o$stage" "$installer" '[0]' >/dev/null
python3 "$server_dir/extract-installshield.py" cabinet "$stage/[0]" "$stage"
"$unshield" -g EzWebServer_Install -d "$stage/extracted" x "$stage/data1.cab" > "$stage/extract.log"
mkdir "$stage/runtime"
python3 "$server_dir/extract-installshield.py" stage "$stage/extracted/EzWebServer_Install" "$stage/runtime"
test -f "$stage/runtime/www/ezwebserver/src/public/api/index.php"
test -f "$stage/runtime/www/ezwebserver/src/vendor/autoload.php"
mv "$stage/runtime" "$runtime"
printf '%s\n' "$runtime"
+43
View File
@@ -0,0 +1,43 @@
<?php
// Launch the original API front controller for the verified, database-independent routes.
function failRequest($status, $message)
{
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['error' => $message]);
}
header('Cache-Control: no-store');
$host = $_SERVER['HTTP_HOST'] ?? '';
if (!preg_match('/\A(?:127\.0\.0\.1|localhost)(?::[0-9]{1,5})?\z/i', $host)) {
failRequest(400, 'Use a loopback host');
return;
}
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'GET') {
header('Allow: GET');
failRequest(405, 'Only GET is supported');
return;
}
$runtime = getenv('EZSERVER_RUNTIME');
$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
if ($path === '/') {
header('Content-Type: text/html; charset=utf-8');
readfile($runtime . '/index.html');
return;
}
if (!preg_match('~\A/api(?:/index\.php)?(?:/v1/info/(?:versions|versionsbyname))?/?\z~i', $path ?? '')) {
failRequest(404, 'Route is unavailable in the macOS preview');
return;
}
$public = $runtime . '/www/ezwebserver/src/public';
$_SERVER['DOCUMENT_ROOT'] = $public;
$_SERVER['SCRIPT_FILENAME'] = $public . '/api/index.php';
$_SERVER['SCRIPT_NAME'] = '/api/index.php';
$_SERVER['PHP_SELF'] = '/api/index.php';
$_SERVER['CI_ENV'] = 'production';
chdir($public . '/api');
require $_SERVER['SCRIPT_FILENAME'];
Executable
+35
View File
@@ -0,0 +1,35 @@
#!/bin/bash
set -euo pipefail
umask 077
server_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
project_dir="$(dirname "$server_dir")"
runtime="${EZSERVER_RUNTIME:-$project_dir/.build/ezserver-macos/runtime}"
php="${EZSERVER_PHP:-php}"
port="${EZSERVER_PORT:-55005}"
if [[ ! -f "$runtime/www/ezwebserver/src/public/api/index.php" ]]; then
printf '%s\n' 'Prepare the EzServer runtime with server/prepare.sh first.' >&2
exit 1
fi
if ! command -v "$php" >/dev/null; then
printf '%s\n' 'PHP CLI is required. Install PHP or set EZSERVER_PHP to its executable.' >&2
exit 1
fi
if ! [[ "$port" =~ ^[1-9][0-9]{0,4}$ ]] || (( port > 65535 )); then
printf '%s\n' 'EZSERVER_PORT must be between 1 and 65535.' >&2
exit 1
fi
"$php" -r '
foreach (["intl", "mbstring", "session"] as $extension) {
if (!extension_loaded($extension)) {
fwrite(STDERR, "Missing PHP extension: " . $extension . PHP_EOL);
exit(1);
}
}
'
export EZSERVER_RUNTIME="$(cd "$runtime" && pwd)"
mkdir -p "$EZSERVER_RUNTIME/empty"
exec "$php" -d display_errors=0 -d expose_php=0 \
-S "127.0.0.1:$port" -t "$EZSERVER_RUNTIME/empty" "$server_dir/router.php"