Files
ezServer-MacOS/Sources/EzServerMac/MenuBarServer.swift
T

171 lines
6.3 KiB
Swift

import AppKit
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 stopping = false
@Published var copying = false
@Published var port = "55005"
@Published var notice: String?
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)
start()
} catch {
notice = error.localizedDescription
}
}
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, !stopping, !copying, 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() {
guard let server, !stopping else { return }
generation = UUID()
starting = false
running = false
stopping = true
server.stop { [weak self] in
Task { @MainActor in
self?.server = nil
self?.stopping = false
}
}
}
func chooseImagesFolder() {
guard canChangeImages, let configuration else { return }
let panel = NSOpenPanel()
panel.canChooseFiles = false
panel.canChooseDirectories = true
panel.canCreateDirectories = true
panel.message = "Выберите папку, в которой EzServer создаст каталог Files."
guard panel.runModal() == .OK, let url = panel.url else { return }
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 { copying = false }
do {
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 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
var body: some View {
VStack(alignment: .leading, spacing: 12) {
HStack {
Text("Порт")
TextField("55005", text: $model.port)
.frame(width: 75)
.disabled(model.running || model.starting || model.stopping)
.accessibilityLabel("Порт HTTP")
Spacer()
Button(model.running || model.starting ? "Остановить" : "Запустить") {
if model.running || model.starting { model.stop() } else { model.start() }
}
.disabled(model.imagesPath.isEmpty || model.stopping || model.copying)
}
HStack {
Text("Папка снимков")
Spacer()
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)
}
Button("Открыть Web Console", action: model.openConsole)
.disabled(!model.running)
}
.padding(16)
.frame(width: 360)
}
}