完善三平台安装包与服务控制流程
统一服务默认端口为 59188,完善 Windows 服务权限与 macOS LaunchAgent 管理。 实现 Windows 与 macOS 托盘状态机、服务启停等待、单实例保护、日志目录入口和退出前清理后台服务。 统一 Linux、Windows、macOS 与 Docker 的 Playwright Chromium runtime 构建流程,增加缓存、架构校验和 Linux 原生 runner,避免 QEMU。 完善 Windows、macOS、Linux 安装包及签名打包脚本,修正 Chromium 嵌入、服务注册和安装卸载流程。 同步 README、AGENTS、官网首页、Wiki 与前端开发文档,统一端口、初始化、服务、日志、托盘和安装说明。
This commit is contained in:
1 parent
94f4e070f6
commit
2df324647a
35 files changed
+1546
-214
No files matched your search
+1
-1
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"
|
||||
@@ -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-<revision>`,服务启动还需要同版本的 `chromium_headless_shell-<revision>`。打包前必须确认
|
||||
服务能使用包内 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
|
||||
|
||||
|
||||
+2
-2
@@ -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"]
|
||||
@@ -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 二进制:
|
||||
|
||||
|
||||
+32
-3
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
+245
-21
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
+59
-17
@@ -1120,6 +1120,7 @@
|
||||
<div class="code-tabs">
|
||||
<button class="code-tab-btn active" onclick="switchTab('docker')">🐳 Docker Compose (推荐)</button>
|
||||
<button class="code-tab-btn" onclick="switchTab('source')">🛠️ 源码构建运行</button>
|
||||
<button class="code-tab-btn" onclick="switchTab('desktop')">🖥️ 独立安装包</button>
|
||||
</div>
|
||||
|
||||
<!-- Tab Content 1: Docker -->
|
||||
@@ -1141,7 +1142,7 @@
|
||||
<span class="comment"># 3. 启动应用 (会自动拉取 GHCR 镜像并初始化 PostgreSQL 17)</span>
|
||||
<span class="command">docker compose up</span> -d
|
||||
|
||||
<span class="comment"># 4. 浏览器访问 http://localhost:8080,使用 admin 账号登录</span></code></pre>
|
||||
<span class="comment"># 4. 浏览器访问 http://localhost:59188,使用 admin 账号登录</span></code></pre>
|
||||
</div>
|
||||
|
||||
<!-- Tab Content 2: Source -->
|
||||
@@ -1154,13 +1155,38 @@
|
||||
<span class="command">npm</span> --prefix frontend ci
|
||||
<span class="command">npm</span> --prefix frontend run build
|
||||
|
||||
<span class="comment"># 2. 启动服务端 (默认监听 :8080)</span>
|
||||
<span class="comment"># 2. 启动服务端 (默认监听 :59188)</span>
|
||||
<span class="command">mkdir</span> -p data
|
||||
<span class="command">go run</span> ./cmd/server \
|
||||
-db data/xianyu_data.db \
|
||||
-addr :8080
|
||||
-addr :59188
|
||||
|
||||
<span class="comment"># 3. 浏览器访问 http://localhost:8080,在首次初始化页面设置管理员密码</span></code></pre>
|
||||
<span class="comment"># 3. 浏览器访问 http://localhost:59188,在首次初始化页面设置管理员密码</span></code></pre>
|
||||
</div>
|
||||
|
||||
<!-- Tab Content 3: Desktop packages -->
|
||||
<div id="tab-desktop" class="code-box-wrapper" style="display: none;">
|
||||
<div class="code-box-header">
|
||||
<span class="code-box-title">Windows / macOS / Linux</span>
|
||||
</div>
|
||||
<pre><code id="code-desktop"><span class="comment"># Windows</span>
|
||||
下载安装器并运行;安装器会注册 YdisksXianyuHelper 服务,并在当前用户登录时启动托盘程序。
|
||||
|
||||
<span class="comment"># macOS</span>
|
||||
根据 CPU 选择 arm64(Apple Silicon)或 amd64(Intel)安装包并运行。
|
||||
安装器会注册后台服务和菜单栏控制器。
|
||||
|
||||
<span class="comment"># Linux</span>
|
||||
下载与主机架构匹配的 amd64 或 arm64 压缩包后执行:
|
||||
<span class="command">sudo</span> ./install.sh
|
||||
|
||||
<span class="comment"># 三个平台首次启动</span>
|
||||
浏览器访问 http://127.0.0.1:59188,在首次初始化页面填写并确认管理员密码。
|
||||
安装包已经包含匹配架构的 Playwright driver、Chromium 和 headless shell,安装时只补齐系统依赖。</code></pre>
|
||||
<p style="color: var(--text-muted); margin-top: 1rem;">
|
||||
Windows 和 macOS 托盘可以启动、停止、重启服务,显示过渡状态,打开日志目录,并在退出前等待服务停止。
|
||||
Linux 使用 systemd 管理 <code>ydisks-xianyu-helper.service</code>,没有桌面托盘。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
@@ -1212,7 +1238,27 @@
|
||||
<svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/></svg>
|
||||
</div>
|
||||
<div class="faq-answer">
|
||||
可以使用 <code>-no-browser</code> 启动参数运行纯 Go 后端与管理后台。但在没有 Chromium 的情况下,遇风控滑块自动通过能力将不可用。推荐直接使用官方 Docker 镜像(已预置 Chromium 与完整运行环境)。
|
||||
可以使用 <code>-no-browser</code> 启动参数运行纯 Go 后端与管理后台,但在没有 Chromium 的情况下,遇风控滑块自动通过能力将不可用。Docker 镜像和 Windows、macOS、Linux 独立安装包都在构建阶段准备了匹配架构的 Chromium 与 Playwright runtime;Linux 安装时只补齐系统依赖,不会从 Debian 仓库重新下载浏览器。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="faq-item">
|
||||
<div class="faq-question" onclick="toggleFaq(this)">
|
||||
<span>Windows、macOS 和 Linux 安装包有什么区别?</span>
|
||||
<svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/></svg>
|
||||
</div>
|
||||
<div class="faq-answer">
|
||||
Windows 安装器注册 <code>YdisksXianyuHelper</code> Windows Service,并在当前用户登录时启动托盘;macOS 需要按 CPU 选择 arm64 或 amd64 安装包,并注册后台服务和菜单栏控制器;Linux 需要下载匹配架构的压缩包,以 root 执行 <code>./install.sh</code> 注册 <code>ydisks-xianyu-helper.service</code>。Windows 和 macOS 托盘支持服务控制、过渡状态和打开日志目录,Linux 使用 systemd 管理,没有桌面托盘。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="faq-item">
|
||||
<div class="faq-question" onclick="toggleFaq(this)">
|
||||
<span>桌面端首次启动和退出如何处理?</span>
|
||||
<svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/></svg>
|
||||
</div>
|
||||
<div class="faq-answer">
|
||||
桌面端服务默认使用 <code>http://127.0.0.1:59188</code>。首次打开管理页面时直接填写并确认管理员密码即可,不需要查找数据库路径或执行 CLI 初始化命令。托盘显示检查中、启动中、运行正常和正在停止等状态;选择退出托盘后,它会先等待后台服务确认停止,再退出自身。日志可从托盘菜单中的“打开日志目录”查看。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1273,21 +1319,17 @@
|
||||
<script>
|
||||
// Tab switching
|
||||
function switchTab(tabName) {
|
||||
const dockerTab = document.getElementById('tab-docker');
|
||||
const sourceTab = document.getElementById('tab-source');
|
||||
const tabs = {
|
||||
docker: document.getElementById('tab-docker'),
|
||||
source: document.getElementById('tab-source'),
|
||||
desktop: document.getElementById('tab-desktop')
|
||||
};
|
||||
const buttons = document.querySelectorAll('.code-tab-btn');
|
||||
|
||||
buttons.forEach(btn => btn.classList.remove('active'));
|
||||
|
||||
if (tabName === 'docker') {
|
||||
dockerTab.style.display = 'block';
|
||||
sourceTab.style.display = 'none';
|
||||
buttons[0].classList.add('active');
|
||||
} else {
|
||||
dockerTab.style.display = 'none';
|
||||
sourceTab.style.display = 'block';
|
||||
buttons[1].classList.add('active');
|
||||
}
|
||||
Object.values(tabs).forEach(tab => { tab.style.display = 'none'; });
|
||||
tabs[tabName].style.display = 'block';
|
||||
[...buttons].find(button => button.getAttribute('onclick') === `switchTab('${tabName}')`).classList.add('active');
|
||||
}
|
||||
|
||||
// Toggle FAQ
|
||||
|
||||
+22
-11
@@ -5,17 +5,28 @@
|
||||
|
||||
## 推荐上线路径
|
||||
|
||||
1. 选择并启动数据库;生产环境推荐 PostgreSQL。
|
||||
2. 设置并备份 `XIANYU_DATA_KEY`;启动服务后打开管理页面,首次填写管理员密码完成初始化。
|
||||
默认管理员用户名为 `admin`。
|
||||
3. 在“账号管理”扫码接入账号,确认账号为启用且在线状态。
|
||||
4. 在“卡密库存”建立可交付内容。
|
||||
5. 同步已有商品,或通过“商品管理”发布商品。
|
||||
6. 在“在线聊天”确认账号会话和历史消息正常,必要时发送测试文本或图片。
|
||||
7. 在“账号自动任务”配置自动评价和每日擦亮;在“自动化规则”建立付款发货、评价赠品或求评价规则。
|
||||
8. 可选:在“系统与 AI”配置模型,再为每个账号启用 AI。
|
||||
9. 建立通知渠道并绑定到账号;用测试通知验证。
|
||||
10. 用小额测试订单验证“卡密发送 → 确认发货”全过程后,再开放正式商品。
|
||||
1. 选择部署方式:Docker Compose、Linux 安装包、Windows 安装包、macOS 安装包或源码运行。
|
||||
2. Docker Compose 设置 `POSTGRES_*`、`DATABASE_URL`、`XIANYU_DATA_KEY` 和
|
||||
`XIANYU_ADMIN_PASSWORD`;其他方式启动服务后打开管理页面,在首次初始化页面填写密码。
|
||||
3. 设置并备份 `XIANYU_DATA_KEY`;默认管理员用户名为 `admin`。
|
||||
4. 在“账号管理”扫码接入账号,确认账号为启用且在线状态。
|
||||
5. 在“卡密库存”建立可交付内容。
|
||||
6. 同步已有商品,或通过“商品管理”发布商品。
|
||||
7. 在“在线聊天”确认账号会话和历史消息正常,必要时发送测试文本或图片。
|
||||
8. 在“账号自动任务”配置自动评价和每日擦亮;在“自动化规则”建立付款发货、评价赠品或求评价规则。
|
||||
9. 可选:在“系统与 AI”配置模型,再为每个账号启用 AI。
|
||||
10. 建立通知渠道并绑定到账号;用测试通知验证。
|
||||
11. 用小额测试订单验证“卡密发送 → 确认发货”全过程后,再开放正式商品。
|
||||
|
||||
桌面安装包的管理地址是 `http://127.0.0.1:59188`。Windows 和 macOS 安装包自带后台服务、托盘/菜单栏
|
||||
控制器以及匹配架构的 Playwright driver、Chromium;Linux 安装包自带相同的浏览器 runtime,
|
||||
安装脚本只补齐系统依赖。桌面托盘退出前会先停止后台服务。
|
||||
|
||||
Windows 安装包注册 `YdisksXianyuHelper` 服务;macOS 安装包分别提供 Apple Silicon(arm64)和
|
||||
Intel(amd64)版本,并注册 `com.ydisks.xianyu-helper.server` 与
|
||||
`com.ydisks.xianyu-helper.tray` 两个 LaunchAgent。Linux 安装包按 amd64/arm64 分发,执行
|
||||
`sudo ./install.sh` 后注册 `ydisks-xianyu-helper.service`。三种独立安装包都在构建阶段准备匹配架构
|
||||
的 Chromium,不依赖 Debian 仓库版本。
|
||||
|
||||
## 先读这些页面
|
||||
|
||||
|
||||
+39
-4
@@ -18,7 +18,7 @@
|
||||
3. 为 `XIANYU_DATA_KEY` 生成一次长期固定的随机值,例如 `openssl rand -base64 48`;不要在后续升级时更换。
|
||||
4. 启动:`docker compose up -d`。
|
||||
5. 查看:`docker compose ps` 和 `docker compose logs -f app`。
|
||||
6. 打开 `http://服务器地址:8080`。设置了 `XIANYU_ADMIN_PASSWORD` 时,Compose 会在首次启动
|
||||
6. 打开 `http://服务器地址:59188`。设置了 `XIANYU_ADMIN_PASSWORD` 时,Compose 会在首次启动
|
||||
自动创建 `admin`;如果使用其他方式启动且数据库尚未初始化,页面会显示初始化表单,填写
|
||||
两次不少于 8 个字符的密码即可。
|
||||
|
||||
@@ -26,12 +26,47 @@
|
||||
|
||||
Docker 中的自动续期会使用容器内 Chromium 检测到的 Linux 原生浏览器指纹请求闲鱼官网;不会因为宿主系统是 Linux 而跳过静默续期。续期结果仍以闲鱼响应和账号登录态为准。
|
||||
|
||||
## 独立安装包
|
||||
|
||||
独立安装包与 Docker 使用同一套 Playwright Chromium 版本来源:Chromium、headless shell 和
|
||||
Playwright driver 都在构建阶段下载并放入包内,不使用 Debian 仓库的 Chromium。安装时只补齐
|
||||
目标系统所需的动态库和其他系统依赖;安装后不需要用户再执行浏览器下载命令。
|
||||
|
||||
| 平台 | 安装方式 | 服务标识 | 默认地址 |
|
||||
| --- | --- | --- | --- |
|
||||
| Linux amd64/arm64 | 解压后以 root 执行 `./install.sh` | `ydisks-xianyu-helper.service` | `http://127.0.0.1:59188` |
|
||||
| Windows | 运行 Inno Setup 安装器 | `YdisksXianyuHelper` | `http://127.0.0.1:59188` |
|
||||
| macOS arm64/amd64 | 运行对应架构的 pkg 安装器 | `com.ydisks.xianyu-helper.server` | `http://127.0.0.1:59188` |
|
||||
|
||||
Windows 和 macOS 安装包还会安装独立的托盘/菜单栏控制器。控制器负责显示检查中、启动中、运行正常、
|
||||
正在停止等中间状态,启动、停止和重启后台服务,打开日志目录,并在退出前等待后台服务确认停止。
|
||||
Windows 安装阶段会授予交互式登录用户该服务的查询、启动和停止权限,因此日常托盘操作不需要
|
||||
重复确认 UAC;修改服务配置或删除服务仍需管理员权限。Linux 没有桌面托盘,使用 systemd 和
|
||||
`journalctl -u ydisks-xianyu-helper.service` 管理服务。
|
||||
|
||||
独立安装包的数据和日志位置为:Windows 的 `C:\ProgramData\YdisksXianyuHelper`,macOS 的
|
||||
`~/Library/Application Support/YdisksXianyuHelper` 与 `~/Library/Logs/YdisksXianyuHelper`,Linux 的
|
||||
`/var/lib/ydisks-xianyu-helper` 与 `/var/log/ydisks-xianyu-helper`。macOS 必须选择与 CPU 匹配的
|
||||
arm64 或 amd64 包;Linux 也必须在相同架构的主机上安装,安装脚本不使用 QEMU。
|
||||
|
||||
## 桌面端日志与操作
|
||||
|
||||
日志目录如下。Windows 和 macOS 托盘菜单还可以启动、停止或重启后台服务,打开管理页面和日志目录。
|
||||
选择“退出托盘”时,会先停止后台服务,再退出托盘控制器,避免后台进程脱离用户控制继续运行。
|
||||
Windows 安装器会在安装阶段一次性配置当前机器上该服务的最小控制权限。普通交互式登录用户之后可以从托盘查询、启动和停止 `YdisksXianyuHelper`,这些操作不需要再次确认 UAC;修改服务配置、删除服务和控制其他系统服务仍需要管理员权限。
|
||||
|
||||
- Windows:`C:\ProgramData\YdisksXianyuHelper\logs\server.log`
|
||||
- macOS:`~/Library/Logs/YdisksXianyuHelper/server.log`,托盘日志为同目录下的 `tray.log`
|
||||
- Linux:`/var/log/ydisks-xianyu-helper/server.log`,同时可用 `journalctl -u ydisks-xianyu-helper.service` 查看
|
||||
|
||||
桌面端首次使用时直接打开管理页面,在初始化页面填写并确认管理员密码即可,不需要查找数据库路径或打开终端。
|
||||
|
||||
## SQLite
|
||||
|
||||
适合开发或轻量单机。默认数据库路径为 `data/xianyu_data.db`:
|
||||
|
||||
```bash
|
||||
go run ./cmd/server -db data/xianyu_data.db -addr :8080
|
||||
go run ./cmd/server -db data/xianyu_data.db -addr :59188
|
||||
```
|
||||
|
||||
也可显式指定:
|
||||
@@ -48,7 +83,7 @@ DATABASE_URL="sqlite://data/xianyu_data.db" ./xianyu-server
|
||||
|
||||
```bash
|
||||
DATABASE_URL="mysql://user:URL编码后的密码@tcp(db.example:3306)/xianyu" \
|
||||
./xianyu-server -addr :8080
|
||||
./xianyu-server -addr :59188
|
||||
```
|
||||
|
||||
应用会补齐所需 MySQL 连接参数。密码中出现 `@`、`:`、`/` 等字符时必须 URL 编码。使用 TLS 的环境请按数据库驱动/基础设施要求配置安全连接,不要把真实密码写进命令历史。
|
||||
@@ -57,7 +92,7 @@ DATABASE_URL="mysql://user:URL编码后的密码@tcp(db.example:3306)/xianyu" \
|
||||
|
||||
```bash
|
||||
DATABASE_URL="postgres://user:URL编码后的密码@db.example:5432/xianyu?sslmode=require" \
|
||||
./xianyu-server -addr :8080
|
||||
./xianyu-server -addr :59188
|
||||
```
|
||||
|
||||
仅在受信任的本机网络可考虑 `sslmode=disable`;公网或跨网络部署应使用 TLS。数据库账号只应拥有该应用数据库的必要权限。
|
||||
|
||||
+5
-3
@@ -13,7 +13,7 @@ frontend/
|
||||
services/ 后端 API 封装(fetch 调用)
|
||||
request.ts 统一请求工具(带 session cookie、错误处理)
|
||||
types.ts 共享类型定义
|
||||
vite.config.ts Vite 配置(base=/static/,代理 /api 到 :8080)
|
||||
vite.config.ts Vite 配置(base=/static/,代理 /api 到 :59188)
|
||||
```
|
||||
|
||||
## 开发
|
||||
@@ -21,10 +21,12 @@ frontend/
|
||||
```bash
|
||||
cd /Users/christ/Workspace/git/xianyu/Ydisks-Xianyu-Helper/frontend
|
||||
npm install
|
||||
npm run dev # http://localhost:3000,API 代理到 localhost:8080
|
||||
npm run dev # http://localhost:3000,API 代理到 localhost:59188
|
||||
```
|
||||
|
||||
开发时先启动后端(`go run ./cmd/server -addr :8080`),再启动前端 dev server。
|
||||
开发时先启动后端(默认端口为 `59188`;桌面安装包绑定 `127.0.0.1`,源码运行可按需指定监听地址),
|
||||
例如 `go run ./cmd/server -addr :59188`,再启动前端 dev server。
|
||||
这里的 `localhost:3000` 仅是 Vite 开发服务器地址,不是应用服务端口。
|
||||
|
||||
## 构建产物
|
||||
|
||||
|
||||
+27
-27
@@ -10,113 +10,113 @@ export default defineConfig({
|
||||
proxy: {
|
||||
// 代理API请求到后端
|
||||
'/api': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
ws: true,
|
||||
},
|
||||
// 代理其他后端请求
|
||||
'/cookies': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/account': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/qr-login': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/password-login': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/keywords': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/keywords-with-item-id': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/default-reply': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/items': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/cards': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/automation-rules': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/automation-issues': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/automation-runs': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/automation-pending-tasks': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/notification-channels': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/message-notifications': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/ai-reply-settings': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/ai-models': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/system-settings': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/user-settings': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/admin': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/analytics': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/login': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/verify': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/logout': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/change-password': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/health': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
|
||||
@@ -5,6 +5,7 @@ APP_NAME="ydisks-xianyu-helper"
|
||||
INSTALL_DIR="/opt/$APP_NAME"
|
||||
DATA_DIR="/var/lib/$APP_NAME"
|
||||
CONFIG_DIR="/etc/$APP_NAME"
|
||||
LOG_DIR="/var/log/$APP_NAME"
|
||||
SERVICE_NAME="$APP_NAME.service"
|
||||
SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
|
||||
|
||||
@@ -55,6 +56,7 @@ fi
|
||||
systemctl stop "$SERVICE_NAME" >/dev/null 2>&1 || true
|
||||
install -d -m 0755 "$INSTALL_DIR"
|
||||
install -d -o "$APP_NAME" -g "$APP_NAME" -m 0750 "$DATA_DIR"
|
||||
install -d -o "$APP_NAME" -g "$APP_NAME" -m 0750 "$LOG_DIR"
|
||||
rm -rf "$INSTALL_DIR/playwright-runtime"
|
||||
install -d -m 0755 "$INSTALL_DIR/playwright-runtime"
|
||||
cp -R "$RUNTIME_SOURCE/." "$INSTALL_DIR/playwright-runtime/"
|
||||
|
||||
@@ -9,7 +9,8 @@ User=ydisks-xianyu
|
||||
Group=ydisks-xianyu
|
||||
WorkingDirectory=/var/lib/ydisks-xianyu-helper
|
||||
EnvironmentFile=-/etc/ydisks-xianyu-helper/config.env
|
||||
ExecStart=/opt/ydisks-xianyu-helper/xianyu-server -addr 127.0.0.1:8080 -workdir /var/lib/ydisks-xianyu-helper -data-key-file /var/lib/ydisks-xianyu-helper/data-key -playwright-runtime-root /opt/ydisks-xianyu-helper/playwright-runtime
|
||||
Environment=XIANYU_LOG_DIR=/var/log/ydisks-xianyu-helper
|
||||
ExecStart=/opt/ydisks-xianyu-helper/xianyu-server -addr 127.0.0.1:59188 -workdir /var/lib/ydisks-xianyu-helper -data-key-file /var/lib/ydisks-xianyu-helper/data-key -playwright-runtime-root /opt/ydisks-xianyu-helper/playwright-runtime
|
||||
Restart=on-failure
|
||||
RestartSec=5s
|
||||
KillSignal=SIGTERM
|
||||
|
||||
@@ -22,9 +22,30 @@ if [ ! -x "$BIN_DIR/xianyu-server" ] || [ ! -x "$BIN_DIR/xianyu-tray" ]; then
|
||||
echo "缺少 $ARCH 架构的桌面二进制:$BIN_DIR" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ ! -d "$DIST_DIR/playwright-runtime/$ARCH/playwright-driver" ] || \
|
||||
[ ! -d "$DIST_DIR/playwright-runtime/$ARCH/playwright-browsers" ]; then
|
||||
echo "缺少 $ARCH 架构的 Playwright runtime:$DIST_DIR/playwright-runtime/$ARCH" >&2
|
||||
case "$ARCH" in
|
||||
arm64) PLATFORM_ARCH="arm64" ;;
|
||||
amd64) PLATFORM_ARCH="x64" ;;
|
||||
esac
|
||||
runtime_dir="$DIST_DIR/playwright-runtime/$ARCH"
|
||||
runtime_has_chromium() {
|
||||
find "$runtime_dir/playwright-browsers" -type f \
|
||||
-path "*/chrome-mac-$PLATFORM_ARCH/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing" \
|
||||
-print -quit 2>/dev/null | grep -q .
|
||||
}
|
||||
runtime_has_headless_shell() {
|
||||
find "$runtime_dir/playwright-browsers" -type f \
|
||||
-path "*/chrome-headless-shell-mac-$PLATFORM_ARCH/chrome-headless-shell" \
|
||||
-print -quit 2>/dev/null | grep -q .
|
||||
}
|
||||
if [ ! -d "$runtime_dir/playwright-driver" ] || \
|
||||
[ ! -d "$runtime_dir/playwright-browsers" ] || \
|
||||
! runtime_has_chromium || ! runtime_has_headless_shell; then
|
||||
echo "未找到完整的 $ARCH Playwright runtime,尝试从本机缓存准备。" >&2
|
||||
"$SCRIPT_DIR/prepare-runtime.sh" "$ARCH" "$runtime_dir"
|
||||
fi
|
||||
|
||||
if ! runtime_has_chromium || ! runtime_has_headless_shell; then
|
||||
echo "Playwright runtime 缺少 $ARCH 架构的 Chromium 或 headless shell。" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<key>ProgramArguments</key>
|
||||
<array>
|
||||
<string>__SERVER__</string>
|
||||
<string>-addr</string><string>127.0.0.1:8080</string>
|
||||
<string>-addr</string><string>127.0.0.1:59188</string>
|
||||
<string>-playwright-runtime-root</string><string>__RUNTIME_ROOT__</string>
|
||||
</array>
|
||||
<key>WorkingDirectory</key><string>__DATA_DIR__</string>
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
<key>Label</key><string>com.ydisks.xianyu-helper.tray</string>
|
||||
<key>ProgramArguments</key><array><string>__TRAY__</string></array>
|
||||
<key>RunAtLoad</key><true/>
|
||||
<key>StandardOutPath</key><string>__LOG_DIR__/tray.log</string>
|
||||
<key>StandardErrorPath</key><string>__LOG_DIR__/tray.log</string>
|
||||
<!-- 托盘允许用户退出;服务端 LaunchAgent 单独负责 KeepAlive。 -->
|
||||
<key>KeepAlive</key><false/>
|
||||
</dict>
|
||||
|
||||
Executable
+72
@@ -0,0 +1,72 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
# 将本机 Playwright 缓存整理成 macOS 安装包使用的固定 runtime 目录。
|
||||
# CI 通过 browser-install 下载 runtime;本地打包直接复用同一版本的缓存,
|
||||
# 不需要再次访问 npm 或 Chromium 下载地址。
|
||||
|
||||
ARCH="${1:?architecture is required (arm64 or amd64)}"
|
||||
DEST_DIR="${2:?runtime destination is required}"
|
||||
|
||||
case "$ARCH" in
|
||||
arm64) PLATFORM_ARCH="arm64" ;;
|
||||
amd64) PLATFORM_ARCH="x64" ;;
|
||||
*) echo "不支持的 macOS 架构:$ARCH" >&2; exit 1 ;;
|
||||
esac
|
||||
|
||||
PLAYWRIGHT_GO_CACHE="${PLAYWRIGHT_GO_CACHE:-${HOME:?}/Library/Caches/ms-playwright-go}"
|
||||
PLAYWRIGHT_BROWSER_CACHE="${PLAYWRIGHT_BROWSER_CACHE:-${HOME:?}/Library/Caches/ms-playwright}"
|
||||
|
||||
if [ ! -d "$PLAYWRIGHT_GO_CACHE" ]; then
|
||||
echo "找不到 Playwright Go 缓存:$PLAYWRIGHT_GO_CACHE" >&2
|
||||
echo "请先运行 browser-install,或设置 PLAYWRIGHT_GO_CACHE。" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ ! -d "$PLAYWRIGHT_BROWSER_CACHE" ]; then
|
||||
echo "找不到 Playwright 浏览器缓存:$PLAYWRIGHT_BROWSER_CACHE" >&2
|
||||
echo "请先运行 browser-install,或设置 PLAYWRIGHT_BROWSER_CACHE。" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
DRIVER_DIR=""
|
||||
for candidate in "$PLAYWRIGHT_GO_CACHE"/[0-9]*; do
|
||||
if [ -d "$candidate/package" ] && [ -x "$candidate/node" ]; then
|
||||
DRIVER_DIR="$candidate"
|
||||
fi
|
||||
done
|
||||
if [ -z "$DRIVER_DIR" ]; then
|
||||
echo "Playwright Go 缓存中没有可用 driver:$PLAYWRIGHT_GO_CACHE" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
BROWSER_DIR=""
|
||||
HEADLESS_DIR=""
|
||||
for candidate in "$PLAYWRIGHT_BROWSER_CACHE"/chromium-[0-9]*; do
|
||||
[ -d "$candidate" ] || continue
|
||||
revision="${candidate##*/chromium-}"
|
||||
chrome="$candidate/chrome-mac-$PLATFORM_ARCH/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"
|
||||
headless="$PLAYWRIGHT_BROWSER_CACHE/chromium_headless_shell-$revision/chrome-headless-shell-mac-$PLATFORM_ARCH/chrome-headless-shell"
|
||||
if [ -f "$chrome" ] && [ -f "$headless" ]; then
|
||||
BROWSER_DIR="$candidate"
|
||||
HEADLESS_DIR="$PLAYWRIGHT_BROWSER_CACHE/chromium_headless_shell-$revision"
|
||||
fi
|
||||
done
|
||||
if [ -z "$BROWSER_DIR" ]; then
|
||||
echo "Playwright 浏览器缓存中没有 $ARCH 架构的 Chromium/headless shell:$PLAYWRIGHT_BROWSER_CACHE" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
revision="${BROWSER_DIR##*/chromium-}"
|
||||
if ! grep -q '"revision": "'"$revision"'"' "$DRIVER_DIR/package/browsers.json"; then
|
||||
echo "Playwright driver 与 Chromium revision 不匹配:driver=$DRIVER_DIR,browser=$revision" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
rm -rf "$DEST_DIR/playwright-driver" "$DEST_DIR/playwright-browsers"
|
||||
mkdir -p "$DEST_DIR"
|
||||
cp -R "$DRIVER_DIR" "$DEST_DIR/playwright-driver"
|
||||
mkdir -p "$DEST_DIR/playwright-browsers"
|
||||
cp -R "$BROWSER_DIR" "$DEST_DIR/playwright-browsers/"
|
||||
cp -R "$HEADLESS_DIR" "$DEST_DIR/playwright-browsers/"
|
||||
|
||||
echo "已从本机缓存准备 macOS $ARCH Playwright runtime:revision=$revision"
|
||||
@@ -56,7 +56,8 @@ fi
|
||||
echo "使用 $RUNTIME_ARCH 架构的 Playwright runtime。"
|
||||
|
||||
mkdir -p "$DATA_DIR" "$LOG_DIR" "$AGENT_DIR"
|
||||
chown -R "$CONSOLE_USER" "$DATA_DIR" "$LOG_DIR" "$AGENT_DIR"
|
||||
chown -R "$CONSOLE_USER" "$DATA_DIR" "$LOG_DIR"
|
||||
chown "$CONSOLE_USER" "$AGENT_DIR"
|
||||
|
||||
escape_sed() {
|
||||
printf '%s' "$1" | sed 's/[&|]/\\&/g'
|
||||
@@ -78,6 +79,7 @@ sed -e "s|__SERVER__|$SERVER_ESCAPED|g" \
|
||||
-e "s|__RUNTIME_ROOT__|$RUNTIME_ROOT_ESCAPED|g" \
|
||||
"$APP/Contents/Resources/com.ydisks.xianyu-helper.server.plist.template" > "$server_plist"
|
||||
sed -e "s|__TRAY__|$TRAY_ESCAPED|g" \
|
||||
-e "s|__LOG_DIR__|$LOG_ESCAPED|g" \
|
||||
"$APP/Contents/Resources/com.ydisks.xianyu-helper.tray.plist.template" > "$tray_plist"
|
||||
chown "$CONSOLE_USER" "$server_plist" "$tray_plist"
|
||||
chmod 0644 "$server_plist" "$tray_plist"
|
||||
@@ -85,6 +87,24 @@ chmod 0644 "$server_plist" "$tray_plist"
|
||||
launchctl bootout "gui/$UID_VALUE/$SERVER_LABEL" >/dev/null 2>&1 || true
|
||||
launchctl bootout "gui/$UID_VALUE/$TRAY_LABEL" >/dev/null 2>&1 || true
|
||||
|
||||
# 旧版本的托盘曾经可能在 bootout 后脱离 launchd 继续存活。它仍然占用
|
||||
# 菜单栏并使用旧的控制逻辑,会让升级后的第二次启动看起来像启动失败。
|
||||
# 这里只按当前应用的绝对路径清理旧托盘,不影响其它程序。
|
||||
STALE_TRAY_PIDS="$(ps -axo pid=,command= | awk -v target="$TRAY" '$2 == target {print $1}')"
|
||||
for stale_pid in $STALE_TRAY_PIDS; do
|
||||
if [ "$stale_pid" != "$$" ] && [ -n "$stale_pid" ]; then
|
||||
kill -TERM "$stale_pid" >/dev/null 2>&1 || true
|
||||
fi
|
||||
done
|
||||
if [ -n "$STALE_TRAY_PIDS" ]; then
|
||||
sleep 1
|
||||
for stale_pid in $STALE_TRAY_PIDS; do
|
||||
if [ "$stale_pid" != "$$" ] && kill -0 "$stale_pid" >/dev/null 2>&1; then
|
||||
kill -KILL "$stale_pid" >/dev/null 2>&1 || true
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
# 清理早期版本使用的个人域名标识,避免升级后新旧 LaunchAgent 同时运行。
|
||||
LEGACY_SERVER_LABEL="com.christ.ydisks-xianyu-helper.server"
|
||||
LEGACY_TRAY_LABEL="com.christ.ydisks-xianyu-helper.tray"
|
||||
@@ -94,5 +114,6 @@ rm -f "$AGENT_DIR/$LEGACY_SERVER_LABEL.plist" "$AGENT_DIR/$LEGACY_TRAY_LABEL.pli
|
||||
|
||||
launchctl bootstrap "gui/$UID_VALUE" "$server_plist"
|
||||
launchctl bootstrap "gui/$UID_VALUE" "$tray_plist"
|
||||
launchctl kickstart -k "gui/$UID_VALUE/$SERVER_LABEL"
|
||||
launchctl kickstart -k "gui/$UID_VALUE/$TRAY_LABEL"
|
||||
# bootstrap 会根据 RunAtLoad 自动启动两个 LaunchAgent。这里不能再调用
|
||||
# kickstart -k:它会给刚由 bootstrap 启动的托盘发送 SIGTERM,托盘会按
|
||||
# 正常退出流程停止服务,导致安装完成后第一次启动就被自己关掉。
|
||||
@@ -25,18 +25,39 @@ Source: "..\..\dist\windows\xianyu-server.exe"; DestDir: "{app}"; Flags: ignorev
|
||||
Source: "..\..\dist\windows\xianyu-tray.exe"; DestDir: "{app}"; Flags: ignoreversion
|
||||
Source: "..\..\icon\windows\icon.ico"; DestDir: "{app}"; Flags: ignoreversion
|
||||
Source: "..\..\dist\windows\playwright-runtime\*"; DestDir: "{app}\playwright-runtime"; Flags: recursesubdirs createallsubdirs ignoreversion
|
||||
Source: "service-control.ps1"; Flags: dontcopy
|
||||
Source: "service-control.ps1"; DestDir: "{app}"; Flags: ignoreversion
|
||||
|
||||
[Dirs]
|
||||
Name: "{#AppDataDir}"
|
||||
Name: "{#AppDataDir}\data"
|
||||
Name: "{#AppDataDir}\logs"; Permissions: users-modify
|
||||
|
||||
[Registry]
|
||||
Root: HKCU; Subkey: "Software\Microsoft\Windows\CurrentVersion\Run"; ValueType: string; ValueName: "YdisksXianyuHelperTray"; ValueData: "{app}\xianyu-tray.exe"; Flags: uninsdeletevalue
|
||||
Root: HKCU; Subkey: "Software\Microsoft\Windows\CurrentVersion\Run"; ValueType: string; ValueName: "YdisksXianyuHelperTray"; ValueData: """{app}\xianyu-tray.exe"""; Flags: uninsdeletevalue
|
||||
|
||||
[Run]
|
||||
Filename: "{sys}\sc.exe"; Parameters: "create YdisksXianyuHelper binPath= ""{app}\xianyu-server.exe"" -service -workdir {#AppDataDir} -data-key-file {#AppDataDir}\data-key -addr 127.0.0.1:8080 -playwright-runtime-root ""{app}\playwright-runtime"" start= delayed-auto"; Flags: runhidden waituntilterminated
|
||||
Filename: "{sys}\sc.exe"; Parameters: "start YdisksXianyuHelper"; Flags: runhidden waituntilterminated
|
||||
Filename: "{app}\xianyu-tray.exe"; Description: "启动菜单栏控制器"; Flags: nowait postinstall skipifsilent
|
||||
Filename: "{sys}\WindowsPowerShell\v1.0\powershell.exe"; Parameters: "-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File ""{app}\service-control.ps1"" -Mode install -ExePath ""{app}\xianyu-server.exe"" -TrayPath ""{app}\xianyu-tray.exe"" -WorkDir ""{#AppDataDir}"" -RuntimeRoot ""{app}\playwright-runtime"""; Flags: runhidden waituntilterminated
|
||||
Filename: "{app}\xianyu-tray.exe"; Description: "启动菜单栏控制器"; Flags: nowait postinstall skipifsilent runasoriginaluser
|
||||
|
||||
[UninstallRun]
|
||||
Filename: "{sys}\sc.exe"; Parameters: "stop YdisksXianyuHelper"; Flags: runhidden waituntilterminated
|
||||
Filename: "{sys}\sc.exe"; Parameters: "delete YdisksXianyuHelper"; Flags: runhidden waituntilterminated
|
||||
Filename: "{sys}\WindowsPowerShell\v1.0\powershell.exe"; Parameters: "-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File ""{app}\service-control.ps1"" -Mode uninstall -TrayPath ""{app}\xianyu-tray.exe"""; Flags: runhidden waituntilterminated
|
||||
|
||||
[Code]
|
||||
function PrepareToInstall(var NeedsRestart: Boolean): String;
|
||||
var
|
||||
ResultCode: Integer;
|
||||
begin
|
||||
Result := '';
|
||||
ExtractTemporaryFile('service-control.ps1');
|
||||
if not Exec(
|
||||
ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'),
|
||||
'-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "' +
|
||||
ExpandConstant('{tmp}\service-control.ps1') + '" -Mode stop -TrayPath "' +
|
||||
ExpandConstant('{app}\xianyu-tray.exe') + '"',
|
||||
'', SW_HIDE, ewWaitUntilTerminated, ResultCode)
|
||||
then
|
||||
Result := '无法执行旧服务停止脚本。'
|
||||
else if ResultCode <> 0 then
|
||||
Result := '旧版后台服务停止失败,错误码:' + IntToStr(ResultCode) + '。';
|
||||
end;
|
||||
@@ -0,0 +1,134 @@
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[ValidateSet('stop', 'install', 'uninstall')]
|
||||
[string]$Mode,
|
||||
|
||||
[string]$ServiceName = 'YdisksXianyuHelper',
|
||||
[string]$ExePath = '',
|
||||
[string]$TrayPath = '',
|
||||
[string]$WorkDir = '',
|
||||
[string]$RuntimeRoot = ''
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
function Get-InstalledService {
|
||||
Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
|
||||
}
|
||||
|
||||
function Stop-InstalledService {
|
||||
$service = Get-InstalledService
|
||||
if ($null -eq $service) {
|
||||
return
|
||||
}
|
||||
if ($service.Status -ne [System.ServiceProcess.ServiceControllerStatus]::Stopped) {
|
||||
Stop-Service -Name $ServiceName -ErrorAction Stop
|
||||
$service.WaitForStatus(
|
||||
[System.ServiceProcess.ServiceControllerStatus]::Stopped,
|
||||
[TimeSpan]::FromSeconds(30)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function Stop-InstalledTray {
|
||||
if ([string]::IsNullOrWhiteSpace($TrayPath)) {
|
||||
return
|
||||
}
|
||||
$normalizedTrayPath = [IO.Path]::GetFullPath($TrayPath)
|
||||
Get-Process -Name 'xianyu-tray' -ErrorAction SilentlyContinue | ForEach-Object {
|
||||
$processPath = $null
|
||||
try {
|
||||
$processPath = $_.Path
|
||||
} catch {
|
||||
$processPath = $null
|
||||
}
|
||||
if (-not [string]::IsNullOrWhiteSpace($processPath) -and
|
||||
[StringComparer]::OrdinalIgnoreCase.Equals(
|
||||
[IO.Path]::GetFullPath($processPath),
|
||||
$normalizedTrayPath
|
||||
)) {
|
||||
Stop-Process -Id $_.Id -Force -ErrorAction Stop
|
||||
if (-not $_.WaitForExit(10000)) {
|
||||
throw "等待旧托盘进程退出超时: $($_.Id)"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Stop-InstalledComponents {
|
||||
Stop-InstalledTray
|
||||
Stop-InstalledService
|
||||
}
|
||||
|
||||
function Invoke-ScChecked {
|
||||
param([Parameter(ValueFromRemainingArguments = $true)][string[]]$Arguments)
|
||||
|
||||
$output = & "$env:SystemRoot\System32\sc.exe" @Arguments 2>&1
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "sc.exe $($Arguments -join ' ') 失败 ($LASTEXITCODE): $($output -join ' ')"
|
||||
}
|
||||
}
|
||||
|
||||
function Grant-InteractiveUserServiceControl {
|
||||
# IU(INTERACTIVE)只包含当前交互式登录会话。授予的 LCRPWP 分别是
|
||||
# 查询状态、启动和停止;不包含修改配置、修改 ACL 或删除服务。
|
||||
$controlAce = '(A;;LCRPWP;;;IU)'
|
||||
$output = & "$env:SystemRoot\System32\sc.exe" sdshow $ServiceName 2>&1
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "读取服务安全描述符失败 ($LASTEXITCODE): $($output -join ' ')"
|
||||
}
|
||||
$sddl = $output |
|
||||
ForEach-Object { $_.ToString().Trim() } |
|
||||
Where-Object { $_ -like 'D:*' } |
|
||||
Select-Object -First 1
|
||||
if ([string]::IsNullOrWhiteSpace($sddl)) {
|
||||
throw '服务安全描述符中没有找到 DACL'
|
||||
}
|
||||
if ($sddl.Contains($controlAce)) {
|
||||
return
|
||||
}
|
||||
|
||||
$saclIndex = $sddl.IndexOf('S:')
|
||||
if ($saclIndex -ge 0) {
|
||||
$updatedSddl = $sddl.Insert($saclIndex, $controlAce)
|
||||
} else {
|
||||
$updatedSddl = $sddl + $controlAce
|
||||
}
|
||||
Invoke-ScChecked sdset $ServiceName $updatedSddl
|
||||
}
|
||||
|
||||
switch ($Mode) {
|
||||
'stop' {
|
||||
Stop-InstalledComponents
|
||||
}
|
||||
'install' {
|
||||
if ([string]::IsNullOrWhiteSpace($ExePath) -or
|
||||
[string]::IsNullOrWhiteSpace($WorkDir) -or
|
||||
[string]::IsNullOrWhiteSpace($RuntimeRoot)) {
|
||||
throw '安装服务缺少 ExePath、WorkDir 或 RuntimeRoot'
|
||||
}
|
||||
|
||||
Stop-InstalledComponents
|
||||
$binaryPath = '"{0}" -service -workdir "{1}" -data-key-file "{1}\data-key" -addr 127.0.0.1:59188 -playwright-runtime-root "{2}"' -f `
|
||||
$ExePath, $WorkDir, $RuntimeRoot
|
||||
if ($null -eq (Get-InstalledService)) {
|
||||
Invoke-ScChecked create $ServiceName 'binPath=' $binaryPath 'start=' 'delayed-auto'
|
||||
} else {
|
||||
Invoke-ScChecked config $ServiceName 'binPath=' $binaryPath 'start=' 'delayed-auto'
|
||||
}
|
||||
Invoke-ScChecked description $ServiceName 'Ydisks闲鱼助手后台服务'
|
||||
Grant-InteractiveUserServiceControl
|
||||
|
||||
Start-Service -Name $ServiceName -ErrorAction Stop
|
||||
(Get-Service -Name $ServiceName).WaitForStatus(
|
||||
[System.ServiceProcess.ServiceControllerStatus]::Running,
|
||||
[TimeSpan]::FromSeconds(30)
|
||||
)
|
||||
}
|
||||
'uninstall' {
|
||||
Stop-InstalledComponents
|
||||
if ($null -ne (Get-InstalledService)) {
|
||||
Invoke-ScChecked delete $ServiceName
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -61,6 +61,6 @@ test_instance() {
|
||||
printf '%s functional test passed\n' "$name"
|
||||
}
|
||||
|
||||
test_instance sqlite http://app-sqlite:8080
|
||||
test_instance mysql http://app-mysql:8080
|
||||
test_instance postgres http://app-postgres:8080
|
||||
test_instance sqlite http://app-sqlite:59188
|
||||
test_instance mysql http://app-mysql:59188
|
||||
test_instance postgres http://app-postgres:59188
|
||||
Reference in new issue
Block a user