feat: 增加桌面端安装包与分支专用 CI/CD

拆分后台服务、浏览器安装器和桌面托盘控制器,支持 Windows Service、macOS LaunchAgent 以及 Linux systemd 部署。

新增 Windows Inno Setup 安装器、macOS Intel/Apple Silicon 通用 pkg、Linux 多架构安装脚本,并在安装过程中自动准备 Playwright Chromium。

新增仅 codex/desktop-packaging 分支触发的桌面端 CI/CD,覆盖 Go 测试、交叉编译和 Windows/macOS/Linux 安装包构建;保持现有 Docker 工作流不变。

补充数据密钥持久化、托盘图标、安装文档及相关测试。
This commit is contained in:
Christ committed 2026-08-11 19:52:34 +08:00
1 parent 1204655170
commit a99ea5c20d
25 files changed
+1141 -81

No files matched your search

+172
View File
@@ -0,0 +1,172 @@
name: 构建桌面端安装包
on:
push:
branches:
- codex/desktop-packaging
workflow_dispatch:
permissions:
contents: read
concurrency:
group: desktop-cd-${{ github.ref }}
cancel-in-progress: true
env:
APP_VERSION: 0.0.0-${{ github.run_number }}
jobs:
linux:
name: Linux 安装包
if: github.ref == 'refs/heads/codex/desktop-packaging'
runs-on: ubuntu-latest
strategy:
matrix:
arch: [amd64, arm64]
steps:
- name: 检出代码
uses: actions/checkout@v4
- name: 配置 Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod
cache: true
- name: 配置 Node.js
uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
cache-dependency-path: frontend/package-lock.json
- name: 构建嵌入式前端
run: npm ci --prefix frontend && npm run build --prefix frontend
- name: 编译 Linux 二进制并组装安装目录
env:
GOOS: linux
GOARCH: ${{ matrix.arch }}
CGO_ENABLED: 0
run: |
package_dir="dist/ydisks-xianyu-helper-linux-${GOARCH}"
mkdir -p "$package_dir"
go build -trimpath -ldflags='-s -w' -o "$package_dir/xianyu-server" ./cmd/server
go build -trimpath -ldflags='-s -w' -o "$package_dir/browser-install" ./cmd/browser-install
cp packaging/linux/install.sh packaging/linux/uninstall.sh packaging/linux/ydisks-xianyu-helper.service "$package_dir/"
chmod +x "$package_dir/install.sh" "$package_dir/uninstall.sh"
tar -C dist -czf "dist/ydisks-xianyu-helper-linux-${GOARCH}-${APP_VERSION}.tar.gz" "$(basename "$package_dir")"
- name: 上传 Linux 安装包
uses: actions/upload-artifact@v4
with:
name: ydisks-xianyu-helper-linux-${{ matrix.arch }}-${{ env.APP_VERSION }}
path: dist/ydisks-xianyu-helper-linux-${{ matrix.arch }}-${{ env.APP_VERSION }}.tar.gz
if-no-files-found: error
windows:
name: Windows 安装包
if: github.ref == 'refs/heads/codex/desktop-packaging'
runs-on: windows-latest
steps:
- name: 检出代码
uses: actions/checkout@v4
- name: 配置 Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod
cache: true
- name: 配置 Node.js
uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
cache-dependency-path: frontend/package-lock.json
- name: 构建嵌入式前端
shell: pwsh
run: npm ci --prefix frontend; npm run build --prefix frontend
- name: 编译 Windows 桌面程序
shell: pwsh
run: |
New-Item -ItemType Directory -Force -Path dist/windows | Out-Null
go build -trimpath -ldflags "-s -w" -o dist/windows/xianyu-server.exe ./cmd/server
go build -trimpath -ldflags "-s -w" -o dist/windows/browser-install.exe ./cmd/browser-install
go build -trimpath -ldflags "-s -w -H=windowsgui" -o dist/windows/xianyu-tray.exe ./cmd/tray
- name: 安装 Inno Setup
shell: pwsh
run: choco install innosetup --no-progress --yes
- name: 构建 Windows 安装器
shell: pwsh
env:
APP_VERSION: ${{ env.APP_VERSION }}
run: |
& 'C:\Program Files (x86)\Inno Setup 6\ISCC.exe' /Qp /O"dist\windows" packaging\windows\installer.iss
$installer = Get-ChildItem -Path dist/windows -Filter 'Ydisks-Xianyu-Helper-Setup.exe' -Recurse | Select-Object -First 1
if ($null -eq $installer) { throw 'Inno Setup 未生成安装器' }
$target = Join-Path (Resolve-Path dist/windows) 'Ydisks-Xianyu-Helper-Setup.exe'
if ($installer.FullName -ne $target) { Copy-Item $installer.FullName $target -Force }
Compress-Archive -Path dist/windows/xianyu-server.exe,dist/windows/browser-install.exe,dist/windows/xianyu-tray.exe -DestinationPath "dist/windows/Ydisks-Xianyu-Helper-${env:APP_VERSION}-binaries.zip"
- name: 上传 Windows 安装包
uses: actions/upload-artifact@v4
with:
name: ydisks-xianyu-helper-windows-${{ env.APP_VERSION }}
path: |
dist/windows/Ydisks-Xianyu-Helper-Setup.exe
dist/windows/Ydisks-Xianyu-Helper-${{ env.APP_VERSION }}-binaries.zip
if-no-files-found: error
macos:
name: macOS 安装包
if: github.ref == 'refs/heads/codex/desktop-packaging'
runs-on: macos-14
steps:
- name: 检出代码
uses: actions/checkout@v4
- name: 配置 Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod
cache: true
- name: 配置 Node.js
uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
cache-dependency-path: frontend/package-lock.json
- name: 构建嵌入式前端
run: npm ci --prefix frontend && npm run build --prefix frontend
- name: 编译 macOS 桌面程序
run: |
mkdir -p dist/macos/arm64 dist/macos/amd64
for arch in arm64 amd64; do
GOOS=darwin GOARCH="$arch" CGO_ENABLED=1 go build -trimpath -ldflags='-s -w' -o "dist/macos/$arch/xianyu-server" ./cmd/server
GOOS=darwin GOARCH="$arch" CGO_ENABLED=1 go build -trimpath -ldflags='-s -w' -o "dist/macos/$arch/browser-install" ./cmd/browser-install
GOOS=darwin GOARCH="$arch" CGO_ENABLED=1 go build -trimpath -ldflags='-s -w' -o "dist/macos/$arch/xianyu-tray" ./cmd/tray
done
lipo -create dist/macos/arm64/xianyu-server dist/macos/amd64/xianyu-server -output dist/macos/xianyu-server
lipo -create dist/macos/arm64/browser-install dist/macos/amd64/browser-install -output dist/macos/browser-install
lipo -create dist/macos/arm64/xianyu-tray dist/macos/amd64/xianyu-tray -output dist/macos/xianyu-tray
- name: 构建 macOS pkg
run: |
chmod +x packaging/macos/build-pkg.sh
packaging/macos/build-pkg.sh "$APP_VERSION" "$PWD/dist/macos"
- name: 上传 macOS 安装包
uses: actions/upload-artifact@v4
with:
name: ydisks-xianyu-helper-macos-${{ env.APP_VERSION }}
path: dist/macos/Ydisks-Xianyu-Helper-${{ env.APP_VERSION }}.pkg
if-no-files-found: error
+86
View File
@@ -0,0 +1,86 @@
name: 桌面端 CI
on:
push:
branches:
- codex/desktop-packaging
workflow_dispatch:
permissions:
contents: read
concurrency:
group: desktop-ci-${{ github.ref }}
cancel-in-progress: true
jobs:
verify:
name: Go 与前端检查
if: github.ref == 'refs/heads/codex/desktop-packaging'
runs-on: ubuntu-latest
steps:
- name: 检出代码
uses: actions/checkout@v4
- name: 配置 Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod
cache: true
- name: 配置 Node.js
uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
cache-dependency-path: frontend/package-lock.json
- name: 构建嵌入式前端
run: npm ci --prefix frontend && npm run build --prefix frontend
- name: 运行 Go 测试
run: go test ./...
- name: 运行 go vet
run: go vet ./...
cross-build:
name: 核心二进制 ${{ matrix.goos }}/${{ matrix.goarch }}
if: github.ref == 'refs/heads/codex/desktop-packaging'
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
include:
- goos: linux
goarch: amd64
- goos: linux
goarch: arm64
- goos: windows
goarch: amd64
- goos: windows
goarch: arm64
- goos: darwin
goarch: amd64
- goos: darwin
goarch: arm64
steps:
- name: 检出代码
uses: actions/checkout@v4
- name: 配置 Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod
cache: true
- name: 编译 server 与浏览器安装器
shell: bash
env:
GOOS: ${{ matrix.goos }}
GOARCH: ${{ matrix.goarch }}
CGO_ENABLED: 0
run: |
mkdir -p dist
go build -trimpath -ldflags='-s -w' -o "dist/xianyu-server-${GOOS}-${GOARCH}" ./cmd/server
go build -trimpath -ldflags='-s -w' -o "dist/browser-install-${GOOS}-${GOARCH}" ./cmd/browser-install
+9 -1
View File
@@ -3,12 +3,20 @@
GO ?= go
GOLANGCI_LINT ?= golangci-lint
.PHONY: build build-int test test-int vet lint cover tidy frontend fmt check
.PHONY: build build-int build-browser-install build-tray test test-int vet lint cover tidy frontend fmt check
## build: 编译 server(默认,跳过 integration build tag)
build:
$(GO) build ./cmd/server
## build-browser-install: 编译独立的 Chromium 安装辅助程序
build-browser-install:
$(GO) build ./cmd/browser-install
## build-tray: 编译 Windows/macOS 菜单栏控制器(需在目标桌面系统上编译)
build-tray:
$(GO) build ./cmd/tray
## build-int: 带 integration tag 编译(含 browser 包,需要 Chromium 环境)
build-int:
$(GO) build -tags integration ./...
+19
View File
@@ -174,6 +174,22 @@ npm --prefix frontend run build
前端资源会在构建时通过 Go 的 `//go:embed` 嵌入服务;如果服务已经在运行,构建完成后
需要重启 Go 服务,浏览器硬刷新本身不会替换运行中进程已加载的前端资源。
### 方式三:桌面端安装包
桌面端由两个进程组成:后台 `xianyu-server` 负责 HTTP API、账号运行时和 Chromium;
`xianyu-tray` 只负责 Windows 托盘或 macOS 菜单栏状态、打开管理页面和服务控制。
Chromium 不打进 Go 二进制,首次安装时由随包的 `browser-install` 自动下载到用户数据目录。
- Windows:安装器注册 `YdisksXianyuHelper` Windows Service,并将托盘控制器加入当前用户登录启动项。
- macOS:安装器注册当前登录用户的两个 LaunchAgent,分别运行后台服务和菜单栏控制器。
- Linux:下载对应架构的 tar 包后,以 root 执行 `./install.sh`;脚本创建专用系统用户、安装
systemd unit,并执行 Playwright Chromium 及系统依赖安装。卸载时执行 `./uninstall.sh`,
默认保留 `/var/lib/ydisks-xianyu-helper` 数据。
桌面端安装包由 GitHub Actions 的 `codex/desktop-packaging` 分支专用工作流构建。当前工作流
上传未签名的 Windows `.exe` 安装器和 macOS `.pkg` 作为 Actions artifact;正式对外分发前,
还应配置 Windows 代码签名证书、Apple Developer ID 和公证流程。
初始化管理员:
```bash
@@ -465,6 +481,8 @@ services:
.
├── cmd/
│ ├── server/ # 主服务与管理员初始化入口
│ ├── browser-install/ # Playwright Chromium 安装辅助程序
│ ├── tray/ # Windows 托盘/macOS 菜单栏控制器
│ ├── init-admin/ # 交互式管理员初始化工具
│ ├── dbverify/ # 多数据库迁移和 CRUD 验证
│ └── dbseed/ # Docker 功能测试数据种子
@@ -481,6 +499,7 @@ services:
│ └── xianyu/ # MTOP、WebSocket、登录和协议实现
├── frontend/ # React、TypeScript、Vite 前端
├── docs/ # 专题文档和行为规范
├── packaging/ # Linux systemd、Windows Inno Setup、macOS pkg
├── scripts/ # Docker 与回归测试脚本
└── Dockerfile.debian13 # 多阶段生产镜像
```
+61
View File
@@ -0,0 +1,61 @@
// Command browser-install prepares the Playwright driver and Chromium runtime.
// It intentionally does not change the server's browser launch behavior.
package main
import (
"flag"
"fmt"
"os"
"github.com/playwright-community/playwright-go"
)
func main() {
driverDir := flag.String("driver-dir", "", "Playwright driver directory")
browserDir := flag.String("browser-dir", "", "Playwright browser cache directory")
withDeps := flag.Bool("with-deps", false, "also install Linux system dependencies")
flag.Parse()
if *driverDir != "" {
if err := os.Setenv("PLAYWRIGHT_DRIVER_PATH", *driverDir); err != nil {
fatal("设置 driver 目录失败", err)
}
}
if *browserDir != "" {
if err := os.Setenv("PLAYWRIGHT_BROWSERS_PATH", *browserDir); err != nil {
fatal("设置浏览器目录失败", err)
}
}
options := &playwright.RunOptions{
Browsers: []string{"chromium"},
Verbose: true,
}
if *driverDir != "" {
options.DriverDirectory = *driverDir
}
driver, err := playwright.NewDriver(options)
if err != nil {
fatal("创建 Playwright driver 失败", err)
}
if err := driver.DownloadDriver(); err != nil {
fatal("下载 Playwright driver 失败", err)
}
args := []string{"install"}
if *withDeps {
args = append(args, "--with-deps")
}
args = append(args, "chromium")
cmd := driver.Command(args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
fatal("安装 Chromium 失败", err)
}
}
func fatal(message string, err error) {
fmt.Fprintf(os.Stderr, "%s: %v\n", message, err)
os.Exit(1)
}
+152 -78
View File
@@ -1,25 +1,18 @@
// Package main 是闲鱼管家 Go 主进程入口。
// 启动:DB 迁移 → 加载账号引擎 → HTTP API 服务。
//
// 用法:
//
// go run ./cmd/server -db data/xianyu_data.db -addr :8080 [-web ./static] [-secure] [-no-browser]
// go run ./cmd/server -db data/xianyu_data.db -init-admin -admin-password '...'
//
// 首次使用可直接用本二进制初始化管理员,不再需要单独 init-admin。
//
// Chromium 仅用于读取本机浏览器指纹和处理 token 滑块,首次使用时由
// playwright-go 准备运行环境。加 -no-browser 可禁用这两项能力。
package main
import (
"context"
"crypto/rand"
"encoding/base64"
"errors"
"flag"
"fmt"
"log/slog"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
@@ -36,74 +29,145 @@ import (
"xianyu-go/internal/server"
)
type serverOptions struct {
dbPath string
dbURL string
addr string
webDir string
workDir string
playwrightDriverDir string
playwrightBrowserDir string
dataKeyFile string
secure bool
noBrowser bool
verbose bool
logLevel string
logFormat string
initAdmin bool
ensureAdmin bool
adminEmail string
adminPassword string
service bool
}
func main() {
dbPath := flag.String("db", "data/xianyu_data.db", "SQLite 数据库路径(兼容旧用法)")
dbURL := flag.String("db-url", "", "数据库连接 URL(sqlite:// mysql:// postgres://),优先级高于 -db;也可用 DATABASE_URL 环境变量")
addr := flag.String("addr", ":8080", "HTTP 监听地址")
webDir := flag.String("web", "", "前端静态资源目录(含 index.html)")
secure := flag.Bool("secure", false, "HTTPS 模式(Cookie 加 Secure)")
noBrowser := flag.Bool("no-browser", false, "禁用 Chromium(本机浏览器指纹读取和 token 滑块自动处理将不可用)")
verbose := flag.Bool("v", false, "调试日志")
logLevel := flag.String("log-level", "", "日志等级:debug/info/warn/error;默认读取 LOG_LEVEL 或系统设置")
logFormat := flag.String("log-format", "", "日志格式:text/json;默认读取 LOG_FORMAT")
initAdmin := flag.Bool("init-admin", false, "初始化或重置 admin 管理员后退出")
ensureAdminOnStart := flag.Bool("ensure-admin", false, "仅在 admin 管理员不存在时初始化;已存在时不修改密码")
adminEmail := flag.String("admin-email", "admin@example.com", "初始化 admin 的邮箱")
adminPassword := flag.String("admin-password", "", "初始化/重置 admin 密码;也可用 XIANYU_ADMIN_PASSWORD 环境变量")
opts := parseOptions()
if opts.workDir != "" {
if err := os.Chdir(opts.workDir); err != nil {
fmt.Fprintf(os.Stderr, "切换工作目录失败: %v\n", err)
os.Exit(2)
}
}
run := func(ctx context.Context) error { return runServer(ctx, opts) }
if opts.service {
if err := runPlatformService("YdisksXianyuHelper", run); err != nil {
fmt.Fprintf(os.Stderr, "服务运行失败: %v\n", err)
os.Exit(1)
}
return
}
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer cancel()
if err := run(ctx); err != nil {
slog.Error("服务退出", "err", err)
os.Exit(1)
}
}
func parseOptions() serverOptions {
var opts serverOptions
flag.StringVar(&opts.dbPath, "db", "data/xianyu_data.db", "SQLite 数据库路径(兼容旧用法)")
flag.StringVar(&opts.dbURL, "db-url", "", "数据库连接 URL(sqlite:// mysql:// postgres://),优先级高于 -db;也可用 DATABASE_URL 环境变量")
flag.StringVar(&opts.addr, "addr", ":8080", "HTTP 监听地址")
flag.StringVar(&opts.webDir, "web", "", "前端静态资源目录(含 index.html)")
flag.StringVar(&opts.workDir, "workdir", "", "服务工作目录;用于桌面服务固定数据和浏览器目录")
flag.StringVar(&opts.playwrightDriverDir, "playwright-driver-dir", "", "Playwright driver 目录")
flag.StringVar(&opts.playwrightBrowserDir, "playwright-browser-dir", "", "Playwright 浏览器缓存目录")
flag.StringVar(&opts.dataKeyFile, "data-key-file", "", "XIANYU_DATA_KEY 持久化文件;不存在时自动生成")
flag.BoolVar(&opts.secure, "secure", false, "HTTPS 模式(Cookie 加 Secure)")
flag.BoolVar(&opts.noBrowser, "no-browser", false, "禁用 Chromium(本机浏览器指纹读取和 token 滑块自动处理将不可用)")
flag.BoolVar(&opts.verbose, "v", false, "调试日志")
flag.StringVar(&opts.logLevel, "log-level", "", "日志等级:debug/info/warn/error;默认读取 LOG_LEVEL 或系统设置")
flag.StringVar(&opts.logFormat, "log-format", "", "日志格式:text/json;默认读取 LOG_FORMAT")
flag.BoolVar(&opts.initAdmin, "init-admin", false, "初始化或重置 admin 管理员后退出")
flag.BoolVar(&opts.ensureAdmin, "ensure-admin", false, "仅在 admin 管理员不存在时初始化;已存在时不修改密码")
flag.StringVar(&opts.adminEmail, "admin-email", "admin@example.com", "初始化 admin 的邮箱")
flag.StringVar(&opts.adminPassword, "admin-password", "", "初始化/重置 admin 密码;也可用 XIANYU_ADMIN_PASSWORD 环境变量")
flag.BoolVar(&opts.service, "service", false, "以 Windows Service 模式运行")
flag.Parse()
return opts
}
func runServer(parent context.Context, opts serverOptions) error {
ctx, cancel := context.WithCancel(parent)
defer cancel()
if opts.playwrightDriverDir != "" {
if err := os.Setenv("PLAYWRIGHT_DRIVER_PATH", opts.playwrightDriverDir); err != nil {
return fmt.Errorf("设置 Playwright driver 目录失败: %w", err)
}
}
if opts.playwrightBrowserDir != "" {
if err := os.Setenv("PLAYWRIGHT_BROWSERS_PATH", opts.playwrightBrowserDir); err != nil {
return fmt.Errorf("设置 Playwright 浏览器目录失败: %w", err)
}
}
if strings.TrimSpace(os.Getenv("XIANYU_DATA_KEY")) == "" && opts.dataKeyFile != "" {
key, err := loadOrCreateDataKey(opts.dataKeyFile)
if err != nil {
return err
}
if err := os.Setenv("XIANYU_DATA_KEY", key); err != nil {
return fmt.Errorf("设置 XIANYU_DATA_KEY 失败: %w", err)
}
}
// 解析数据库连接:DATABASE_URL > -db-url > -db(SQLite 路径,向后兼容)。
resolvedDBURL := strings.TrimSpace(os.Getenv("DATABASE_URL"))
if resolvedDBURL == "" {
resolvedDBURL = strings.TrimSpace(*dbURL)
resolvedDBURL = strings.TrimSpace(opts.dbURL)
}
if resolvedDBURL == "" {
resolvedDBURL = *dbPath
resolvedDBURL = opts.dbPath
}
resolvedLogLevel := strings.TrimSpace(os.Getenv("LOG_LEVEL"))
explicitLogLevel := resolvedLogLevel != ""
if strings.TrimSpace(*logLevel) != "" {
resolvedLogLevel = strings.TrimSpace(*logLevel)
if strings.TrimSpace(opts.logLevel) != "" {
resolvedLogLevel = strings.TrimSpace(opts.logLevel)
explicitLogLevel = true
}
if resolvedLogLevel == "" && *verbose {
if resolvedLogLevel == "" && opts.verbose {
resolvedLogLevel = "debug"
explicitLogLevel = true
}
if err := logging.SetLevel(resolvedLogLevel); err != nil {
fmt.Fprintf(os.Stderr, "日志等级无效: %v\n", err)
os.Exit(2)
return fmt.Errorf("日志等级无效: %w", err)
}
resolvedLogFormat := strings.TrimSpace(os.Getenv("LOG_FORMAT"))
explicitLogFormat := resolvedLogFormat != ""
if strings.TrimSpace(*logFormat) != "" {
resolvedLogFormat = strings.TrimSpace(*logFormat)
if strings.TrimSpace(opts.logFormat) != "" {
resolvedLogFormat = strings.TrimSpace(opts.logFormat)
explicitLogFormat = true
}
logger := logging.NewLogger(os.Stdout, resolvedLogFormat)
slog.SetDefault(logger)
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer cancel()
// 1) DB。
database, dialect, err := db.Open(ctx, resolvedDBURL)
if err != nil {
logger.Error("打开数据库失败", "err", err)
os.Exit(1)
return fmt.Errorf("打开数据库失败: %w", err)
}
defer database.Close()
logger.Info("数据库已就绪", "dialect", dialect)
store := db.NewStore(database, dialect)
if err := store.EncryptLegacySecrets(ctx); err != nil {
logger.Error("校验或升级数据库敏感字段失败", "err", err)
os.Exit(1)
return fmt.Errorf("校验或升级数据库敏感字段失败: %w", err)
}
defer database.Close()
if !explicitLogLevel {
if lv, err := store.Settings.Get(ctx, "log_level"); err == nil && strings.TrimSpace(lv) != "" {
if err := logging.SetLevel(lv); err != nil {
logger.Warn("忽略无效的系统日志等级设置", "value", lv, "err", err)
logger.Warn("忽略无效的系统日志设置", "value", lv, "err", err)
}
}
}
@@ -114,45 +178,39 @@ func main() {
}
}
if *initAdmin {
if err := ensureAdmin(ctx, store, *adminEmail, *adminPassword); err != nil {
logger.Error("初始化管理员失败", "err", err)
os.Exit(1)
if opts.initAdmin {
if err := ensureAdmin(ctx, store, opts.adminEmail, opts.adminPassword); err != nil {
return fmt.Errorf("初始化管理员失败: %w", err)
}
logger.Info("管理员初始化完成", "username", "admin")
return
return nil
}
if *ensureAdminOnStart {
created, err := ensureAdminIfMissing(ctx, store, *adminEmail, *adminPassword)
if opts.ensureAdmin {
created, err := ensureAdminIfMissing(ctx, store, opts.adminEmail, opts.adminPassword)
if err != nil {
logger.Error("检查或初始化管理员失败", "err", err)
os.Exit(1)
return fmt.Errorf("检查或初始化管理员失败: %w", err)
}
if created {
logger.Info("管理员初始化完成", "username", "admin")
}
}
// 检查系统是否已初始化。
if init, _ := store.Users.IsSystemInitialized(ctx); !init {
logger.Warn("系统尚未初始化,请先运行本二进制的 -init-admin 初始化管理员")
}
// 2) Chromium 只负责读取本机浏览器指纹和处理 token 滑块。
// 扫码、人脸、续期、MTOP、Cookie 与 WebSocket 全部走 Go 协议实现。
var bm *browser.Manager
if !*noBrowser {
if !opts.noBrowser {
bm = browser.NewManager(logger)
if err := bm.Initialize(); err != nil {
logger.Error("初始化 Playwright Chromium 指纹失败", "err", err)
os.Exit(1)
return fmt.Errorf("初始化 Playwright Chromium 指纹失败: %w", err)
}
}
var mgr *account.Manager
ap := adapter.New(store, bm, logger)
chatService := chat.New(store)
ap.SetChatService(chatService)
mgr = account.NewManager(store, ap, logger)
mgr := account.NewManager(store, ap, logger)
autoCenter := automation.New(store, mgr, logger)
autoCenter.SetOrderDetailFetcher(ap)
notifier := notify.New("", store, logger)
@@ -168,24 +226,14 @@ func main() {
renewalScheduler := renewal.NewScheduler(store, mgr, ap, logger, notifier)
go renewalScheduler.Run(ctx)
// 3) HTTP 服务。
srv := server.New(store, mgr, *secure, *webDir, *addr, logger, autoCenter, notifier)
srv := server.New(store, mgr, opts.secure, opts.webDir, opts.addr, logger, autoCenter, notifier)
srv.SetChatService(chatService)
srv.StartPublishBatchRecovery(ctx)
if err := srv.Run(ctx); err != nil {
logger.Error("HTTP 服务退出", "err", err)
// 即便出错也尝试清理已启动的账号与浏览器。
cancel()
srv.WaitForBackground()
automationScheduler.Wait()
renewalScheduler.Wait()
mgr.StopAll()
if bm != nil {
_ = bm.Close()
}
os.Exit(1)
runErr := srv.Run(ctx)
if runErr != nil {
logger.Error("HTTP 服务退出", "err", runErr)
}
// HTTP 服务正常退出(ctx 取消触发 Shutdown):停账号引擎、关浏览器。
cancel()
srv.WaitForBackground()
automationScheduler.Wait()
renewalScheduler.Wait()
@@ -194,11 +242,38 @@ func main() {
_ = bm.Close()
}
notifier.Wait()
return runErr
}
// handlerAdapter 已下沉到 internal/adapter 包;本文件只负责装配。
func loadOrCreateDataKey(path string) (string, error) {
path = strings.TrimSpace(path)
if path == "" {
return "", fmt.Errorf("data key 文件路径不能为空")
}
if raw, err := os.ReadFile(path); err == nil {
key := strings.TrimSpace(string(raw))
if key == "" {
return "", fmt.Errorf("data key 文件为空: %s", path)
}
return key, nil
} else if !errors.Is(err, os.ErrNotExist) {
return "", fmt.Errorf("读取 data key 文件失败: %w", err)
}
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return "", fmt.Errorf("创建 data key 目录失败: %w", err)
}
raw := make([]byte, 48)
if _, err := rand.Read(raw); err != nil {
return "", fmt.Errorf("生成 data key 失败: %w", err)
}
key := base64.RawStdEncoding.EncodeToString(raw)
if err := os.WriteFile(path, []byte(key+"\n"), 0o600); err != nil {
return "", fmt.Errorf("写入 data key 文件失败: %w", err)
}
return key, nil
}
// ensureAdmin 解析密码后委托 auth.InitAdmin 完成创建或重置。
func ensureAdmin(ctx context.Context, store *db.Store, email, password string) error {
if password == "" {
password = os.Getenv("XIANYU_ADMIN_PASSWORD")
@@ -210,7 +285,6 @@ func ensureAdmin(ctx context.Context, store *db.Store, email, password string) e
return err
}
// ensureAdminIfMissing 只为首次部署创建管理员,避免容器重启重置既有管理员密码。
func ensureAdminIfMissing(ctx context.Context, store *db.Store, email, password string) (bool, error) {
admin, err := store.Users.GetAdmin(ctx)
if err != nil && !errors.Is(err, db.ErrNotFound) {
+22
View File
@@ -2,6 +2,7 @@ package main
import (
"context"
"os"
"path/filepath"
"testing"
@@ -32,3 +33,24 @@ func TestEnsureAdminIfMissingCreatesOnlyOnce(t *testing.T) {
t.Fatalf("later password must not reset admin: ok=%v err=%v", ok, err)
}
}
func TestLoadOrCreateDataKeyPersists(t *testing.T) {
path := filepath.Join(t.TempDir(), "data-key")
first, err := loadOrCreateDataKey(path)
if err != nil {
t.Fatalf("create data key: %v", err)
}
if first == "" {
t.Fatal("created data key is empty")
}
second, err := loadOrCreateDataKey(path)
if err != nil {
t.Fatalf("load data key: %v", err)
}
if first != second {
t.Fatalf("data key changed between loads")
}
if raw, err := os.ReadFile(path); err != nil || string(raw) == "" {
t.Fatalf("data key file was not written: err=%v", err)
}
}
+12
View File
@@ -0,0 +1,12 @@
//go:build !windows
package main
import (
"context"
"fmt"
)
func runPlatformService(_ string, _ func(context.Context) error) error {
return fmt.Errorf("当前平台不支持 -service;请使用系统服务管理器启动普通进程")
}
+48
View File
@@ -0,0 +1,48 @@
//go:build windows
package main
import (
"context"
"fmt"
"golang.org/x/sys/windows/svc"
)
type windowsServiceHandler struct {
run func(context.Context) error
}
func runPlatformService(name string, run func(context.Context) error) error {
if err := svc.Run(name, windowsServiceHandler{run: run}); err != nil {
return fmt.Errorf("Windows Service %q: %w", name, err)
}
return nil
}
func (h windowsServiceHandler) Execute(_ []string, requests <-chan svc.ChangeRequest, status chan<- svc.Status) (bool, uint32) {
const accepted = svc.AcceptStop | svc.AcceptShutdown
status <- svc.Status{State: svc.StartPending}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { done <- h.run(ctx) }()
status <- svc.Status{State: svc.Running, Accepts: accepted}
for {
select {
case request := <-requests:
switch request.Cmd {
case svc.Stop, svc.Shutdown:
status <- svc.Status{State: svc.StopPending, Accepts: accepted}
cancel()
}
case err := <-done:
cancel()
if err != nil {
return true, 1
}
return false, 0
}
}
}
+65
View File
@@ -0,0 +1,65 @@
package main
import (
"bytes"
"encoding/binary"
"image"
"image/color"
"image/png"
"runtime"
)
// trayIconBytes 返回一个不依赖外部文件的图标,避免安装器还要额外管理图标路径。
// Windows 的 Shell_NotifyIcon 需要 ICO;macOS/Linux 可以直接使用 PNG。
func trayIconBytes() []byte {
const size = 32
img := image.NewRGBA(image.Rect(0, 0, size, size))
for y := 0; y < size; y++ {
for x := 0; x < size; x++ {
dx, dy := x-size/2, y-size/2
if dx*dx+dy*dy <= 14*14 {
img.SetRGBA(x, y, color.RGBA{R: 37, G: 99, B: 235, A: 255})
}
if abs(x-y) <= 2 || abs(x+y-(size-1)) <= 2 {
if dx*dx+dy*dy <= 10*10 {
img.SetRGBA(x, y, color.RGBA{R: 255, G: 255, B: 255, A: 255})
}
}
}
}
var pngData bytes.Buffer
_ = png.Encode(&pngData, img)
if runtime.GOOS != "windows" {
return pngData.Bytes()
}
return pngToICO(pngData.Bytes(), size)
}
func pngToICO(data []byte, size int) []byte {
const headerSize = 6
const entrySize = 16
result := make([]byte, headerSize+entrySize+len(data))
// ICONDIR: reserved, type=icon, image count=1.
binary.LittleEndian.PutUint16(result[0:2], 0)
binary.LittleEndian.PutUint16(result[2:4], 1)
binary.LittleEndian.PutUint16(result[4:6], 1)
entry := result[headerSize : headerSize+entrySize]
entry[0] = byte(size)
entry[1] = byte(size)
entry[2] = 0
entry[3] = 0
binary.LittleEndian.PutUint16(entry[4:6], 1)
binary.LittleEndian.PutUint16(entry[6:8], 32)
binary.LittleEndian.PutUint32(entry[8:12], uint32(len(data)))
binary.LittleEndian.PutUint32(entry[12:16], headerSize+entrySize)
copy(result[headerSize+entrySize:], data)
return result
}
func abs(value int) int {
if value < 0 {
return -value
}
return value
}
+140
View File
@@ -0,0 +1,140 @@
// Command tray provides the small desktop controller for the background server.
// The server remains a separate process managed by the operating system.
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"os/exec"
"runtime"
"strings"
"time"
"fyne.io/systray"
)
type healthResponse struct {
Status string `json:"status"`
Database string `json:"database"`
}
var serviceURL = strings.TrimRight(envOr("XIANYU_SERVICE_URL", "http://127.0.0.1:8080"), "/")
func main() {
systray.Run(onReady, func() {})
}
func onReady() {
systray.SetTitle("闲鱼管家")
systray.SetIcon(trayIconBytes())
systray.SetTooltip("闲鱼管家服务")
statusItem := systray.AddMenuItem("服务状态:检查中", "读取后台服务状态")
openItem := systray.AddMenuItem("打开管理页面", "在默认浏览器打开管理页面")
systray.AddSeparator()
startItem := systray.AddMenuItem("启动服务", "启动后台服务")
stopItem := systray.AddMenuItem("停止服务", "停止后台服务")
restartItem := systray.AddMenuItem("重启服务", "重启后台服务")
browserItem := systray.AddMenuItem("安装/修复 Chromium", "准备 Playwright Chromium")
systray.AddSeparator()
quitItem := systray.AddMenuItem("退出托盘", "只退出菜单栏控制器")
go refreshStatus(statusItem)
go func() {
for range openItem.ClickedCh {
_ = openURL(serviceURL)
}
}()
go func() {
for range startItem.ClickedCh {
_ = serviceAction("start")
}
}()
go func() {
for range stopItem.ClickedCh {
_ = serviceAction("stop")
}
}()
go func() {
for range restartItem.ClickedCh {
_ = serviceAction("restart")
}
}()
go func() {
for range browserItem.ClickedCh {
_ = installBrowser()
}
}()
go func() {
for range quitItem.ClickedCh {
systray.Quit()
}
}()
}
func installBrowser() error {
path := strings.TrimSpace(os.Getenv("XIANYU_BROWSER_INSTALL"))
if path == "" {
executable, err := os.Executable()
if err != nil {
return err
}
path = executable
if runtime.GOOS == "darwin" {
path = strings.Replace(path, "/Contents/MacOS/xianyu-tray", "/Contents/Helpers/browser-install", 1)
} else {
path = strings.Replace(path, "xianyu-tray.exe", "browser-install.exe", 1)
}
}
return exec.Command(path).Run()
}
func refreshStatus(item *systray.MenuItem) {
client := &http.Client{Timeout: 2 * time.Second}
for {
status, err := readHealth(client)
if err != nil {
item.SetTitle("服务状态:未运行")
systray.SetTooltip("闲鱼管家:后台服务未运行")
} else if status.Status == "ok" && status.Database == "ok" {
item.SetTitle("服务状态:运行正常")
systray.SetTooltip("闲鱼管家:运行正常")
} else {
item.SetTitle("服务状态:异常")
systray.SetTooltip("闲鱼管家:数据库或服务异常")
}
time.Sleep(5 * time.Second)
}
}
func readHealth(client *http.Client) (healthResponse, error) {
resp, err := client.Get(serviceURL + "/health")
if err != nil {
return healthResponse{}, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return healthResponse{}, fmt.Errorf("health status %d", resp.StatusCode)
}
var health healthResponse
if err := json.NewDecoder(resp.Body).Decode(&health); err != nil {
return healthResponse{}, err
}
return health, nil
}
func openURL(url string) error {
if runtime.GOOS == "windows" {
return exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
}
return exec.Command("open", url).Start()
}
func envOr(name, fallback string) string {
if value := strings.TrimSpace(os.Getenv(name)); value != "" {
return value
}
return fallback
}
+25
View File
@@ -0,0 +1,25 @@
//go:build darwin
package main
import (
"fmt"
"os"
"os/exec"
)
func serviceAction(action string) error {
label := envOr("XIANYU_SERVICE_NAME", "com.christ.ydisks-xianyu-helper")
uid := fmt.Sprint(os.Getuid())
target := "gui/" + uid + "/" + label
switch action {
case "start":
return exec.Command("launchctl", "kickstart", target).Run()
case "stop":
return exec.Command("launchctl", "kill", "SIGTERM", target).Run()
case "restart":
return exec.Command("launchctl", "kickstart", "-k", target).Run()
default:
return nil
}
}
+5
View File
@@ -0,0 +1,5 @@
//go:build !windows && !darwin
package main
func serviceAction(_ string) error { return nil }
+20
View File
@@ -0,0 +1,20 @@
//go:build windows
package main
import "os/exec"
func serviceAction(action string) error {
name := envOr("XIANYU_SERVICE_NAME", "YdisksXianyuHelper")
switch action {
case "start", "stop":
return exec.Command("sc.exe", action, name).Run()
case "restart":
if err := exec.Command("sc.exe", "stop", name).Run(); err != nil {
return err
}
return exec.Command("sc.exe", "start", name).Run()
default:
return nil
}
}
+4 -2
View File
@@ -3,6 +3,7 @@ module xianyu-go
go 1.26.4
require (
fyne.io/systray v1.12.2
github.com/coder/websocket v1.8.15
github.com/go-chi/chi/v5 v5.3.0
github.com/go-sql-driver/mysql v1.10.0
@@ -12,6 +13,8 @@ require (
github.com/sashabaranov/go-openai v1.41.2
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
golang.org/x/crypto v0.50.0
golang.org/x/sync v0.20.0
golang.org/x/sys v0.46.0
golang.org/x/term v0.44.0
modernc.org/sqlite v1.53.0
)
@@ -22,6 +25,7 @@ require (
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/go-jose/go-jose/v3 v3.0.4 // indirect
github.com/go-stack/stack v1.8.1 // indirect
github.com/godbus/dbus/v5 v5.1.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
@@ -32,8 +36,6 @@ require (
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/sethvargo/go-retry v0.3.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/sync v0.20.0 // indirect
golang.org/x/sys v0.46.0 // indirect
golang.org/x/text v0.36.0 // indirect
modernc.org/libc v1.73.4 // indirect
modernc.org/mathutil v1.7.1 // indirect
+4
View File
@@ -1,5 +1,7 @@
filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
fyne.io/systray v1.12.2 h1:Y8DZxgLHsVQt6rY9Zrkkg+j67S7vv/1F2viOWKPpVeA=
fyne.io/systray v1.12.2/go.mod h1:RVwqP9nYMo7h5zViCBHri2FgjXF7H2cub7MAq4NSoLs=
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@@ -17,6 +19,8 @@ github.com/go-sql-driver/mysql v1.10.0 h1:Q+1LV8DkHJvSYAdR83XzuhDaTykuDx0l6fkXxo
github.com/go-sql-driver/mysql v1.10.0/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
github.com/go-stack/stack v1.8.1 h1:ntEHSVwIt7PNXNpgPmVfMrNhLtgjlmnZha2kOpuRiDw=
github.com/go-stack/stack v1.8.1/go.mod h1:dcoOX6HbPZSZptuspn9bctJ+N/CnF5gGygcUP3XYfe4=
github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
+75
View File
@@ -0,0 +1,75 @@
#!/usr/bin/env bash
set -Eeuo pipefail
APP_NAME="ydisks-xianyu-helper"
INSTALL_DIR="/opt/$APP_NAME"
DATA_DIR="/var/lib/$APP_NAME"
CONFIG_DIR="/etc/$APP_NAME"
SERVICE_NAME="$APP_NAME.service"
SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
if [[ "$(id -u)" -ne 0 ]]; then
echo "请使用 root 运行:sudo $0" >&2
exit 1
fi
if ! command -v systemctl >/dev/null 2>&1; then
echo "当前系统没有 systemd,安装脚本暂不支持。" >&2
exit 1
fi
SERVER_SOURCE="${XIANYU_SERVER_SOURCE:-$SCRIPT_DIR/xianyu-server}"
BROWSER_SOURCE="${XIANYU_BROWSER_INSTALL_SOURCE:-$SCRIPT_DIR/browser-install}"
if [[ ! -x "$SERVER_SOURCE" ]]; then
echo "找不到 xianyu-server:$SERVER_SOURCE" >&2
exit 1
fi
if [[ ! -x "$BROWSER_SOURCE" ]]; then
echo "找不到 browser-install:$BROWSER_SOURCE" >&2
exit 1
fi
if ! getent group "$APP_NAME" >/dev/null; then
groupadd --system "$APP_NAME"
fi
if ! id "$APP_NAME" >/dev/null 2>&1; then
useradd --system --gid "$APP_NAME" --home-dir "$DATA_DIR" --no-create-home --shell /usr/sbin/nologin "$APP_NAME"
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 "$DATA_DIR/playwright-driver" "$DATA_DIR/playwright-browsers"
install -d -m 0750 "$CONFIG_DIR"
install -m 0755 "$SERVER_SOURCE" "$INSTALL_DIR/xianyu-server"
install -m 0755 "$BROWSER_SOURCE" "$INSTALL_DIR/browser-install"
install -m 0644 "$SCRIPT_DIR/ydisks-xianyu-helper.service" "/etc/systemd/system/$SERVICE_NAME"
if [[ ! -f "$CONFIG_DIR/config.env" ]]; then
umask 077
if command -v openssl >/dev/null 2>&1; then
data_key="$(openssl rand -base64 48 2>/dev/null | tr -d '\n')"
else
data_key="$(head -c 48 /dev/urandom | base64 | tr -d '\n')"
fi
{
printf 'XIANYU_DATA_KEY=%s\n' "$data_key"
printf 'LOG_FORMAT=json\n'
} > "$CONFIG_DIR/config.env"
fi
chown -R "$APP_NAME:$APP_NAME" "$DATA_DIR"
chmod 0600 "$CONFIG_DIR/config.env"
if [[ "${XIANYU_SKIP_BROWSER_INSTALL:-0}" != "1" ]]; then
"$INSTALL_DIR/browser-install" \
-driver-dir "$DATA_DIR/playwright-driver" \
-browser-dir "$DATA_DIR/playwright-browsers" \
--with-deps
chown -R "$APP_NAME:$APP_NAME" "$DATA_DIR/playwright-driver" "$DATA_DIR/playwright-browsers"
fi
systemctl daemon-reload
systemctl enable --now "$SERVICE_NAME"
systemctl --no-pager --full status "$SERVICE_NAME" || true
echo "安装完成:systemctl status $SERVICE_NAME"
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env bash
set -Eeuo pipefail
APP_NAME="ydisks-xianyu-helper"
SERVICE_NAME="$APP_NAME.service"
if [[ "$(id -u)" -ne 0 ]]; then
echo "请使用 root 运行:sudo $0" >&2
exit 1
fi
systemctl disable --now "$SERVICE_NAME" >/dev/null 2>&1 || true
rm -f "/etc/systemd/system/$SERVICE_NAME"
systemctl daemon-reload
rm -rf "/opt/$APP_NAME"
echo "程序和服务已移除;数据仍保留在 /var/lib/$APP_NAME。"
@@ -0,0 +1,21 @@
[Unit]
Description=Ydisks Xianyu Helper
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
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-driver-dir /var/lib/ydisks-xianyu-helper/playwright-driver -playwright-browser-dir /var/lib/ydisks-xianyu-helper/playwright-browsers
Restart=on-failure
RestartSec=5s
KillSignal=SIGTERM
TimeoutStopSec=30s
NoNewPrivileges=true
PrivateTmp=true
[Install]
WantedBy=multi-user.target
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleIdentifier</key>
<string>com.christ.ydisks-xianyu-helper</string>
<key>CFBundleName</key>
<string>Ydisks Xianyu Helper</string>
<key>CFBundleDisplayName</key>
<string>闲鱼管家</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleVersion</key>
<string>__VERSION__</string>
<key>CFBundleShortVersionString</key>
<string>__VERSION__</string>
<key>LSUIElement</key>
<true/>
<key>CFBundleExecutable</key>
<string>xianyu-tray</string>
</dict>
</plist>
+25
View File
@@ -0,0 +1,25 @@
#!/bin/sh
set -eu
VERSION="${1:?version is required}"
DIST_DIR="${2:?dist directory is required}"
ROOT_DIR="$DIST_DIR/pkgroot"
APP="$ROOT_DIR/Applications/Ydisks Xianyu Helper.app"
rm -rf "$ROOT_DIR"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Helpers" "$APP/Contents/Resources"
cp "$DIST_DIR/xianyu-server" "$APP/Contents/Helpers/xianyu-server"
cp "$DIST_DIR/browser-install" "$APP/Contents/Helpers/browser-install"
cp "$DIST_DIR/xianyu-tray" "$APP/Contents/MacOS/xianyu-tray"
cp "$(dirname "$0")/com.christ.ydisks-xianyu-helper.server.plist.template" "$APP/Contents/Resources/"
cp "$(dirname "$0")/com.christ.ydisks-xianyu-helper.tray.plist.template" "$APP/Contents/Resources/"
sed "s/__VERSION__/$VERSION/g" "$(dirname "$0")/Info.plist" > "$APP/Contents/Info.plist"
chmod 0755 "$APP/Contents/MacOS/xianyu-tray" "$APP/Contents/Helpers/xianyu-server" "$APP/Contents/Helpers/browser-install"
pkgbuild \
--root "$ROOT_DIR" \
--scripts "$(dirname "$0")/scripts" \
--identifier com.christ.ydisks-xianyu-helper \
--version "$VERSION" \
--install-location / \
"$DIST_DIR/Ydisks-Xianyu-Helper-$VERSION.pkg"
@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key><string>com.christ.ydisks-xianyu-helper.server</string>
<key>ProgramArguments</key>
<array>
<string>__SERVER__</string>
<string>-addr</string><string>127.0.0.1:8080</string>
<string>-workdir</string><string>__DATA_DIR__</string>
<string>-data-key-file</string><string>__DATA_KEY__</string>
<string>-playwright-driver-dir</string><string>__DRIVER_DIR__</string>
<string>-playwright-browser-dir</string><string>__BROWSER_DIR__</string>
</array>
<key>WorkingDirectory</key><string>__DATA_DIR__</string>
<key>RunAtLoad</key><true/>
<key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
<key>StandardOutPath</key><string>__LOG_DIR__/server.log</string>
<key>StandardErrorPath</key><string>__LOG_DIR__/server.log</string>
</dict>
</plist>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key><string>com.christ.ydisks-xianyu-helper.tray</string>
<key>ProgramArguments</key><array><string>__TRAY__</string></array>
<key>RunAtLoad</key><true/>
<key>KeepAlive</key><true/>
</dict>
</plist>
+64
View File
@@ -0,0 +1,64 @@
#!/bin/sh
set -eu
APP="/Applications/Ydisks Xianyu Helper.app"
SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
SERVER="$APP/Contents/Helpers/xianyu-server"
TRAY="$APP/Contents/MacOS/xianyu-tray"
BROWSER_INSTALL="$APP/Contents/Helpers/browser-install"
CONSOLE_USER="$(stat -f '%Su' /dev/console)"
if [ "$CONSOLE_USER" = "root" ] || [ -z "$CONSOLE_USER" ]; then
echo "没有登录用户,跳过 LaunchAgent 和 Chromium 初始化;登录后请重新打开应用。"
exit 0
fi
UID_VALUE="$(id -u "$CONSOLE_USER")"
HOME_DIR="$(dscl . -read "/Users/$CONSOLE_USER" NFSHomeDirectory | awk '{print $2}')"
DATA_DIR="$HOME_DIR/Library/Application Support/YdisksXianyuHelper"
DRIVER_DIR="$DATA_DIR/playwright-driver"
BROWSER_DIR="$DATA_DIR/playwright-browsers"
LOG_DIR="$HOME_DIR/Library/Logs/YdisksXianyuHelper"
AGENT_DIR="$HOME_DIR/Library/LaunchAgents"
mkdir -p "$DATA_DIR" "$DRIVER_DIR" "$BROWSER_DIR" "$LOG_DIR" "$AGENT_DIR"
chown -R "$CONSOLE_USER" "$DATA_DIR" "$LOG_DIR" "$AGENT_DIR"
escape_sed() {
printf '%s' "$1" | sed 's/[&|]/\\&/g'
}
SERVER_ESCAPED="$(escape_sed "$SERVER")"
TRAY_ESCAPED="$(escape_sed "$TRAY")"
DATA_ESCAPED="$(escape_sed "$DATA_DIR")"
DRIVER_ESCAPED="$(escape_sed "$DRIVER_DIR")"
BROWSER_ESCAPED="$(escape_sed "$BROWSER_DIR")"
LOG_ESCAPED="$(escape_sed "$LOG_DIR")"
DATA_KEY_ESCAPED="$(escape_sed "$DATA_DIR/data-key")"
server_plist="$AGENT_DIR/com.christ.ydisks-xianyu-helper.server.plist"
tray_plist="$AGENT_DIR/com.christ.ydisks-xianyu-helper.tray.plist"
sed -e "s|__SERVER__|$SERVER_ESCAPED|g" \
-e "s|__DATA_DIR__|$DATA_ESCAPED|g" \
-e "s|__DATA_KEY__|$DATA_KEY_ESCAPED|g" \
-e "s|__DRIVER_DIR__|$DRIVER_ESCAPED|g" \
-e "s|__BROWSER_DIR__|$BROWSER_ESCAPED|g" \
-e "s|__LOG_DIR__|$LOG_ESCAPED|g" \
"$APP/Contents/Resources/com.christ.ydisks-xianyu-helper.server.plist.template" > "$server_plist"
sed -e "s|__TRAY__|$TRAY_ESCAPED|g" \
"$APP/Contents/Resources/com.christ.ydisks-xianyu-helper.tray.plist.template" > "$tray_plist"
chown "$CONSOLE_USER" "$server_plist" "$tray_plist"
chmod 0644 "$server_plist" "$tray_plist"
launchctl bootout "gui/$UID_VALUE/com.christ.ydisks-xianyu-helper.server" >/dev/null 2>&1 || true
launchctl bootout "gui/$UID_VALUE/com.christ.ydisks-xianyu-helper.tray" >/dev/null 2>&1 || true
launchctl asuser "$UID_VALUE" env HOME="$HOME_DIR" "$BROWSER_INSTALL" \
-driver-dir "$DRIVER_DIR" -browser-dir "$BROWSER_DIR" >/tmp/ydisks-xianyu-helper-browser-install.log 2>&1 || {
echo "Chromium 自动安装失败,详见 /tmp/ydisks-xianyu-helper-browser-install.log"
}
launchctl bootstrap "gui/$UID_VALUE" "$server_plist"
launchctl bootstrap "gui/$UID_VALUE" "$tray_plist"
launchctl kickstart -k "gui/$UID_VALUE/com.christ.ydisks-xianyu-helper.server"
launchctl kickstart -k "gui/$UID_VALUE/com.christ.ydisks-xianyu-helper.tray"
+43
View File
@@ -0,0 +1,43 @@
#define AppName "Ydisks Xianyu Helper"
#define AppVersion GetEnv("APP_VERSION")
#define AppPublisher "Christ9038"
#define AppExeName "xianyu-server.exe"
#define AppDataDir "{commonappdata}\YdisksXianyuHelper"
[Setup]
AppId={{A6E8B04B-3C8A-4E20-AE62-6B1C3F6B31AE}
AppName={#AppName}
AppVersion={#AppVersion}
AppPublisher={#AppPublisher}
DefaultDirName={autopf}\Ydisks Xianyu Helper
DefaultGroupName={#AppName}
OutputBaseFilename=Ydisks-Xianyu-Helper-Setup
PrivilegesRequired=admin
ArchitecturesInstallIn64BitMode=x64compatible
DisableProgramGroupPage=yes
UninstallDisplayIcon={app}\{#AppExeName}
Compression=lzma2
SolidCompression=yes
[Files]
Source: "dist\windows\xianyu-server.exe"; DestDir: "{app}"; Flags: ignoreversion
Source: "dist\windows\browser-install.exe"; DestDir: "{app}"; Flags: ignoreversion
Source: "dist\windows\xianyu-tray.exe"; DestDir: "{app}"; Flags: ignoreversion
[Dirs]
Name: "{#AppDataDir}\data"
Name: "{#AppDataDir}\playwright-driver"
Name: "{#AppDataDir}\playwright-browsers"
[Registry]
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-driver-dir {#AppDataDir}\playwright-driver -playwright-browser-dir {#AppDataDir}\playwright-browsers"" start= delayed-auto"; Flags: runhidden waituntilterminated
Filename: "{app}\browser-install.exe"; Parameters: "-driver-dir ""{#AppDataDir}\playwright-driver"" -browser-dir ""{#AppDataDir}\playwright-browsers"""; Flags: waituntilterminated
Filename: "{sys}\sc.exe"; Parameters: "start YdisksXianyuHelper"; Flags: runhidden waituntilterminated
Filename: "{app}\xianyu-tray.exe"; Description: "启动菜单栏控制器"; Flags: nowait postinstall skipifsilent
[UninstallRun]
Filename: "{sys}\sc.exe"; Parameters: "stop YdisksXianyuHelper"; Flags: runhidden waituntilterminated
Filename: "{sys}\sc.exe"; Parameters: "delete YdisksXianyuHelper"; Flags: runhidden waituntilterminated