From 2df324647ae4266d7f39b874226dfc949b4616fa Mon Sep 17 00:00:00 2001 From: Christ Date: Wed, 12 Aug 2026 20:53:53 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E5=96=84=E4=B8=89=E5=B9=B3=E5=8F=B0?= =?UTF-8?q?=E5=AE=89=E8=A3=85=E5=8C=85=E4=B8=8E=E6=9C=8D=E5=8A=A1=E6=8E=A7?= =?UTF-8?q?=E5=88=B6=E6=B5=81=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 统一服务默认端口为 59188,完善 Windows 服务权限与 macOS LaunchAgent 管理。 实现 Windows 与 macOS 托盘状态机、服务启停等待、单实例保护、日志目录入口和退出前清理后台服务。 统一 Linux、Windows、macOS 与 Docker 的 Playwright Chromium runtime 构建流程,增加缓存、架构校验和 Linux 原生 runner,避免 QEMU。 完善 Windows、macOS、Linux 安装包及签名打包脚本,修正 Chromium 嵌入、服务注册和安装卸载流程。 同步 README、AGENTS、官网首页、Wiki 与前端开发文档,统一端口、初始化、服务、日志、托盘和安装说明。 --- .env.example | 2 +- .github/workflows/desktop-cd.yml | 88 ++++-- .github/workflows/docker-publish.yml | 135 +++++++-- AGENTS.md | 84 +++++- Dockerfile.debian13 | 4 +- README.md | 67 ++++- cmd/server/main.go | 35 ++- cmd/server/main_test.go | 23 ++ cmd/tray/instance_lock_unix.go | 43 +++ cmd/tray/instance_lock_unix_test.go | 29 ++ cmd/tray/instance_lock_windows.go | 27 ++ cmd/tray/main.go | 266 ++++++++++++++++-- cmd/tray/main_test.go | 66 +++++ cmd/tray/service_control_darwin.go | 56 +++- cmd/tray/service_control_other.go | 9 +- cmd/tray/service_control_windows.go | 191 +++++++++++-- cmd/tray/service_control_windows_test.go | 83 ++++++ compose.yml | 6 +- docker-compose.debian13-postgres17.yml | 6 +- docker-compose.functional.yml | 18 +- docs/index.html | 76 +++-- docs/wiki/Home.md | 33 ++- docs/wiki/部署与数据库.md | 43 ++- frontend/README.md | 8 +- frontend/vite.config.ts | 54 ++-- packaging/linux/install.sh | 2 + packaging/linux/ydisks-xianyu-helper.service | 3 +- packaging/macos/build-pkg.sh | 27 +- ...ydisks.xianyu-helper.server.plist.template | 2 +- ...m.ydisks.xianyu-helper.tray.plist.template | 2 + packaging/macos/prepare-runtime.sh | 72 +++++ packaging/macos/scripts/postinstall | 27 +- packaging/windows/installer.iss | 33 ++- packaging/windows/service-control.ps1 | 134 +++++++++ scripts/docker-functional-test.sh | 6 +- 35 files changed, 1546 insertions(+), 214 deletions(-) create mode 100644 cmd/tray/instance_lock_unix.go create mode 100644 cmd/tray/instance_lock_unix_test.go create mode 100644 cmd/tray/instance_lock_windows.go create mode 100644 cmd/tray/main_test.go create mode 100644 cmd/tray/service_control_windows_test.go create mode 100755 packaging/macos/prepare-runtime.sh create mode 100644 packaging/windows/service-control.ps1 diff --git a/.env.example b/.env.example index 10d6705..b566b0c 100644 --- a/.env.example +++ b/.env.example @@ -13,7 +13,7 @@ DATABASE_URL=postgres://xianyu:请替换为URL编码后的数据库密码@postgr XIANYU_IMAGE=ghcr.io/christ9038/ydisks-xianyu-helper:latest XIANYU_DATA_KEY=请替换为稳定且足够长的随机密钥 XIANYU_BIND_ADDRESS=0.0.0.0 -XIANYU_HTTP_PORT=8080 +XIANYU_HTTP_PORT=59188 XIANYU_UPLOAD_DIR=/app/data/uploads TZ=Asia/Shanghai LOG_LEVEL=info diff --git a/.github/workflows/desktop-cd.yml b/.github/workflows/desktop-cd.yml index 9c832fc..5aa4dea 100644 --- a/.github/workflows/desktop-cd.yml +++ b/.github/workflows/desktop-cd.yml @@ -18,12 +18,19 @@ env: jobs: linux: - name: Linux 安装包 + name: Linux 安装包 (${{ matrix.arch }}) if: github.ref == 'refs/heads/codex/desktop-packaging' - runs-on: ubuntu-latest + runs-on: ${{ matrix.runner }} strategy: + fail-fast: false matrix: - arch: [amd64, arm64] + include: + - arch: amd64 + runner: ubuntu-24.04 + playwright_platform: ubuntu24.04-x64 + - arch: arm64 + runner: ubuntu-24.04-arm + playwright_platform: ubuntu24.04-arm64 steps: - name: 检出代码 uses: actions/checkout@v6 @@ -41,9 +48,6 @@ jobs: cache: npm cache-dependency-path: frontend/package-lock.json - - name: 配置 QEMU - uses: docker/setup-qemu-action@v4 - - name: 构建嵌入式前端 run: npm ci --prefix frontend && npm run build --prefix frontend @@ -63,33 +67,62 @@ jobs: uses: actions/cache/restore@v5 with: path: dist/ydisks-xianyu-helper-linux-${{ matrix.arch }}/playwright-runtime - key: ydisks-playwright-runtime-v2-linux-${{ matrix.arch }}-${{ hashFiles('go.mod', 'go.sum', 'cmd/browser-install/main.go') }} + key: ydisks-playwright-runtime-v4-linux-${{ matrix.arch }}-${{ hashFiles('go.mod', 'go.sum', 'cmd/browser-install/main.go') }} - - name: 预下载 Linux Chromium runtime + - name: 在原生架构 runner 预下载 Linux Chromium runtime if: steps.cache-linux-playwright.outputs.cache-hit != 'true' env: GOARCH: ${{ matrix.arch }} + PLAYWRIGHT_HOST_PLATFORM_OVERRIDE: ${{ matrix.playwright_platform }} run: | set -Eeuo pipefail + case "$(uname -m)" in + x86_64) runner_arch=amd64 ;; + aarch64|arm64) runner_arch=arm64 ;; + *) echo "不支持的 runner 架构:$(uname -m)" >&2; exit 1 ;; + esac + if [ "$runner_arch" != "$GOARCH" ]; then + echo "runner 架构 $runner_arch 与目标架构 $GOARCH 不一致,拒绝使用模拟器构建。" >&2 + exit 1 + fi package_dir="dist/ydisks-xianyu-helper-linux-${GOARCH}" runtime_dir="$package_dir/playwright-runtime/$GOARCH" - case "$GOARCH" in - amd64) playwright_platform="ubuntu20.04-x64" ;; - arm64) playwright_platform="ubuntu20.04-arm64" ;; - *) echo "不支持的 Linux 架构:$GOARCH" >&2; exit 1 ;; - esac mkdir -p "$runtime_dir/playwright-driver" "$runtime_dir/playwright-browsers" - PLAYWRIGHT_HOST_PLATFORM_OVERRIDE="$playwright_platform" \ - "$package_dir/browser-install" \ - -driver-dir "$runtime_dir/playwright-driver" \ - -browser-dir "$runtime_dir/playwright-browsers" + "$package_dir/browser-install" \ + -driver-dir "$PWD/$runtime_dir/playwright-driver" \ + -browser-dir "$PWD/$runtime_dir/playwright-browsers" - name: 保存 Linux Chromium runtime 缓存 if: steps.cache-linux-playwright.outputs.cache-hit != 'true' uses: actions/cache/save@v5 with: path: dist/ydisks-xianyu-helper-linux-${{ matrix.arch }}/playwright-runtime - key: ${{ steps.cache-linux-playwright.outputs.cache-primary-key }} + key: ydisks-playwright-runtime-v4-linux-${{ matrix.arch }}-${{ hashFiles('go.mod', 'go.sum', 'cmd/browser-install/main.go') }} + + - name: 校验 Linux Chromium runtime 架构 + env: + GOARCH: ${{ matrix.arch }} + run: | + set -Eeuo pipefail + runtime_dir="dist/ydisks-xianyu-helper-linux-${GOARCH}/playwright-runtime/${GOARCH}" + node_path="$runtime_dir/playwright-driver/node" + test -x "$node_path" + "$node_path" --version + node_type="$(file -b "$node_path")" + case "$GOARCH:$node_type" in + amd64:*x86-64*) ;; + arm64:*aarch64*|arm64:*ARM64*) ;; + *) echo "Playwright driver 架构错误:$node_type" >&2; exit 1 ;; + esac + chromium_path="$(find "$runtime_dir/playwright-browsers" -type f \ + \( -name chrome -o -name headless_shell \) -perm -111 -print -quit)" + test -n "$chromium_path" + chromium_type="$(file -b "$chromium_path")" + case "$GOARCH:$chromium_type" in + amd64:*x86-64*) ;; + arm64:*aarch64*|arm64:*ARM64*) ;; + *) echo "Chromium 架构错误:$chromium_type" >&2; exit 1 ;; + esac - name: 组装 Linux 安装目录 run: | @@ -132,6 +165,22 @@ jobs: shell: pwsh run: npm ci --prefix frontend; npm run build --prefix frontend + - name: 验证 Windows 托盘逻辑与安装脚本 + shell: pwsh + run: | + go test ./cmd/tray + $tokens = $null + $parseErrors = $null + [void][System.Management.Automation.Language.Parser]::ParseFile( + (Resolve-Path 'packaging/windows/service-control.ps1'), + [ref]$tokens, + [ref]$parseErrors + ) + if ($parseErrors.Count -gt 0) { + $parseErrors | ForEach-Object { Write-Error $_.Message } + throw 'Windows 服务安装脚本语法检查失败' + } + - name: 编译 Windows 桌面程序 shell: pwsh run: | @@ -245,6 +294,9 @@ jobs: - name: 构建嵌入式前端 run: npm ci --prefix frontend && npm run build --prefix frontend + - name: 验证 macOS 托盘逻辑 + run: go test ./cmd/tray + - name: 编译 macOS 桌面程序 run: | mkdir -p dist/macos/arm64 dist/macos/amd64 diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml index 2869bf5..fe91d61 100644 --- a/.github/workflows/docker-publish.yml +++ b/.github/workflows/docker-publish.yml @@ -16,15 +16,38 @@ concurrency: cancel-in-progress: true jobs: - publish: - name: 发布多架构镜像 - runs-on: ubuntu-latest + build: + name: 构建镜像 (${{ matrix.arch }}) + runs-on: ${{ matrix.runner }} + strategy: + fail-fast: false + matrix: + include: + - arch: amd64 + runner: ubuntu-24.04 + platform: linux/amd64 + - arch: arm64 + runner: ubuntu-24.04-arm + platform: linux/arm64 steps: - name: 检出代码 uses: actions/checkout@v6 - - name: 配置 QEMU - uses: docker/setup-qemu-action@v4 + - name: 校验 runner 原生架构 + shell: bash + env: + EXPECTED_ARCH: ${{ matrix.arch }} + run: | + set -Eeuo pipefail + case "$(uname -m)" in + x86_64) actual_arch=amd64 ;; + aarch64|arm64) actual_arch=arm64 ;; + *) echo "不支持的 runner 架构:$(uname -m)" >&2; exit 1 ;; + esac + if [ "$actual_arch" != "$EXPECTED_ARCH" ]; then + echo "runner 架构 $actual_arch 与目标架构 $EXPECTED_ARCH 不一致,拒绝使用模拟器构建。" >&2 + exit 1 + fi - name: 配置 Docker Buildx uses: docker/setup-buildx-action@v4 @@ -41,6 +64,63 @@ jobs: shell: bash run: echo "name=ghcr.io/${GITHUB_REPOSITORY,,}" >> "$GITHUB_OUTPUT" + - name: 构建并推送原生架构摘要 + id: build + uses: docker/build-push-action@v7 + with: + context: . + file: Dockerfile.debian13 + platforms: ${{ matrix.platform }} + outputs: type=image,name=${{ steps.image.outputs.name }},push-by-digest=true,name-canonical=true,push=true + cache-from: type=gha,scope=ydisks-docker-${{ matrix.arch }} + cache-to: type=gha,mode=max,scope=ydisks-docker-${{ matrix.arch }} + provenance: mode=max + sbom: true + + - name: 保存镜像摘要 + shell: bash + env: + IMAGE_DIGEST: ${{ steps.build.outputs.digest }} + run: | + set -Eeuo pipefail + mkdir -p dist/digests + touch "dist/digests/${IMAGE_DIGEST#sha256:}" + + - name: 上传镜像摘要 + uses: actions/upload-artifact@v7 + with: + name: ydisks-docker-digest-${{ matrix.arch }} + path: dist/digests/* + if-no-files-found: error + retention-days: 1 + + publish: + name: 合并多架构镜像 + needs: build + runs-on: ubuntu-24.04 + steps: + - name: 配置 Docker Buildx + uses: docker/setup-buildx-action@v4 + + - name: 下载镜像摘要 + uses: actions/download-artifact@v8 + with: + pattern: ydisks-docker-digest-* + path: dist/digests + merge-multiple: true + + - name: 登录 GitHub Container Registry + uses: docker/login-action@v4 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: 生成小写镜像名称 + id: image + shell: bash + run: echo "name=ghcr.io/${GITHUB_REPOSITORY,,}" >> "$GITHUB_OUTPUT" + - name: 生成镜像标签 id: meta uses: docker/metadata-action@v6 @@ -54,17 +134,34 @@ jobs: type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }} type=raw,value=alpha,enable=${{ github.ref == 'refs/heads/codex/desktop-packaging' }} - - name: 构建并推送镜像 - uses: docker/build-push-action@v7 - with: - context: . - file: Dockerfile.debian13 - platforms: linux/amd64,linux/arm64 - push: true - tags: ${{ steps.meta.outputs.tags }} - labels: ${{ steps.meta.outputs.labels }} - # Dockerfile 中的 Chromium 下载层也由 GitHub Actions 主机缓存。 - cache-from: type=gha,scope=ydisks-docker - cache-to: type=gha,mode=max,scope=ydisks-docker - provenance: mode=max - sbom: true + - name: 创建并推送多架构 manifest + shell: bash + env: + IMAGE_NAME: ${{ steps.image.outputs.name }} + IMAGE_TAGS: ${{ steps.meta.outputs.tags }} + run: | + set -Eeuo pipefail + mapfile -t digest_files < <(find dist/digests -maxdepth 1 -type f -print | sort) + if [ "${#digest_files[@]}" -ne 2 ]; then + echo "预期 2 个镜像摘要,实际 ${#digest_files[@]} 个。" >&2 + exit 1 + fi + digest_args=() + for digest_file in "${digest_files[@]}"; do + digest_args+=("$IMAGE_NAME@sha256:$(basename "$digest_file")") + done + tag_args=() + while IFS= read -r tag; do + [ -n "$tag" ] && tag_args+=(--tag "$tag") + done <<< "$IMAGE_TAGS" + docker buildx imagetools create "${tag_args[@]}" "${digest_args[@]}" + + - name: 检查多架构 manifest + shell: bash + env: + IMAGE_TAGS: ${{ steps.meta.outputs.tags }} + run: | + set -Eeuo pipefail + first_tag="$(printf '%s\n' "$IMAGE_TAGS" | sed -n '/./{p;q;}')" + test -n "$first_tag" + docker buildx imagetools inspect "$first_tag" diff --git a/AGENTS.md b/AGENTS.md index 5fa48e2..6c7f1e7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,8 +34,8 @@ make frontend # build frontend into internal/webui/static Run the server (SQLite by default; MySQL/Postgres via `-db-url` or `DATABASE_URL`): ```bash -go run ./cmd/server -db data/xianyu_data.db -addr :8080 -DATABASE_URL="mysql://user:pass@tcp(host:3306)/db" go run ./cmd/server -addr :8080 +go run ./cmd/server -db data/xianyu_data.db -addr :59188 +DATABASE_URL="mysql://user:pass@tcp(host:3306)/db" go run ./cmd/server -addr :59188 ``` On a new database, open the management page after starting the server. The first-run page accepts @@ -45,7 +45,7 @@ The CLI bootstrap remains available for headless or operational environments. Disable browser automation when Chromium is unavailable: ```bash -go run ./cmd/server -db data/xianyu_data.db -addr :8080 -no-browser +go run ./cmd/server -db data/xianyu_data.db -addr :59188 -no-browser ``` Initialize or reset the administrator: @@ -89,7 +89,83 @@ Run the frontend development server: npm run dev ``` -Vite proxies backend routes to `localhost:8080`. Production builds are written to `internal/webui/static/` and embedded by the Go server. +Vite proxies backend routes to `localhost:59188`. Production builds are written to `internal/webui/static/` and embedded by the Go server. + +## Desktop packaging and service behavior + +The application defaults to port `59188`; commands using `-addr :59188` listen on all interfaces. Desktop +packages explicitly bind the server to `127.0.0.1:59188` and keep the server and tray as separate processes: + +- Windows installs the `YdisksXianyuHelper` Windows Service and starts `xianyu-tray.exe` for the current + user. The installer grants the interactive user only service status/start/stop rights, so tray service + actions do not launch UAC prompts after installation. Service configuration and deletion remain admin-only. +- macOS registers `com.ydisks.xianyu-helper.server` and `com.ydisks.xianyu-helper.tray` LaunchAgents. + The app is `/Applications/Ydisks闲鱼助手/Ydisks闲鱼助手.app`, and the tray executable is named + `Ydisks闲鱼助手` with `LSUIElement=true` so it does not appear in the Dock. +- Linux packages are architecture-specific tar archives. `install.sh` must run as root on a native matching + architecture, installs `ydisks-xianyu-helper.service`, and keeps data in `/var/lib/ydisks-xianyu-helper`. + +All desktop packages contain the matching Playwright driver, Chromium and headless shell. Do not add a +Debian Chromium package or download a second browser during installation. The desktop CI workflow runs +only on `codex/desktop-packaging`; Linux amd64 and arm64 jobs use native GitHub-hosted runners and must +not use QEMU or cross-architecture emulation. Docker publishing also builds each architecture on its native +runner and publishes `latest` only from `main`, `alpha` only from `codex/desktop-packaging`. + +The tray state machine is shared by Windows and macOS: it serializes actions, shows transition states, +waits for a healthy `/health` response after start/restart, waits for the endpoint to become unreachable +after stop, and stops the server before exiting. The tray also provides an “Open log directory” action. + +Desktop first-run initialization is done in the web UI at `http://127.0.0.1:59188`; users enter and confirm +the initial administrator password. `-init-admin` remains an operational/headless fallback, while Docker +Compose uses `XIANYU_ADMIN_PASSWORD` for non-interactive initialization. + +## macOS 本地安装包构建 + +macOS 安装包必须通过 `packaging/macos/build-pkg.sh` 构建,禁止手工复制 Chromium、Playwright +driver 或 headless shell 到 `dist`。打包脚本会检查目标架构的 runtime;runtime 不完整时自动调用 +`packaging/macos/prepare-runtime.sh`,从本机 Playwright 缓存整理出与 driver 匹配的 Chromium +和 Chromium headless shell。 + +本机 arm64 打包流程: + +```bash +npm ci --prefix frontend +npm run build --prefix frontend +mkdir -p dist/macos/arm64 +go build -trimpath -ldflags='-s -w' -o dist/macos/arm64/xianyu-server ./cmd/server +go build -trimpath -ldflags='-s -w' -o dist/macos/arm64/browser-install ./cmd/browser-install +go build -trimpath -ldflags='-s -w' -o dist/macos/arm64/xianyu-tray ./cmd/tray +packaging/macos/build-pkg.sh 0.0.0-local "$PWD/dist/macos" arm64 +``` + +`prepare-runtime.sh` 默认读取: + +- `~/Library/Caches/ms-playwright-go`:Playwright Go driver +- `~/Library/Caches/ms-playwright`:Chromium 与 `chromium_headless_shell` + +如果本机缓存尚未准备好,先运行编译出的 `browser-install`;不要只复制 +`chromium-`,服务启动还需要同版本的 `chromium_headless_shell-`。打包前必须确认 +服务能使用包内 runtime 启动并访问健康检查;可用临时端口验证: + +```bash +runtime_app="$PWD/dist/macos/pkgroot-arm64/Applications/Ydisks闲鱼助手/Ydisks闲鱼助手.app" +mkdir -p /tmp/ydisks-local-data +"$runtime_app/Contents/Helpers/xianyu-server" \ + -addr 127.0.0.1:59189 \ + -workdir /tmp/ydisks-local-data \ + -playwright-runtime-root "$runtime_app/Contents/Resources/playwright-runtime" +curl -fsS http://127.0.0.1:59189/health +``` + +本地没有签名身份时可以生成未签名 pkg,但必须明确告知未签名状态;CI 使用固定签名 Secrets 生成可分发包。 + +## CI desktop package rules + +Do not manually assemble desktop packages in CI. The desktop workflow must build the embedded frontend, +compile the platform binaries, restore or populate the architecture-specific Playwright runtime cache, +assemble the package with the platform packaging script, and run the package-specific signing step. +Windows uses `packaging/windows/installer.iss`; macOS uses `packaging/macos/build-pkg.sh`; Linux archives +the directory containing `install.sh`, `uninstall.sh`, the systemd unit, binaries and matching runtime. ## Architecture diff --git a/Dockerfile.debian13 b/Dockerfile.debian13 index 1b3858b..d430368 100644 --- a/Dockerfile.debian13 +++ b/Dockerfile.debian13 @@ -72,5 +72,5 @@ COPY --from=playwright-runtime /ms-playwright /ms-playwright RUN node /ms-playwright-go/package/cli.js install-deps chromium \ && rm -rf /var/lib/apt/lists/* RUN mkdir -p /app/data /app/browser_data -EXPOSE 8080 -CMD ["/app/xianyu-server", "-addr", ":8080"] +EXPOSE 59188 +CMD ["/app/xianyu-server", "-addr", ":59188"] diff --git a/README.md b/README.md index 8c23a1a..5e26725 100644 --- a/README.md +++ b/README.md @@ -146,7 +146,7 @@ openssl rand -base64 48 # 适合作为 XIANYU_DATA_KEY docker compose up -d ``` -浏览器访问 `http://localhost:8080`,使用用户名 `admin` 和 `.env` 中的 +浏览器访问 `http://localhost:59188`,使用用户名 `admin` 和 `.env` 中的 `XIANYU_ADMIN_PASSWORD` 登录。 > GHCR 镜像公开时可以匿名拉取。若镜像仍为私有,请先执行 @@ -177,11 +177,11 @@ npm --prefix frontend run build ### 方式三:桌面端安装包 桌面端由两个进程组成:后台 `xianyu-server` 负责 HTTP API、账号运行时和 Chromium; -`xianyu-tray` 只负责 Windows 托盘或 macOS 菜单栏状态、打开管理页面和服务控制。 +`xianyu-tray` 只负责 Windows 托盘或 macOS 菜单栏状态、打开管理页面、打开日志目录和服务控制。 Chromium 不打进 Go 二进制,但 Linux、Windows 和 macOS 独立安装包会内置对应架构的 Playwright driver 与 Chromium runtime,安装后无需用户再下载浏览器。 -- Windows:安装器注册 `YdisksXianyuHelper` Windows Service,并将托盘控制器加入当前用户登录启动项。 +- Windows:安装器注册 `YdisksXianyuHelper` Windows Service,并将托盘控制器加入当前用户登录启动项。安装阶段会为交互式登录用户授予该服务的状态查询、启动和停止权限;安装完成后从托盘启动、停止、重启或退出服务不再触发 UAC,也不会获得修改或删除服务的权限。 - macOS:安装器注册当前登录用户的两个 LaunchAgent,分别运行后台服务和菜单栏控制器。 - Linux:下载对应架构的 tar 包后,以 root 执行 `./install.sh`;安装包已经包含对应架构的 Playwright driver 与 Chromium,脚本只通过 Playwright 安装系统依赖,不会再下载浏览器。 @@ -189,16 +189,50 @@ Playwright driver 与 Chromium runtime,安装后无需用户再下载浏览器 卸载时执行 `./uninstall.sh`, 默认保留 `/var/lib/ydisks-xianyu-helper` 数据。 +桌面端安装后的固定位置和服务标识如下: + +| 平台 | 后台服务 | 托盘/菜单栏程序 | 数据与日志 | +| --- | --- | --- | --- | +| Windows | `YdisksXianyuHelper` Windows Service | 当前用户登录启动的 `xianyu-tray.exe` | `C:\ProgramData\YdisksXianyuHelper\data`、`C:\ProgramData\YdisksXianyuHelper\logs` | +| macOS | `com.ydisks.xianyu-helper.server` LaunchAgent | `Ydisks闲鱼助手.app` 内的菜单栏程序 | `~/Library/Application Support/YdisksXianyuHelper`、`~/Library/Logs/YdisksXianyuHelper` | +| Linux | `ydisks-xianyu-helper.service` systemd unit | 无桌面托盘 | `/var/lib/ydisks-xianyu-helper`、`/var/log/ydisks-xianyu-helper` | + +Windows 和 macOS 托盘启动时会自动启动后台服务,并显示检查中、启动中、运行正常、正在停止 +等状态。选择“退出托盘”时,只有确认后台服务已经停止后托盘才会退出;“打开日志目录”可直接 +打开日志位置。Windows 安装阶段会为交互式登录用户授予当前服务的查询、启动和停止权限, +安装完成后托盘控制服务不需要重复确认 UAC;修改服务配置或删除服务仍需管理员权限。 + +托盘菜单中的“退出托盘”会先停止后台服务,再退出托盘程序;“打开日志目录”可直接打开当前平台的日志目录:Windows +为 `C:\ProgramData\YdisksXianyuHelper\logs`,macOS 为 +`~/Library/Logs/YdisksXianyuHelper`。Linux 服务日志同时写入 +`/var/log/ydisks-xianyu-helper/server.log`,也可以使用 +`journalctl -u ydisks-xianyu-helper.service` 查看。 + 桌面端安装包由 GitHub Actions 的 `codex/desktop-packaging` 分支专用工作流构建:Linux 上传 amd64/arm64 tar 包,Windows 上传安装器,macOS 分别上传 arm64 和 amd64 安装包。Windows 和 macOS 安装包使用工作流中配置的固定签名证书签名;未配置对应 GitHub Secrets 时,签名 步骤会失败,不会生成可分发的安装包。 +Linux 安装包的 `install.sh` 必须在与安装包相同架构的 Linux 主机上以 root 执行。安装包已经 +包含对应架构的 Playwright driver、Chromium 和 headless shell;安装时只安装 Chromium 所需 +系统库,不会从 Debian 仓库重新安装 Chromium。 + +本地 macOS 打包可直接执行: + +```bash +./packaging/macos/prepare-runtime.sh arm64 ./dist/macos/playwright-runtime/arm64 +./packaging/macos/build-pkg.sh 0.0.0-local ./dist/macos arm64 +``` + +`build-pkg.sh` 会自动复用 `~/Library/Caches/ms-playwright-go` 和 +`~/Library/Caches/ms-playwright` 中与当前 Playwright driver 匹配的 Chromium;缓存不完整时会明确报错, +不会生成安装后无法启动服务的残缺安装包。Intel macOS 使用 `amd64` 参数,并需要本机已有对应 x64 runtime。 + 桌面端首次启动: 1. 安装对应平台的安装包。macOS 请选择 arm64(Apple Silicon)或 amd64(Intel)版本。 2. 启动后台服务和托盘/菜单栏控制器。 -3. 打开托盘菜单中的管理页面,或访问 `http://127.0.0.1:8080`。 +3. 打开托盘菜单中的管理页面,或访问 `http://127.0.0.1:59188`。 4. 如果数据库尚未初始化,页面会要求设置并确认管理员密码;完成后会自动登录,管理员用户名为 `admin`。 Linux 需要先安装并启动 systemd 服务: @@ -207,7 +241,12 @@ Linux 需要先安装并启动 systemd 服务: sudo ./install.sh ``` -然后访问 `http://127.0.0.1:8080` 完成首次初始化。 +然后访问 `http://127.0.0.1:59188` 完成首次初始化。 + +Linux、Windows、macOS 和源码运行默认都使用网页初始化:启动服务后打开 +`http://127.0.0.1:59188`,在“首次设置管理员密码”页面输入并确认不少于 8 个字符的密码, +系统会创建 `admin` 并自动登录。只有 Docker Compose 使用 `.env` 中的 +`XIANYU_ADMIN_PASSWORD` 做非交互初始化;CLI 方式仅用于无浏览器、自动化部署或重置密码。 对于无浏览器环境、自动化部署或需要重置管理员密码的运维场景,仍可使用 CLI 初始化: @@ -222,16 +261,16 @@ go run ./cmd/server \ 启动服务: ```bash -go run ./cmd/server -db data/xianyu_data.db -addr :8080 +go run ./cmd/server -db data/xianyu_data.db -addr :59188 ``` -启动完成后访问 `http://localhost:8080`。如果数据库尚未初始化,直接在页面填写并确认 +启动完成后访问 `http://localhost:59188`。如果数据库尚未初始化,直接在页面填写并确认 管理员密码即可,不需要知道数据库文件路径,也不需要先执行 CLI 命令。 如当前环境无法安装 Chromium,可以使用 `-no-browser` 启动: ```bash -go run ./cmd/server -db data/xianyu_data.db -addr :8080 -no-browser +go run ./cmd/server -db data/xianyu_data.db -addr :59188 -no-browser ``` 此模式仍可运行管理后台,但浏览器指纹读取和滑块风控处理不可用,不建议用于需要登录 @@ -287,7 +326,7 @@ Docker Compose 还支持: | `POSTGRES_PASSWORD` | 必填 | 数据库密码 | | `XIANYU_IMAGE` | `ghcr.io/christ9038/ydisks-xianyu-helper:latest` | 应用镜像与标签 | | `XIANYU_BIND_ADDRESS` | `0.0.0.0` | 应用在宿主机上的绑定地址 | -| `XIANYU_HTTP_PORT` | `8080` | 应用在宿主机上的端口 | +| `XIANYU_HTTP_PORT` | `59188` | 应用在宿主机上的端口 | 默认 `compose.yml` 直接拉取 GHCR 的 `:latest` 多架构镜像;如需固定版本,请将 `XIANYU_IMAGE` 改为 `:main`、版本号或 `:sha-<提交号>` 标签。 @@ -302,7 +341,7 @@ Docker Compose 还支持: | --- | --- | --- | | `-db` | `data/xianyu_data.db` | SQLite 数据库路径 | | `-db-url` | 空 | `sqlite://`、`mysql://` 或 `postgres://` 连接 URL | -| `-addr` | `:8080` | HTTP 监听地址 | +| `-addr` | `:59188` | HTTP 监听地址 | | `-web` | 内嵌前端 | 外部前端静态资源目录,目录内需包含 `index.html` | | `-secure` | `false` | 为管理端 Cookie 添加 `Secure` 属性,HTTPS 部署应启用 | | `-no-browser` | `false` | 禁用 Chromium 指纹读取和滑块处理 | @@ -427,7 +466,7 @@ docker compose up -d ```bash docker compose ps -curl -fsS http://127.0.0.1:8080/health +curl -fsS http://127.0.0.1:59188/health docker compose logs --tail=200 app ``` @@ -491,7 +530,7 @@ docker volume ls --filter name=xianyu ```yaml services: app: - command: ["/app/xianyu-server", "-addr", ":8080", "-secure"] + command: ["/app/xianyu-server", "-addr", ":59188", "-secure"] ``` ## 开发指南 @@ -530,7 +569,7 @@ services: 启动后端: ```bash -go run ./cmd/server -db data/xianyu_data.db -addr :8080 +go run ./cmd/server -db data/xianyu_data.db -addr :59188 ``` 启动前端开发服务器: @@ -540,7 +579,7 @@ npm --prefix frontend ci npm --prefix frontend run dev ``` -访问 `http://localhost:3000`。Vite 会将 API 请求代理到 `http://localhost:8080`。 +访问 `http://localhost:3000`。Vite 会将 API 请求代理到 `http://localhost:59188`。 构建嵌入式前端和 Go 二进制: diff --git a/cmd/server/main.go b/cmd/server/main.go index af00667..58b6466 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -9,6 +9,7 @@ import ( "errors" "flag" "fmt" + "io" "log/slog" "os" "os/signal" @@ -88,7 +89,7 @@ func parseOptions() serverOptions { var opts serverOptions flag.StringVar(&opts.dbPath, "db", defaultDBPath, "SQLite 数据库路径(兼容旧用法)") flag.StringVar(&opts.dbURL, "db-url", "", "数据库连接 URL(sqlite:// mysql:// postgres://),优先级高于 -db;也可用 DATABASE_URL 环境变量") - flag.StringVar(&opts.addr, "addr", ":8080", "HTTP 监听地址") + flag.StringVar(&opts.addr, "addr", ":59188", "HTTP 监听地址") flag.StringVar(&opts.webDir, "web", "", "前端静态资源目录(含 index.html)") flag.StringVar(&opts.workDir, "workdir", "", "服务工作目录;用于桌面服务固定数据和浏览器目录") flag.StringVar(&opts.playwrightRuntimeRoot, "playwright-runtime-root", "", "随安装包分发的 Playwright runtime 根目录") @@ -185,7 +186,12 @@ func runServer(parent context.Context, opts serverOptions) error { resolvedLogFormat = strings.TrimSpace(opts.logFormat) explicitLogFormat = true } - logger := logging.NewLogger(os.Stdout, resolvedLogFormat) + logWriter, closeLog, err := openServerLogWriter(dataDir) + if err != nil { + return err + } + defer closeLog() + logger := logging.NewLogger(logWriter, resolvedLogFormat) slog.SetDefault(logger) database, dialect, err := db.Open(ctx, resolvedDBURL) @@ -207,7 +213,7 @@ func runServer(parent context.Context, opts serverOptions) error { } if !explicitLogFormat { if format, err := store.Settings.Get(ctx, "log_format"); err == nil && strings.TrimSpace(format) != "" { - logger = logging.NewLogger(os.Stdout, format) + logger = logging.NewLogger(logWriter, format) slog.SetDefault(logger) } } @@ -279,6 +285,29 @@ func runServer(parent context.Context, opts serverOptions) error { return runErr } +// openServerLogWriter keeps container and interactive runs on stdout while +// desktop/system-service installations persist logs in their platform log +// directory. Windows services do not have a useful console, so they get a +// default log file beside the service data directory. +func openServerLogWriter(dataDir string) (io.Writer, func(), error) { + logDir := strings.TrimSpace(os.Getenv("XIANYU_LOG_DIR")) + if logDir == "" && runtime.GOOS == "windows" && dataDir != "" { + logDir = filepath.Join(dataDir, "logs") + } + if logDir == "" { + return os.Stdout, func() {}, nil + } + if err := os.MkdirAll(logDir, 0o700); err != nil { + return nil, nil, fmt.Errorf("创建日志目录失败: %w", err) + } + logPath := filepath.Join(logDir, "server.log") + file, err := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600) + if err != nil { + return nil, nil, fmt.Errorf("打开日志文件失败: %w", err) + } + return file, func() { _ = file.Close() }, nil +} + func applyPlaywrightRuntimeRoot(opts *serverOptions) { if opts == nil { return diff --git a/cmd/server/main_test.go b/cmd/server/main_test.go index 814d852..c57d01a 100644 --- a/cmd/server/main_test.go +++ b/cmd/server/main_test.go @@ -2,6 +2,7 @@ package main import ( "context" + "io" "os" "path/filepath" "runtime" @@ -56,6 +57,28 @@ func TestLoadOrCreateDataKeyPersists(t *testing.T) { } } +func TestOpenServerLogWriterUsesConfiguredDirectory(t *testing.T) { + logDir := t.TempDir() + t.Setenv("XIANYU_LOG_DIR", logDir) + + writer, closeLog, err := openServerLogWriter("") + if err != nil { + t.Fatalf("open log writer: %v", err) + } + if _, err := io.WriteString(writer, "test log\n"); err != nil { + t.Fatalf("write log: %v", err) + } + closeLog() + + content, err := os.ReadFile(filepath.Join(logDir, "server.log")) + if err != nil { + t.Fatalf("read log file: %v", err) + } + if string(content) != "test log\n" { + t.Fatalf("unexpected log content: %q", content) + } +} + func TestResolveDataDirKeepsExplicitDirectory(t *testing.T) { explicit := filepath.Join(t.TempDir(), "ydisks-data") got, err := resolveDataDir(explicit) diff --git a/cmd/tray/instance_lock_unix.go b/cmd/tray/instance_lock_unix.go new file mode 100644 index 0000000..01f7911 --- /dev/null +++ b/cmd/tray/instance_lock_unix.go @@ -0,0 +1,43 @@ +//go:build !windows + +package main + +import ( + "fmt" + "os" + "path/filepath" + + "golang.org/x/sys/unix" +) + +func acquireTrayInstance() (release func(), acquired bool, err error) { + cacheDirectory, err := os.UserCacheDir() + if err != nil { + return nil, false, fmt.Errorf("获取用户缓存目录失败: %w", err) + } + lockDirectory := filepath.Join(cacheDirectory, "YdisksXianyuHelper") + if err := os.MkdirAll(lockDirectory, 0o755); err != nil { + return nil, false, fmt.Errorf("创建托盘锁目录失败: %w", err) + } + + return acquireTrayFileLock(filepath.Join(lockDirectory, "tray.lock")) +} + +func acquireTrayFileLock(lockPath string) (release func(), acquired bool, err error) { + lockFile, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0o600) + if err != nil { + return nil, false, fmt.Errorf("打开托盘锁文件失败: %w", err) + } + if err := unix.Flock(int(lockFile.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil { + _ = lockFile.Close() + if err == unix.EWOULDBLOCK || err == unix.EAGAIN { + return func() {}, false, nil + } + return nil, false, fmt.Errorf("锁定托盘实例失败: %w", err) + } + + return func() { + _ = unix.Flock(int(lockFile.Fd()), unix.LOCK_UN) + _ = lockFile.Close() + }, true, nil +} diff --git a/cmd/tray/instance_lock_unix_test.go b/cmd/tray/instance_lock_unix_test.go new file mode 100644 index 0000000..b97fd9a --- /dev/null +++ b/cmd/tray/instance_lock_unix_test.go @@ -0,0 +1,29 @@ +//go:build !windows + +package main + +import ( + "path/filepath" + "testing" +) + +func TestAcquireTrayInstanceRejectsSecondInstance(t *testing.T) { + lockPath := filepath.Join(t.TempDir(), "tray.lock") + releaseFirst, acquired, err := acquireTrayFileLock(lockPath) + if err != nil { + t.Fatalf("acquire first tray instance: %v", err) + } + if !acquired { + t.Fatal("first tray instance should acquire lock") + } + defer releaseFirst() + + releaseSecond, acquired, err := acquireTrayFileLock(lockPath) + if err != nil { + t.Fatalf("acquire second tray instance: %v", err) + } + defer releaseSecond() + if acquired { + t.Fatal("second tray instance must be rejected") + } +} diff --git a/cmd/tray/instance_lock_windows.go b/cmd/tray/instance_lock_windows.go new file mode 100644 index 0000000..d2f9f9d --- /dev/null +++ b/cmd/tray/instance_lock_windows.go @@ -0,0 +1,27 @@ +//go:build windows + +package main + +import ( + "fmt" + + "golang.org/x/sys/windows" +) + +func acquireTrayInstance() (release func(), acquired bool, err error) { + mutexName, err := windows.UTF16PtrFromString(`Local\YdisksXianyuHelperTray`) + if err != nil { + return nil, false, fmt.Errorf("生成托盘互斥锁名称失败: %w", err) + } + handle, err := windows.CreateMutex(nil, false, mutexName) + if err == windows.ERROR_ALREADY_EXISTS { + if handle != 0 { + _ = windows.CloseHandle(handle) + } + return func() {}, false, nil + } + if err != nil { + return nil, false, fmt.Errorf("创建托盘互斥锁失败: %w", err) + } + return func() { _ = windows.CloseHandle(handle) }, true, nil +} diff --git a/cmd/tray/main.go b/cmd/tray/main.go index 2ba8707..a65312d 100644 --- a/cmd/tray/main.go +++ b/cmd/tray/main.go @@ -5,11 +5,17 @@ package main import ( "encoding/json" "fmt" + "log" "net/http" "os" "os/exec" + "os/signal" + "path/filepath" "runtime" "strings" + "sync" + "sync/atomic" + "syscall" "time" "fyne.io/systray" @@ -20,10 +26,89 @@ type healthResponse struct { Database string `json:"database"` } -var serviceURL = strings.TrimRight(envOr("XIANYU_SERVICE_URL", "http://127.0.0.1:8080"), "/") +var serviceURL = strings.TrimRight(envOr("XIANYU_SERVICE_URL", "http://127.0.0.1:59188"), "/") + +var ( + actionMu sync.Mutex + transitioning atomic.Bool + exitRequested atomic.Bool +) func main() { - systray.Run(onReady, func() {}) + closeLog := configureTrayLogger() + defer closeLog() + releaseInstance, acquired, err := acquireTrayInstance() + if err != nil { + log.Printf("获取托盘单实例锁失败: %v", err) + return + } + if !acquired { + log.Printf("托盘已经运行,本次启动直接退出") + return + } + defer releaseInstance() + log.Printf("托盘启动,PID=%d", os.Getpid()) + watchTerminationSignals() + systray.Run(onReady, onTrayExit) + + // systray 的退出回调运行在 Cocoa/系统托盘事件循环中,不能在回调 + // 内同步执行 launchctl,否则 macOS 可能把 LaunchAgent 标记为已退出, + // 但实际托盘进程仍然存活。等事件循环真正返回后再处理外部退出。 + if !exitRequested.Load() { + log.Printf("托盘事件循环结束,清理后台服务") + if err := quitTray(); err != nil { + log.Printf("清理后台服务失败: %v", err) + } else if err := waitForService(&http.Client{Timeout: 2 * time.Second}, false, 30*time.Second); err != nil { + log.Printf("等待后台服务退出失败: %v", err) + } + } + log.Printf("托盘退出") +} + +func watchTerminationSignals() { + signals := make(chan os.Signal, 1) + signal.Notify(signals, os.Interrupt, syscall.SIGTERM) + go func() { + reason := <-signals + log.Printf("收到进程终止信号: %s", reason) + + actionMu.Lock() + // actionMu 保证不会与菜单动作并发;拿到锁时其它动作已经完成。 + transitioning.Store(true) + if err := quitTray(); err != nil { + log.Printf("终止前停止后台服务失败: %v", err) + } else if err := waitForService(&http.Client{Timeout: 2 * time.Second}, false, 30*time.Second); err != nil { + log.Printf("终止前等待后台服务退出失败: %v", err) + } + transitioning.Store(false) + actionMu.Unlock() + signal.Stop(signals) + os.Exit(0) + }() +} + +func onTrayExit() { + // 这里只记录事件。服务清理由 main 在 systray.Run 返回后执行,避免 + // 阻塞原生托盘事件循环。 + log.Printf("收到托盘退出事件") +} + +func configureTrayLogger() func() { + directory, err := logDirectoryPath() + if err != nil { + return func() {} + } + if err := os.MkdirAll(directory, 0o755); err != nil { + return func() {} + } + path := filepath.Join(directory, "tray.log") + file, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644) + if err != nil { + return func() {} + } + log.SetOutput(file) + log.SetFlags(log.LstdFlags | log.Lmicroseconds) + return func() { _ = file.Close() } } func onReady() { @@ -33,42 +118,52 @@ func onReady() { statusItem := systray.AddMenuItem("服务状态:检查中", "读取后台服务状态") openItem := systray.AddMenuItem("打开管理页面", "在默认浏览器打开管理页面") + logItem := systray.AddMenuItem("打开日志目录", "打开后台服务和托盘日志所在目录") systray.AddSeparator() startItem := systray.AddMenuItem("启动服务", "启动后台服务") stopItem := systray.AddMenuItem("停止服务", "停止后台服务") restartItem := systray.AddMenuItem("重启服务", "重启后台服务") systray.AddSeparator() - quitItem := systray.AddMenuItem("退出托盘", "只退出菜单栏控制器") + quitItem := systray.AddMenuItem("退出托盘", "停止后台服务并退出菜单栏控制器") - go refreshStatus(statusItem) + // 安装脚本只负责注册平台服务。用户再次打开托盘时,托盘本身必须确保 + // 后台服务已启动。首次启动动作完成后再进入轮询,避免“检查中”的旧请求 + // 覆盖“启动中”等中间状态。 + go func() { + runServiceAction(statusItem, "启动服务", "启动中", "start", startItem, stopItem, restartItem, quitItem) + refreshStatus(statusItem) + }() go func() { for range openItem.ClickedCh { _ = openURL(serviceURL) } }() + go func() { + for range logItem.ClickedCh { + if err := openLogDirectory(); err != nil { + statusItem.SetTitle("日志目录:打开失败") + systray.SetTooltip(fmt.Sprintf("Ydisks闲鱼助手:打开日志目录失败:%v", err)) + } + } + }() go func() { for range startItem.ClickedCh { - runServiceAction(statusItem, "启动服务", "start") + runServiceAction(statusItem, "启动服务", "启动中", "start", startItem, stopItem, restartItem, quitItem) } }() go func() { for range stopItem.ClickedCh { - runServiceAction(statusItem, "停止服务", "stop") + runServiceAction(statusItem, "停止服务", "正在停止", "stop", startItem, stopItem, restartItem, quitItem) } }() go func() { for range restartItem.ClickedCh { - runServiceAction(statusItem, "重启服务", "restart") + runServiceAction(statusItem, "重启服务", "正在重启", "restart", startItem, stopItem, restartItem, quitItem) } }() go func() { for range quitItem.ClickedCh { - if err := quitTray(); err != nil { - statusItem.SetTitle("托盘状态:退出失败") - systray.SetTooltip(fmt.Sprintf("Ydisks闲鱼助手:托盘退出失败:%v", err)) - continue - } - systray.Quit() + exitTray(statusItem, startItem, stopItem, restartItem, quitItem) } }() } @@ -76,7 +171,13 @@ func onReady() { func refreshStatus(item *systray.MenuItem) { client := &http.Client{Timeout: 2 * time.Second} for { - refreshStatusOnce(item, client) + // 与菜单动作使用同一把锁,避免一次已经开始的健康检查在“启动中” + // 或“正在停止”之后才返回,并把中间状态错误覆盖掉。 + actionMu.Lock() + if !transitioning.Load() { + refreshStatusOnce(item, client) + } + actionMu.Unlock() time.Sleep(5 * time.Second) } } @@ -98,32 +199,137 @@ func refreshStatusOnce(item *systray.MenuItem, client *http.Client) { } } -func runServiceAction(statusItem *systray.MenuItem, actionName, action string) { +func runServiceAction(statusItem *systray.MenuItem, actionName, transitionTitle, action string, actionItems ...*systray.MenuItem) { + actionMu.Lock() + defer actionMu.Unlock() + if transitioning.Swap(true) { + return + } + defer transitioning.Store(false) + log.Printf("开始执行服务操作: %s", actionName) + setMenuItemsDisabled(true, actionItems...) + defer setMenuItemsDisabled(false, actionItems...) + systray.SetIcon(trayIconBytes(false)) - statusItem.SetTitle("服务状态:" + actionName + "中") + statusItem.SetTitle("服务状态:" + transitionTitle) + systray.SetTooltip("Ydisks闲鱼助手:" + transitionTitle) + client := &http.Client{Timeout: 2 * time.Second} + if action == "start" { + if health, err := readHealth(client); err == nil && health.Status == "ok" && health.Database == "ok" { + statusItem.SetTitle("服务状态:运行正常") + systray.SetIcon(trayIconBytes(true)) + systray.SetTooltip("Ydisks闲鱼助手:运行正常") + return + } + } if err := serviceAction(action); err != nil { + log.Printf("服务操作失败: %s: %v", actionName, err) statusItem.SetTitle("服务状态:操作失败") systray.SetTooltip(fmt.Sprintf("Ydisks闲鱼助手:%s失败:%v", actionName, err)) return } + wantRunning := action != "stop" + if err := waitForService(client, wantRunning, 30*time.Second); err != nil { + log.Printf("服务操作状态确认失败: %s: %v", actionName, err) + statusItem.SetTitle("服务状态:操作失败") + systray.SetTooltip(fmt.Sprintf("Ydisks闲鱼助手:%s后状态确认失败:%v", actionName, err)) + return + } + if wantRunning { + statusItem.SetTitle("服务状态:运行正常") + systray.SetIcon(trayIconBytes(true)) + systray.SetTooltip("Ydisks闲鱼助手:运行正常") + } else { + statusItem.SetTitle("服务状态:未运行") + systray.SetTooltip("Ydisks闲鱼助手:后台服务已停止") + } + log.Printf("服务操作完成: %s", actionName) +} - statusItem.SetTitle("服务状态:检查中") +func exitTray(statusItem *systray.MenuItem, actionItems ...*systray.MenuItem) { + actionMu.Lock() + defer actionMu.Unlock() + if transitioning.Swap(true) { + return + } + defer transitioning.Store(false) + log.Printf("开始退出托盘") + setMenuItemsDisabled(true, actionItems...) + + systray.SetIcon(trayIconBytes(false)) + statusItem.SetTitle("托盘状态:正在退出") + systray.SetTooltip("Ydisks闲鱼助手:正在停止后台服务") + if err := quitTray(); err != nil { + log.Printf("退出托盘停止服务失败: %v", err) + statusItem.SetTitle("托盘状态:退出失败") + systray.SetTooltip(fmt.Sprintf("Ydisks闲鱼助手:后台服务停止失败:%v", err)) + setMenuItemsDisabled(false, actionItems...) + return + } + if err := waitForService(&http.Client{Timeout: 2 * time.Second}, false, 30*time.Second); err != nil { + log.Printf("退出托盘等待服务停止失败: %v", err) + statusItem.SetTitle("托盘状态:退出失败") + systray.SetTooltip(fmt.Sprintf("Ydisks闲鱼助手:后台服务仍未退出:%v", err)) + setMenuItemsDisabled(false, actionItems...) + return + } + systray.SetTooltip("Ydisks闲鱼助手:后台服务已退出") + exitRequested.Store(true) + systray.Quit() +} + +func setMenuItemsDisabled(disabled bool, items ...*systray.MenuItem) { + for _, item := range items { + if disabled { + item.Disable() + } else { + item.Enable() + } + } +} + +func waitForService(client *http.Client, wantRunning bool, timeout time.Duration) error { + deadline := time.Now().Add(timeout) + for { + health, reachable, err := probeHealth(client) + running := reachable && err == nil && health.Status == "ok" && health.Database == "ok" + if wantRunning && running { + return nil + } + // “已停止”要求监听端口确实不可达。服务仍能返回异常状态或非 2xx + // 响应时,进程仍然存在,不能让托盘提前退出。 + if !wantRunning && !reachable { + return nil + } + if time.Now().After(deadline) { + if wantRunning { + return fmt.Errorf("等待后台服务启动超时") + } + return fmt.Errorf("等待后台服务退出超时") + } + time.Sleep(250 * time.Millisecond) + } } func readHealth(client *http.Client) (healthResponse, error) { + health, _, err := probeHealth(client) + return health, err +} + +func probeHealth(client *http.Client) (healthResponse, bool, error) { resp, err := client.Get(serviceURL + "/health") if err != nil { - return healthResponse{}, err + return healthResponse{}, false, err } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode >= 300 { - return healthResponse{}, fmt.Errorf("health status %d", resp.StatusCode) + return healthResponse{}, true, fmt.Errorf("health status %d", resp.StatusCode) } var health healthResponse if err := json.NewDecoder(resp.Body).Decode(&health); err != nil { - return healthResponse{}, err + return healthResponse{}, true, err } - return health, nil + return health, true, nil } func openURL(url string) error { @@ -133,6 +339,24 @@ func openURL(url string) error { return exec.Command("open", url).Start() } +func openLogDirectory() error { + directory, err := logDirectoryPath() + if err != nil { + return err + } + if err := os.MkdirAll(directory, 0o755); err != nil { + return fmt.Errorf("创建日志目录失败: %w", err) + } + switch runtime.GOOS { + case "windows": + return exec.Command("explorer.exe", directory).Start() + case "darwin": + return exec.Command("open", directory).Start() + default: + return exec.Command("xdg-open", directory).Start() + } +} + func envOr(name, fallback string) string { if value := strings.TrimSpace(os.Getenv(name)); value != "" { return value diff --git a/cmd/tray/main_test.go b/cmd/tray/main_test.go new file mode 100644 index 0000000..61949d0 --- /dev/null +++ b/cmd/tray/main_test.go @@ -0,0 +1,66 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "testing" + "time" +) + +func TestWaitForServiceRequiresHealthyResponse(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"status":"degraded","database":"error"}`)) + })) + t.Cleanup(server.Close) + originalURL := serviceURL + serviceURL = server.URL + t.Cleanup(func() { serviceURL = originalURL }) + + client := server.Client() + if err := waitForService(client, true, 20*time.Millisecond); err == nil { + t.Fatal("degraded health response must not count as running") + } +} + +func TestWaitForServiceAcceptsHealthyResponse(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"status":"ok","database":"ok"}`)) + })) + t.Cleanup(server.Close) + originalURL := serviceURL + serviceURL = server.URL + t.Cleanup(func() { serviceURL = originalURL }) + + if err := waitForService(server.Client(), true, time.Second); err != nil { + t.Fatalf("healthy response should count as running: %v", err) + } +} + +func TestWaitForServiceDoesNotTreatUnhealthyResponseAsStopped(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusServiceUnavailable) + })) + t.Cleanup(server.Close) + originalURL := serviceURL + serviceURL = server.URL + t.Cleanup(func() { serviceURL = originalURL }) + + if err := waitForService(server.Client(), false, 20*time.Millisecond); err == nil { + t.Fatal("reachable unhealthy service must not count as stopped") + } +} + +func TestWaitForServiceAcceptsUnreachableAsStopped(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + client := server.Client() + originalURL := serviceURL + serviceURL = server.URL + t.Cleanup(func() { serviceURL = originalURL }) + server.Close() + + if err := waitForService(client, false, time.Second); err != nil { + t.Fatalf("unreachable service should count as stopped: %v", err) + } +} diff --git a/cmd/tray/service_control_darwin.go b/cmd/tray/service_control_darwin.go index 6abb89c..39fcfbb 100644 --- a/cmd/tray/service_control_darwin.go +++ b/cmd/tray/service_control_darwin.go @@ -8,6 +8,7 @@ import ( "os/exec" "path/filepath" "strings" + "time" ) func serviceAction(action string) error { @@ -22,19 +23,34 @@ func serviceAction(action string) error { plistPath := filepath.Join(home, "Library", "LaunchAgents", label+".plist") switch action { case "start": - if err := launchctl("print", target); err != nil { - if err := launchctl("bootstrap", domain, plistPath); err != nil { + if err := launchctl("print", target); err == nil { + if err := launchctl("kickstart", target); err == nil { + return nil + } + // launchd 可能仍保留一个正在退出的旧 job;先完整卸载, + // 等它消失后再 bootstrap,避免第二次启动报 Input/output error。 + _ = launchctl("bootout", target) + if err := waitForLaunchctlGone(target, 10*time.Second); err != nil { return err } } + if err := launchctl("bootstrap", domain, plistPath); err != nil { + return err + } return launchctl("kickstart", target) case "stop": if err := launchctl("print", target); err != nil { return nil } - return launchctl("bootout", target) + if err := launchctl("bootout", target); err != nil { + return err + } + return waitForLaunchctlGone(target, 10*time.Second) case "restart": _ = launchctl("bootout", target) + if err := waitForLaunchctlGone(target, 10*time.Second); err != nil { + return err + } if err := launchctl("bootstrap", domain, plistPath); err != nil { return err } @@ -44,13 +60,35 @@ func serviceAction(action string) error { } } -func quitTray() error { - label := envOr("XIANYU_TRAY_SERVICE_NAME", "com.ydisks.xianyu-helper.tray") - target := "gui/" + fmt.Sprint(os.Getuid()) + "/" + label - if err := launchctl("print", target); err != nil { - return nil +func waitForLaunchctlGone(target string, timeout time.Duration) error { + deadline := time.Now().Add(timeout) + for { + if err := launchctl("print", target); err != nil { + return nil + } + if time.Now().After(deadline) { + return fmt.Errorf("等待 LaunchAgent 退出超时: %s", target) + } + time.Sleep(200 * time.Millisecond) } - return launchctl("bootout", target) +} + +func quitTray() error { + if err := serviceAction("stop"); err != nil { + return fmt.Errorf("停止后台服务失败: %w", err) + } + // 不要从托盘进程内部 bootout 自己的 LaunchAgent。launchctl 可能会先 + // 卸载 job 再留下当前进程,导致旧托盘残留而新托盘无法正确接管。 + // KeepAlive=false,随后由 systray.Quit() 正常退出进程即可。 + return nil +} + +func logDirectoryPath() (string, error) { + home, err := os.UserHomeDir() + if err != nil { + return "", fmt.Errorf("获取用户目录失败: %w", err) + } + return filepath.Join(home, "Library", "Logs", "YdisksXianyuHelper"), nil } func launchctl(args ...string) error { diff --git a/cmd/tray/service_control_other.go b/cmd/tray/service_control_other.go index 9ae6c5f..6cbca54 100644 --- a/cmd/tray/service_control_other.go +++ b/cmd/tray/service_control_other.go @@ -2,10 +2,17 @@ package main -import "fmt" +import ( + "fmt" + "path/filepath" +) func serviceAction(action string) error { return fmt.Errorf("当前平台不支持托盘服务操作: %s", action) } func quitTray() error { return nil } + +func logDirectoryPath() (string, error) { + return filepath.Join("/var", "log", "ydisks-xianyu-helper"), nil +} diff --git a/cmd/tray/service_control_windows.go b/cmd/tray/service_control_windows.go index db6f272..1676872 100644 --- a/cmd/tray/service_control_windows.go +++ b/cmd/tray/service_control_windows.go @@ -3,46 +3,181 @@ package main import ( + "errors" "fmt" - "os/exec" + "os" + "path/filepath" "strings" + "time" + + "golang.org/x/sys/windows" ) +const windowsServiceAccess = windows.SERVICE_QUERY_STATUS | windows.SERVICE_START | windows.SERVICE_STOP + +type windowsServiceController interface { + state() (uint32, error) + start() error + stop() error + close() +} + +type nativeWindowsServiceController struct { + handle windows.Handle +} + func serviceAction(action string) error { - name := envOr("XIANYU_SERVICE_NAME", "YdisksXianyuHelper") if action != "start" && action != "stop" && action != "restart" { return fmt.Errorf("未知服务操作: %s", action) } - quotedName := strings.ReplaceAll(name, "'", "''") - script := fmt.Sprintf(`$ErrorActionPreference = 'Stop' -function Invoke-Sc([string] $verb) { - $process = Start-Process -FilePath "$env:SystemRoot\System32\sc.exe" -ArgumentList @($verb, '%s') -Verb RunAs -WindowStyle Hidden -Wait -PassThru - if ($null -eq $process) { exit 1 } - return $process.ExitCode -} -$exitCode = 0 -switch ('%s') { - 'start' { $exitCode = Invoke-Sc 'start' } - 'stop' { $exitCode = Invoke-Sc 'stop' } - 'restart' { - $stopCode = Invoke-Sc 'stop' - if ($stopCode -ne 0 -and $stopCode -ne 1062) { exit $stopCode } - $exitCode = Invoke-Sc 'start' - } -} -exit $exitCode`, quotedName, action) - - cmd := exec.Command("powershell.exe", "-NoLogo", "-NoProfile", "-NonInteractive", "-WindowStyle", "Hidden", "-Command", script) - output, err := cmd.CombinedOutput() + name := envOr("XIANYU_SERVICE_NAME", "YdisksXianyuHelper") + controller, err := openWindowsServiceController(name) if err != nil { - message := strings.TrimSpace(string(output)) - if message == "" { - return fmt.Errorf("Windows 服务操作 %s 失败: %w", action, err) + if action == "stop" && errors.Is(err, windows.ERROR_SERVICE_DOES_NOT_EXIST) { + return nil } - return fmt.Errorf("Windows 服务操作 %s 失败: %s", action, message) + if errors.Is(err, windows.ERROR_ACCESS_DENIED) { + return fmt.Errorf("没有控制 Windows 服务的权限,请重新安装当前版本以更新服务权限") + } + return fmt.Errorf("打开 Windows 服务 %s 失败: %w", name, err) + } + defer controller.close() + + return controlWindowsService(controller, action, 30*time.Second, 250*time.Millisecond) +} + +func openWindowsServiceController(name string) (windowsServiceController, error) { + manager, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_CONNECT) + if err != nil { + return nil, err + } + defer windows.CloseServiceHandle(manager) //nolint:errcheck + + namePointer, err := windows.UTF16PtrFromString(name) + if err != nil { + return nil, err + } + handle, err := windows.OpenService(manager, namePointer, windowsServiceAccess) + if err != nil { + return nil, err + } + return &nativeWindowsServiceController{handle: handle}, nil +} + +func controlWindowsService(controller windowsServiceController, action string, timeout, pollInterval time.Duration) error { + switch action { + case "start": + return ensureWindowsServiceRunning(controller, timeout, pollInterval) + case "stop": + return ensureWindowsServiceStopped(controller, timeout, pollInterval) + case "restart": + if err := ensureWindowsServiceStopped(controller, timeout, pollInterval); err != nil { + return err + } + return ensureWindowsServiceRunning(controller, timeout, pollInterval) + default: + return fmt.Errorf("未知服务操作: %s", action) + } +} + +func ensureWindowsServiceRunning(controller windowsServiceController, timeout, pollInterval time.Duration) error { + state, err := controller.state() + if err != nil { + return fmt.Errorf("查询 Windows 服务状态失败: %w", err) + } + switch state { + case windows.SERVICE_RUNNING: + return nil + case windows.SERVICE_START_PENDING: + return waitForWindowsServiceState(controller, windows.SERVICE_RUNNING, timeout, pollInterval) + case windows.SERVICE_STOP_PENDING: + if err := waitForWindowsServiceState(controller, windows.SERVICE_STOPPED, timeout, pollInterval); err != nil { + return err + } + } + + if err := controller.start(); err != nil && !errors.Is(err, windows.ERROR_SERVICE_ALREADY_RUNNING) { + return fmt.Errorf("启动 Windows 服务失败: %w", err) + } + return waitForWindowsServiceState(controller, windows.SERVICE_RUNNING, timeout, pollInterval) +} + +func ensureWindowsServiceStopped(controller windowsServiceController, timeout, pollInterval time.Duration) error { + state, err := controller.state() + if err != nil { + return fmt.Errorf("查询 Windows 服务状态失败: %w", err) + } + switch state { + case windows.SERVICE_STOPPED: + return nil + case windows.SERVICE_STOP_PENDING: + return waitForWindowsServiceState(controller, windows.SERVICE_STOPPED, timeout, pollInterval) + case windows.SERVICE_START_PENDING: + if err := waitForWindowsServiceState(controller, windows.SERVICE_RUNNING, timeout, pollInterval); err != nil { + return err + } + } + + if err := controller.stop(); err != nil && !errors.Is(err, windows.ERROR_SERVICE_NOT_ACTIVE) { + return fmt.Errorf("停止 Windows 服务失败: %w", err) + } + return waitForWindowsServiceState(controller, windows.SERVICE_STOPPED, timeout, pollInterval) +} + +func waitForWindowsServiceState(controller windowsServiceController, expected uint32, timeout, pollInterval time.Duration) error { + deadline := time.Now().Add(timeout) + for { + state, err := controller.state() + if err != nil { + return fmt.Errorf("查询 Windows 服务状态失败: %w", err) + } + if state == expected { + return nil + } + if time.Now().After(deadline) { + return fmt.Errorf("等待 Windows 服务状态 %d 超时,当前状态 %d", expected, state) + } + time.Sleep(pollInterval) + } +} + +func (controller *nativeWindowsServiceController) state() (uint32, error) { + var status windows.SERVICE_STATUS + if err := windows.QueryServiceStatus(controller.handle, &status); err != nil { + return 0, err + } + return status.CurrentState, nil +} + +func (controller *nativeWindowsServiceController) start() error { + return windows.StartService(controller.handle, 0, nil) +} + +func (controller *nativeWindowsServiceController) stop() error { + var status windows.SERVICE_STATUS + return windows.ControlService(controller.handle, windows.SERVICE_CONTROL_STOP, &status) +} + +func (controller *nativeWindowsServiceController) close() { + _ = windows.CloseServiceHandle(controller.handle) +} + +func quitTray() error { + if err := serviceAction("stop"); err != nil { + return fmt.Errorf("停止后台服务失败: %w", err) } return nil } -func quitTray() error { return nil } +func logDirectoryPath() (string, error) { + base := strings.TrimSpace(os.Getenv("PROGRAMDATA")) + if base == "" { + var err error + base, err = os.UserConfigDir() + if err != nil { + return "", fmt.Errorf("获取 Windows 数据目录失败: %w", err) + } + } + return filepath.Join(base, "YdisksXianyuHelper", "logs"), nil +} diff --git a/cmd/tray/service_control_windows_test.go b/cmd/tray/service_control_windows_test.go new file mode 100644 index 0000000..3160193 --- /dev/null +++ b/cmd/tray/service_control_windows_test.go @@ -0,0 +1,83 @@ +//go:build windows + +package main + +import ( + "fmt" + "reflect" + "testing" + "time" + + "golang.org/x/sys/windows" +) + +type fakeWindowsServiceController struct { + states []uint32 + actions []string +} + +func (controller *fakeWindowsServiceController) state() (uint32, error) { + if len(controller.states) == 0 { + return 0, fmt.Errorf("测试状态序列为空") + } + state := controller.states[0] + if len(controller.states) > 1 { + controller.states = controller.states[1:] + } + return state, nil +} + +func (controller *fakeWindowsServiceController) start() error { + controller.actions = append(controller.actions, "start") + return nil +} + +func (controller *fakeWindowsServiceController) stop() error { + controller.actions = append(controller.actions, "stop") + return nil +} + +func (controller *fakeWindowsServiceController) close() {} + +func TestWindowsRestartWaitsForStoppedBeforeStarting(t *testing.T) { + controller := &fakeWindowsServiceController{ + states: []uint32{ + windows.SERVICE_RUNNING, + windows.SERVICE_STOP_PENDING, + windows.SERVICE_STOPPED, + windows.SERVICE_STOPPED, + windows.SERVICE_START_PENDING, + windows.SERVICE_RUNNING, + }, + } + if err := controlWindowsService(controller, "restart", time.Second, time.Millisecond); err != nil { + t.Fatalf("restart Windows service: %v", err) + } + if want := []string{"stop", "start"}; !reflect.DeepEqual(controller.actions, want) { + t.Fatalf("actions = %v, want %v", controller.actions, want) + } +} + +func TestWindowsStartWaitsForPreviousStop(t *testing.T) { + controller := &fakeWindowsServiceController{ + states: []uint32{ + windows.SERVICE_STOP_PENDING, + windows.SERVICE_STOPPED, + windows.SERVICE_START_PENDING, + windows.SERVICE_RUNNING, + }, + } + if err := controlWindowsService(controller, "start", time.Second, time.Millisecond); err != nil { + t.Fatalf("start Windows service: %v", err) + } + if want := []string{"start"}; !reflect.DeepEqual(controller.actions, want) { + t.Fatalf("actions = %v, want %v", controller.actions, want) + } +} + +func TestWindowsServiceAccessIsLimitedToStatusStartStop(t *testing.T) { + want := uint32(windows.SERVICE_QUERY_STATUS | windows.SERVICE_START | windows.SERVICE_STOP) + if windowsServiceAccess != want { + t.Fatalf("service access = %#x, want %#x", windowsServiceAccess, want) + } +} diff --git a/compose.yml b/compose.yml index 80fc5ad..0ad9660 100644 --- a/compose.yml +++ b/compose.yml @@ -45,12 +45,12 @@ services: postgres: condition: service_healthy environment: *app-env - command: ["/app/xianyu-server", "-addr", ":8080", "-ensure-admin"] + command: ["/app/xianyu-server", "-addr", ":59188", "-ensure-admin"] ports: - - "${XIANYU_BIND_ADDRESS:-0.0.0.0}:${XIANYU_HTTP_PORT:-8080}:8080" + - "${XIANYU_BIND_ADDRESS:-0.0.0.0}:${XIANYU_HTTP_PORT:-59188}:59188" volumes: *app-volumes healthcheck: - test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8080/health >/dev/null || exit 1"] + test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:59188/health >/dev/null || exit 1"] interval: 30s timeout: 5s retries: 5 diff --git a/docker-compose.debian13-postgres17.yml b/docker-compose.debian13-postgres17.yml index f765760..29cb816 100644 --- a/docker-compose.debian13-postgres17.yml +++ b/docker-compose.debian13-postgres17.yml @@ -45,12 +45,12 @@ services: postgres: condition: service_healthy environment: *app-env - command: ["/app/xianyu-server", "-addr", ":8080"] + command: ["/app/xianyu-server", "-addr", ":59188"] ports: - - "${XIANYU_BIND_ADDRESS:-0.0.0.0}:${XIANYU_HTTP_PORT:-8080}:8080" + - "${XIANYU_BIND_ADDRESS:-0.0.0.0}:${XIANYU_HTTP_PORT:-59188}:59188" volumes: *app-volumes healthcheck: - test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8080/health >/dev/null || exit 1"] + test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:59188/health >/dev/null || exit 1"] interval: 30s timeout: 5s retries: 5 diff --git a/docker-compose.functional.yml b/docker-compose.functional.yml index 734438a..42f34e4 100644 --- a/docker-compose.functional.yml +++ b/docker-compose.functional.yml @@ -121,14 +121,14 @@ services: DATABASE_URL: *mysql-url XIANYU_DATA_KEY: *data-key TZ: Asia/Shanghai - command: ["/app/xianyu-server", "-addr", ":8080", "-no-browser"] + command: ["/app/xianyu-server", "-addr", ":59188", "-no-browser"] ports: - - "28081:8080" + - "28081:59188" volumes: - app_mysql_data:/app/data - app_mysql_browser_data:/app/browser_data healthcheck: - test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8080/health >/dev/null"] + test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:59188/health >/dev/null"] interval: 5s timeout: 5s retries: 30 @@ -143,14 +143,14 @@ services: DATABASE_URL: sqlite:///app/data/xianyu-functional.db XIANYU_DATA_KEY: *data-key TZ: Asia/Shanghai - command: ["/app/xianyu-server", "-addr", ":8080", "-no-browser"] + command: ["/app/xianyu-server", "-addr", ":59188", "-no-browser"] ports: - - "28080:8080" + - "28080:59188" volumes: - app_sqlite_data:/app/data - app_sqlite_browser_data:/app/browser_data healthcheck: - test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8080/health >/dev/null"] + test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:59188/health >/dev/null"] interval: 5s timeout: 5s retries: 30 @@ -165,14 +165,14 @@ services: DATABASE_URL: *postgres-url XIANYU_DATA_KEY: *data-key TZ: Asia/Shanghai - command: ["/app/xianyu-server", "-addr", ":8080", "-no-browser"] + command: ["/app/xianyu-server", "-addr", ":59188", "-no-browser"] ports: - - "28082:8080" + - "28082:59188" volumes: - app_postgres_data:/app/data - app_postgres_browser_data:/app/browser_data healthcheck: - test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8080/health >/dev/null"] + test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:59188/health >/dev/null"] interval: 5s timeout: 5s retries: 30 diff --git a/docs/index.html b/docs/index.html index 8c8b957..7f77e2f 100644 --- a/docs/index.html +++ b/docs/index.html @@ -1120,6 +1120,7 @@
+
@@ -1141,7 +1142,7 @@ # 3. 启动应用 (会自动拉取 GHCR 镜像并初始化 PostgreSQL 17) docker compose up -d -# 4. 浏览器访问 http://localhost:8080,使用 admin 账号登录 +# 4. 浏览器访问 http://localhost:59188,使用 admin 账号登录 @@ -1154,13 +1155,38 @@ npm --prefix frontend ci npm --prefix frontend run build -# 2. 启动服务端 (默认监听 :8080) +# 2. 启动服务端 (默认监听 :59188) mkdir -p data go run ./cmd/server \ -db data/xianyu_data.db \ - -addr :8080 + -addr :59188 -# 3. 浏览器访问 http://localhost:8080,在首次初始化页面设置管理员密码 +# 3. 浏览器访问 http://localhost:59188,在首次初始化页面设置管理员密码 + + + + @@ -1212,7 +1238,27 @@
- 可以使用 -no-browser 启动参数运行纯 Go 后端与管理后台。但在没有 Chromium 的情况下,遇风控滑块自动通过能力将不可用。推荐直接使用官方 Docker 镜像(已预置 Chromium 与完整运行环境)。 + 可以使用 -no-browser 启动参数运行纯 Go 后端与管理后台,但在没有 Chromium 的情况下,遇风控滑块自动通过能力将不可用。Docker 镜像和 Windows、macOS、Linux 独立安装包都在构建阶段准备了匹配架构的 Chromium 与 Playwright runtime;Linux 安装时只补齐系统依赖,不会从 Debian 仓库重新下载浏览器。 +
+ + +
+
+ Windows、macOS 和 Linux 安装包有什么区别? + +
+
+ Windows 安装器注册 YdisksXianyuHelper Windows Service,并在当前用户登录时启动托盘;macOS 需要按 CPU 选择 arm64 或 amd64 安装包,并注册后台服务和菜单栏控制器;Linux 需要下载匹配架构的压缩包,以 root 执行 ./install.sh 注册 ydisks-xianyu-helper.service。Windows 和 macOS 托盘支持服务控制、过渡状态和打开日志目录,Linux 使用 systemd 管理,没有桌面托盘。 +
+
+ +
+
+ 桌面端首次启动和退出如何处理? + +
+
+ 桌面端服务默认使用 http://127.0.0.1:59188。首次打开管理页面时直接填写并确认管理员密码即可,不需要查找数据库路径或执行 CLI 初始化命令。托盘显示检查中、启动中、运行正常和正在停止等状态;选择退出托盘后,它会先等待后台服务确认停止,再退出自身。日志可从托盘菜单中的“打开日志目录”查看。
@@ -1273,21 +1319,17 @@