Compare commits

...
Author SHA1 Message Date
Christ 542241d241 统一 Docker Chromium 构建缓存与主分支发布流程
- 使用 node:latest 作为 Docker 构建与运行时基础镜像,移除最终镜像中的 apt 更新和 Debian Chromium 依赖。

- 在 GitHub Actions 中按目标架构缓存并校验 Playwright driver、Chromium 与 headless shell runtime,Docker 和桌面端复用一致的版本校验逻辑。

- 让桌面端安装包工作流同时支持 main 与 codex/desktop-packaging 分支,保持 Linux 原生架构构建并避免 QEMU。

- 明确 main 发布 main、latest 标签,功能分支发布 desktop-packaging、alpha 标签。

- 同步 Compose 默认端口、Node.js 路径、健康检查及部署文档。
2026-08-12 22:30:45 +08:00
Christ 2df324647a 完善三平台安装包与服务控制流程
统一服务默认端口为 59188,完善 Windows 服务权限与 macOS LaunchAgent 管理。

实现 Windows 与 macOS 托盘状态机、服务启停等待、单实例保护、日志目录入口和退出前清理后台服务。

统一 Linux、Windows、macOS 与 Docker 的 Playwright Chromium runtime 构建流程,增加缓存、架构校验和 Linux 原生 runner,避免 QEMU。

完善 Windows、macOS、Linux 安装包及签名打包脚本,修正 Chromium 嵌入、服务注册和安装卸载流程。

同步 README、AGENTS、官网首页、Wiki 与前端开发文档,统一端口、初始化、服务、日志、托盘和安装说明。
2026-08-12 20:53:53 +08:00
Christ 94f4e070f6 统一 Chromium 构建与发布流程
统一独立安装包与 Docker 镜像的 Playwright Chromium 来源,固定使用 go.mod 对应的 Playwright 版本,避免依赖 Debian 仓库中的 chromium 包。

- Docker 多架构构建阶段按 debian13 目标架构下载 Chromium,并通过 Playwright 安装系统运行库。

- Linux、Windows、macOS 安装包在 GitHub Actions 构建阶段预下载并打包对应架构的 driver 与 Chromium。

- 为 Linux、Windows、macOS runtime 增加 GitHub Actions 缓存,缓存键绑定依赖和下载程序版本。

- Linux 安装过程改为复制内置 runtime,仅安装系统依赖,不再安装时下载浏览器。

- 修复使用外部 Node.js 时 Playwright runtime 的就绪检测,并补充相关测试。

- codex/desktop-packaging 分支启用 Docker CI,发布 alpha 标签,不覆盖 latest。

- 同步更新 Docker Compose 配置和部署文档。
2026-08-12 17:35:45 +08:00
Christ 6032dfed0f feat: 支持通过管理页面完成首次初始化
初始化流程:

- 新增一次性 POST /initialize 接口,仅在系统尚未存在管理员时允许创建账号。

- 校验管理员密码不少于 8 个字符,初始化成功后自动建立会话并登录。

- 增加初始化并发保护,避免首次打开多个页面时互相覆盖密码。

前端与资源:

- 将初始化页面改为密码和确认密码表单,移除普通用户需要执行的 CLI 命令和数据库路径提示。

- 初始化成功后直接进入管理后台,并重新构建嵌入式前端资源。

- 增加未初始化接口回归测试和自动登录验证。

文档同步:

- 更新 README、文档站、GitHub Wiki、前端说明和 AGENTS.md。

- 明确 Docker 使用 XIANYU_ADMIN_PASSWORD 非交互初始化。

- 明确独立二进制和 Linux 安装包通过 Web 页面初始化,CLI 仅作为无浏览器或运维备用方式。

- 同步桌面端 Chromium runtime 内置、Linux 安装流程和 Windows/macOS 签名包说明。
2026-08-12 03:04:28 +08:00
Christ 80baba46ff fix: 修复 macOS runtime 执行权限与架构包上传
- 在 pkgbuild 前将 Playwright Node、Chromium 及其他 Mach-O 文件统一设置为 0755,避免安装后普通用户启动服务时出现 permission denied。

- 将 macOS arm64 与 amd64 安装包分别上传为独立 Artifact,避免用户下载包含另一架构的无用文件。
2026-08-12 02:17:38 +08:00
Christ b7444e8090 fix: 调整 macOS Chromium 嵌套签名顺序
- 跳过 Chromium bundle 内部 Mach-O 的提前单独签名,避免主程序触发未完成 Framework 校验。

- 仅签名 bundle 外的独立二进制,并按目录深度递归签名 app、framework 和 xpc 组件。
2026-08-12 01:57:42 +08:00
Christ fed5d582e7 fix: 修复 macOS Chromium 签名与缓存保存
- 对 Chromium 内嵌的 Helper App、Framework 和外层应用执行递归签名,并改用临时清单传递路径,保留真实签名错误。

- 将 macOS Playwright runtime 缓存拆分为恢复和保存步骤,在 runtime 下载完成后立即写入缓存,并增加前缀回退键。
2026-08-12 01:46:50 +08:00
Christ 0bafa50dbf fix: 修复桌面安装包签名与 Windows 服务参数
- 按目录深度签名 macOS Chromium 内嵌 framework、xpc 和应用组件,避免 amd64 构建留下未签名 Mach-O 文件。

- 修正 Inno Setup 中 xianyu-server 和 Playwright runtime 路径的嵌套引号,确保 Windows 安装器可以正常编译并注册服务。
2026-08-12 01:30:41 +08:00
Christ 3aabc3e8e4 ci: 缓存桌面端 Chromium runtime
为 Windows amd64 以及 macOS arm64 和 amd64 runtime 增加 GitHub Actions 缓存。

缓存键绑定操作系统、架构和 go.mod 哈希;命中缓存时跳过 Chromium 与 Playwright driver 下载,Playwright 版本变化后自动生成新缓存。

使用 actions/cache@v6,并通过 cache-hit 控制 runtime 预下载步骤。
2026-08-12 01:13:45 +08:00
Christ 1ac6912c7b feat: 拆分 macOS 架构安装包并内置浏览器运行时
将 macOS 安装包拆分为 arm64 与 amd64 两个独立产物,每个安装包只携带对应架构的服务、托盘程序、Playwright driver 和 Chromium。

调整桌面端 CI,在构建阶段预下载并组装 Playwright runtime;服务启动时按当前进程架构解析 runtime 根目录,避免安装后联网下载 Chromium。

移除 Windows/macOS 安装阶段的 browser-install 调用和托盘中的安装/修复 Chromium 菜单,保留 Linux 安装脚本的既有流程。

升级 Playwright Go 依赖到 v0.6100.0,并迁移导入路径;仅按本次授权修改 CAPTCHA 相关文件的 import 行,不改变 CAPTCHA 行为。

验证:go test ./...、go vet ./...、macOS 安装脚本语法、Workflow YAML 语法、Windows amd64 交叉编译及两个 macOS pkg 的本地组装。
2026-08-12 01:09:59 +08:00
Christ d4e9717570 fix: 按系统规范解析桌面服务数据目录
macOS 和 Windows 在未显式指定工作目录时,通过 Go 的用户配置目录接口解析 YdisksXianyuHelper 数据目录;macOS LaunchAgent 不再注入数据库、密钥和浏览器目录参数。

服务自动创建数据目录及 data 子目录,将默认 SQLite 数据库放置到系统用户数据目录,修复 macOS 服务因 data/xianyu_data.db 父目录不存在而启动即退出的问题。

保留显式工作目录、Windows 现有 ProgramData 数据布局以及 Linux/Docker 的默认相对路径行为,并补充服务目录解析和数据库路径测试。

删除名称为桌面端 CI 的 GitHub Actions Workflow,保留桌面安装包构建发布 Workflow。
2026-08-12 00:19:14 +08:00
Christ bfa72fd9b7 feat: 重构 macOS 安装目录与卸载流程
将 macOS 应用固定安装到 /Applications/Ydisks闲鱼助手/,应用包和托盘可执行文件统一使用 Ydisks闲鱼助手 名称。

托盘菜单栏不再显示文字标题,根据后台服务健康状态切换彩色和黑白图标。

新增完整卸载程序,停止新旧 LaunchAgent 及遗留进程,删除应用、服务配置、用户数据、Chromium 缓存和日志,并清理安装包收据。

修正 postinstall 和 preinstall 的应用路径处理,避免 macOS localized 路径导致服务 plist 生成失败。
2026-08-11 23:53:24 +08:00
Christ 9cb50a229c fix: 兼容 macOS localized 应用安装路径
macOS 安装器可能将应用放入 Ydisks Xianyu Helper.localized 目录,安装脚本改为自动发现普通路径和 localized 路径,避免 postinstall 找不到模板文件。
2026-08-11 23:27:33 +08:00
Christ 13b57891fb fix: 使用 macOS 26 Assets.car 图标方案
恢复仓库提供的 Xcode 26 Assets.car,并通过 CFBundleIconName=AppIcon 接入 macOS 26 新图标方案,同时保留 icns 兼容旧版 macOS。
2026-08-11 23:14:19 +08:00
Christ 8c5c305221 chore: 移除 macOS 图标构建副产物
安装包只需要 icon.icns,不提交 iconutil 生成的 Assets.car 临时文件。
2026-08-11 23:07:44 +08:00
Christ 137a08489d feat: 接入统一桌面端产品图标
使用根目录 icon 资源替换托盘占位图标,并为 macOS App、Windows 安装器和 Linux 安装脚本接入对应图标格式。
2026-08-11 23:07:13 +08:00
Christ 07fea7d1e6 fix: 修复 macOS 旧版本升级安装失败
安装前卸载旧 Bundle ID 对应的应用与 LaunchAgent,避免安装器因组件标识变化保留旧应用,导致 postinstall 找不到新版本资源模板。
2026-08-11 22:51:40 +08:00
Christ 761d57f9bf fix: 增加 macOS 安装失败日志
将 postinstall 的完整执行过程和退出码写入 /var/log/ydisks-xianyu-helper-install.log。

记录 LaunchAgent 注册、用户目录解析和 Chromium 初始化输出,便于定位安装失败原因。
2026-08-11 22:44:19 +08:00
Christ 3d715e916b fix: 修复托盘进程无法退出
将 macOS 托盘 LaunchAgent 的 KeepAlive 设置为 false,避免用户退出后被 launchd 立即拉起。

托盘退出菜单主动卸载当前 LaunchAgent,再结束托盘进程。

保留旧版本通过 launchctl bootout 清理服务的升级恢复路径。
2026-08-11 22:40:46 +08:00
Christ 07e91afc22 fix: 统一 macOS 应用与服务标识
将 macOS Bundle ID、pkg identifier 和 LaunchAgent 服务标识统一为 com.ydisks.xianyu-helper。

使用 com.ydisks.xianyu-helper.server 管理后台服务,使用 com.ydisks.xianyu-helper.tray 管理托盘控制器。

升级安装时清理旧版 com.christ.ydisks-xianyu-helper LaunchAgent,避免新旧服务重复运行。
2026-08-11 22:02:43 +08:00
Christ 733a536031 fix: 修复托盘服务控制无效问题
修正 macOS LaunchAgent 服务标签,使用 bootstrap 和 bootout 管理服务,避免 KeepAlive 导致停止后立即重启。

Windows 托盘操作通过 UAC 提权执行 sc.exe,支持普通用户控制管理员安装的 Windows 服务。

显示服务启动、停止和重启失败原因,避免静默丢弃控制命令错误。

其他平台明确返回不支持错误,并完成本机及 Windows、macOS 交叉编译验证。
2026-08-11 21:56:27 +08:00
Christ c21a3a33dc fix: 修正 macOS 安装包签名身份识别
将安装包证书的信任策略调整为 basic,匹配 productsign 对 Installer Signing Identity 的校验。

通过管理员 Trust Settings 写入证书信任,不再把证书重复导入临时钥匙串,保持证书与私钥身份匹配。

保留应用 codeSign 信任与临时钥匙串搜索列表。
2026-08-11 21:44:35 +08:00
Christ 86d659cf40 fix: 避免 macOS 签名导入触发交互确认
使用临时钥匙串和 -A 授权导入签名身份,移除会触发用户交互的分区列表配置。

通过 GitHub macOS runner 的免密码 sudo 写入 codeSign 与 pkgSign 管理员信任设置。

保留临时钥匙串搜索列表,确保 codesign 和 productsign 可以找到应用及安装包签名身份。
2026-08-11 21:35:03 +08:00
Christ f0accce14a ci: 为 macOS 安装包增加产品签名
新增独立的 macOS Installer Signing Identity,并在构建流程中导入安装包 P12。

先使用应用签名证书签名 App 及内部组件,再使用 productsign 签名最终 pkg。

使用 pkgutil 校验安装包签名,签名失败时终止 macOS 构建。

安装包证书复用现有 MACOS_SIGNING_P12_PASSWORD,不改变 Linux 和 Docker 部署流程。
2026-08-11 21:00:44 +08:00
Christ 430fbc0767 ci: 接入桌面安装包自签名流程
读取并使用 Windows PFX 证书签名三个桌面二进制文件。

在 Inno Setup 生成安装器后继续签名最终安装器,并将已签名二进制打入归档。

导入 macOS P12 到临时钥匙串,建立代码签名信任,并按由内到外顺序签名 App 及其内部组件。

对 macOS App 执行深度签名校验,签名失败时终止构建。

保持 Linux 安装包与现有 Docker 部署流程不变。
2026-08-11 20:53:47 +08:00
Christ bac5aa0c4f ci: 升级 GitHub Actions 到 Node.js 24 兼容版本
将 checkout、setup-go、setup-node 和 upload-artifact 升级到官方当前版本,消除 GitHub Actions 对 Node.js 20 的弃用警告。

同步升级 Docker QEMU、Buildx、登录、元数据和镜像构建插件,并保持现有分支触发条件与 Docker 发布行为不变。
2026-08-11 20:12:01 +08:00
Christ 07b5be626b fix: 修正 Windows 安装器二进制路径
Inno Setup 的 Source 路径改为相对于 packaging/windows/installer.iss 定位仓库根目录下的 dist/windows 构建产物,修复 GitHub Actions 找不到 xianyu-server.exe、browser-install.exe 和 xianyu-tray.exe 的问题。
2026-08-11 20:08:51 +08:00
Christ a99ea5c20d 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 工作流不变。

补充数据密钥持久化、托盘图标、安装文档及相关测试。
2026-08-11 19:52:34 +08:00
Christ 1204655170 merge: 合并同步生命周期与前端视觉治理 2026-08-10 12:41:16 +08:00
82 changed files with 3824 additions and 314 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
+3
View File
@@ -14,3 +14,6 @@ init-admin
*.sqlite
*.sqlite3
cover.out
!/.docker/
!/.docker/playwright-runtime/
!/.docker/playwright-runtime/**
+1 -1
View File
@@ -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
+416
View File
@@ -0,0 +1,416 @@
name: 构建桌面端安装包
on:
push:
branches:
- main
- 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 安装包 (${{ matrix.arch }})
if: github.ref == 'refs/heads/main' || github.ref == 'refs/heads/codex/desktop-packaging'
runs-on: ${{ matrix.runner }}
strategy:
fail-fast: false
matrix:
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
- name: 配置 Go
uses: actions/setup-go@v7
with:
go-version-file: go.mod
cache: true
- name: 配置 Node.js
uses: actions/setup-node@v6
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
- name: 缓存 Linux Chromium runtime
id: cache-linux-playwright
uses: actions/cache@v5
with:
path: dist/ydisks-xianyu-helper-linux-${{ matrix.arch }}/playwright-runtime
key: ydisks-playwright-runtime-v6-linux-${{ matrix.arch }}-${{ hashFiles('go.mod', 'go.sum') }}
- 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"
mkdir -p "$runtime_dir/playwright-driver" "$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 架构
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 -o -name chrome-headless-shell \) -perm -111 -print -quit)"
test -n "$chromium_path"
chromium_revision="$(RUNTIME_SPEC="$runtime_dir/playwright-driver/package/browsers.json" node -e 'const b=require(process.env.RUNTIME_SPEC).browsers; console.log(b.find(x=>x.name==="chromium").revision)')"
headless_revision="$(RUNTIME_SPEC="$runtime_dir/playwright-driver/package/browsers.json" node -e 'const b=require(process.env.RUNTIME_SPEC).browsers; console.log(b.find(x=>x.name==="chromium-headless-shell").revision)')"
test -d "$runtime_dir/playwright-browsers/chromium-$chromium_revision"
test -d "$runtime_dir/playwright-browsers/chromium_headless_shell-$headless_revision"
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: |
set -Eeuo pipefail
package_dir="dist/ydisks-xianyu-helper-linux-${{ matrix.arch }}"
cp icon/linux/icon.png "$package_dir/icon.png"
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-${{ matrix.arch }}-${APP_VERSION}.tar.gz" "$(basename "$package_dir")"
- name: 上传 Linux 安装包
uses: actions/upload-artifact@v7
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/main' || github.ref == 'refs/heads/codex/desktop-packaging'
runs-on: windows-latest
steps:
- name: 检出代码
uses: actions/checkout@v6
- name: 配置 Go
uses: actions/setup-go@v7
with:
go-version-file: go.mod
cache: true
- name: 配置 Node.js
uses: actions/setup-node@v6
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: |
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: |
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: 缓存 Windows Chromium runtime
id: cache-windows-playwright
uses: actions/cache@v5
with:
path: dist/windows/playwright-runtime/amd64
key: ydisks-playwright-runtime-v6-windows-amd64-${{ hashFiles('go.mod', 'go.sum') }}
- name: 预下载 Windows Chromium runtime
if: steps.cache-windows-playwright.outputs.cache-hit != 'true'
shell: pwsh
run: |
New-Item -ItemType Directory -Force -Path dist/windows/playwright-runtime/amd64/playwright-driver | Out-Null
New-Item -ItemType Directory -Force -Path dist/windows/playwright-runtime/amd64/playwright-browsers | Out-Null
& dist/windows/browser-install.exe `
-driver-dir "$PWD/dist/windows/playwright-runtime/amd64/playwright-driver" `
-browser-dir "$PWD/dist/windows/playwright-runtime/amd64/playwright-browsers"
if ($LASTEXITCODE -ne 0) { throw 'Windows Playwright runtime 下载失败' }
- name: 校验 Windows Chromium runtime
shell: pwsh
run: |
$runtimeRoot = Resolve-Path 'dist/windows/playwright-runtime/amd64'
$driverNode = Join-Path $runtimeRoot 'playwright-driver/node.exe'
$driverCli = Join-Path $runtimeRoot 'playwright-driver/package/cli.js'
if (-not (Test-Path -LiteralPath $driverNode -PathType Leaf)) { throw 'Windows Playwright driver 缺少 node.exe' }
if (-not (Test-Path -LiteralPath $driverCli -PathType Leaf)) { throw 'Windows Playwright driver 缺少 package/cli.js' }
$browserSpec = Get-Content -Raw -LiteralPath (Join-Path $runtimeRoot 'playwright-driver/package/browsers.json') | ConvertFrom-Json
$chromiumRevision = ($browserSpec.browsers | Where-Object name -eq 'chromium').revision
$headlessRevision = ($browserSpec.browsers | Where-Object name -eq 'chromium-headless-shell').revision
if (-not (Test-Path -LiteralPath (Join-Path $runtimeRoot "playwright-browsers/chromium-$chromiumRevision") -PathType Container)) { throw 'Windows Chromium revision 与 driver 不匹配' }
if (-not (Test-Path -LiteralPath (Join-Path $runtimeRoot "playwright-browsers/chromium_headless_shell-$headlessRevision") -PathType Container)) { throw 'Windows headless shell revision 与 driver 不匹配' }
$chromium = Get-ChildItem -LiteralPath (Join-Path $runtimeRoot 'playwright-browsers') -Recurse -File |
Where-Object { $_.Name -in @('chrome.exe', 'headless_shell.exe', 'chrome-headless-shell.exe') } |
Select-Object -First 1
if ($null -eq $chromium) { throw 'Windows Chromium runtime 缺少 Chromium 可执行文件' }
- name: 导入 Windows 签名证书
shell: pwsh
env:
WINDOWS_SIGNING_PFX_BASE64: ${{ secrets.WINDOWS_SIGNING_PFX_BASE64 }}
WINDOWS_SIGNING_PFX_PASSWORD: ${{ secrets.WINDOWS_SIGNING_PFX_PASSWORD }}
WINDOWS_SIGNING_IDENTITY: ${{ secrets.WINDOWS_SIGNING_IDENTITY }}
run: |
$pfxPath = Join-Path $env:RUNNER_TEMP 'ydisks-windows-signing.pfx'
[IO.File]::WriteAllBytes($pfxPath, [Convert]::FromBase64String($env:WINDOWS_SIGNING_PFX_BASE64))
if (-not (Test-Path -LiteralPath $pfxPath -PathType Leaf)) { throw 'Windows PFX 文件写入失败' }
"WINDOWS_SIGNING_PFX_PATH=$pfxPath" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
- name: 签名 Windows 桌面程序
shell: pwsh
env:
WINDOWS_SIGNING_PFX_PASSWORD: ${{ secrets.WINDOWS_SIGNING_PFX_PASSWORD }}
WINDOWS_SIGNING_IDENTITY: ${{ secrets.WINDOWS_SIGNING_IDENTITY }}
run: |
& packaging/windows/sign.ps1 `
-PfxPath $env:WINDOWS_SIGNING_PFX_PATH `
-Files 'dist/windows/xianyu-server.exe','dist/windows/xianyu-tray.exe'
- 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 }
- name: 签名 Windows 安装器
shell: pwsh
env:
WINDOWS_SIGNING_PFX_PASSWORD: ${{ secrets.WINDOWS_SIGNING_PFX_PASSWORD }}
WINDOWS_SIGNING_IDENTITY: ${{ secrets.WINDOWS_SIGNING_IDENTITY }}
run: |
& packaging/windows/sign.ps1 `
-PfxPath $env:WINDOWS_SIGNING_PFX_PATH `
-Files 'dist/windows/Ydisks-Xianyu-Helper-Setup.exe'
- name: 打包 Windows 二进制归档
shell: pwsh
env:
APP_VERSION: ${{ env.APP_VERSION }}
run: |
Compress-Archive -Path dist/windows/xianyu-server.exe,dist/windows/xianyu-tray.exe,dist/windows/playwright-runtime -DestinationPath "dist/windows/Ydisks-Xianyu-Helper-${env:APP_VERSION}-binaries.zip"
- name: 上传 Windows 安装包
uses: actions/upload-artifact@v7
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/main' || github.ref == 'refs/heads/codex/desktop-packaging'
runs-on: macos-14
steps:
- name: 检出代码
uses: actions/checkout@v6
- name: 配置 Go
uses: actions/setup-go@v7
with:
go-version-file: go.mod
cache: true
- name: 配置 Node.js
uses: actions/setup-node@v6
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: go test ./cmd/tray
- 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
- name: 缓存 macOS Chromium runtime
id: cache-macos-playwright
uses: actions/cache/restore@v5
with:
path: |
dist/macos/playwright-runtime/arm64
dist/macos/playwright-runtime/amd64
key: ydisks-playwright-runtime-v6-macos-universal-${{ hashFiles('go.mod', 'go.sum') }}
- name: 预下载 macOS Chromium runtime
if: steps.cache-macos-playwright.outputs.cache-hit != 'true'
run: |
set -Eeuo pipefail
mkdir -p dist/macos/playwright-runtime/arm64/playwright-driver
mkdir -p dist/macos/playwright-runtime/arm64/playwright-browsers
mkdir -p dist/macos/playwright-runtime/amd64/playwright-driver
mkdir -p dist/macos/playwright-runtime/amd64/playwright-browsers
PLAYWRIGHT_HOST_PLATFORM_OVERRIDE=mac14-arm64 \
dist/macos/arm64/browser-install \
-driver-dir "$PWD/dist/macos/playwright-runtime/arm64/playwright-driver" \
-browser-dir "$PWD/dist/macos/playwright-runtime/arm64/playwright-browsers"
PLAYWRIGHT_HOST_PLATFORM_OVERRIDE=mac14 \
arch -x86_64 dist/macos/amd64/browser-install \
-driver-dir "$PWD/dist/macos/playwright-runtime/amd64/playwright-driver" \
-browser-dir "$PWD/dist/macos/playwright-runtime/amd64/playwright-browsers"
- name: 保存 macOS Chromium runtime 缓存
if: steps.cache-macos-playwright.outputs.cache-hit != 'true'
uses: actions/cache/save@v5
with:
path: |
dist/macos/playwright-runtime/arm64
dist/macos/playwright-runtime/amd64
key: ${{ steps.cache-macos-playwright.outputs.cache-primary-key }}
- name: 导入 macOS 签名证书
env:
MACOS_SIGNING_P12_BASE64: ${{ secrets.MACOS_SIGNING_P12_BASE64 }}
MACOS_INSTALLER_SIGNING_P12_BASE64: ${{ secrets.MACOS_INSTALLER_SIGNING_P12_BASE64 }}
MACOS_SIGNING_P12_PASSWORD: ${{ secrets.MACOS_SIGNING_P12_PASSWORD }}
MACOS_SIGNING_IDENTITY: ${{ secrets.MACOS_SIGNING_IDENTITY }}
MACOS_INSTALLER_SIGNING_IDENTITY: ${{ secrets.MACOS_INSTALLER_SIGNING_IDENTITY }}
run: |
set -Eeuo pipefail
keychain_path="$RUNNER_TEMP/ydisks-signing.keychain-db"
keychain_password="$(uuidgen)"
app_p12_path="$RUNNER_TEMP/ydisks-signing-app.p12"
app_cert_path="$RUNNER_TEMP/ydisks-signing-app.pem"
installer_p12_path="$RUNNER_TEMP/ydisks-signing-installer.p12"
installer_cert_path="$RUNNER_TEMP/ydisks-signing-installer.pem"
printf '%s' "$MACOS_SIGNING_P12_BASE64" | base64 --decode > "$app_p12_path"
printf '%s' "$MACOS_INSTALLER_SIGNING_P12_BASE64" | base64 --decode > "$installer_p12_path"
security create-keychain -p "$keychain_password" "$keychain_path"
security set-keychain-settings -lut 21600 "$keychain_path"
security unlock-keychain -p "$keychain_password" "$keychain_path"
# 临时 CI 钥匙串使用 -A 授权签名工具,避免 set-key-partition-list 触发交互确认。
security import "$app_p12_path" -k "$keychain_path" -P "$MACOS_SIGNING_P12_PASSWORD" -A
security import "$installer_p12_path" -k "$keychain_path" -P "$MACOS_SIGNING_P12_PASSWORD" -A
security find-certificate -c "$MACOS_SIGNING_IDENTITY" -p "$keychain_path" > "$app_cert_path"
security find-certificate -c "$MACOS_INSTALLER_SIGNING_IDENTITY" -p "$keychain_path" > "$installer_cert_path"
# GitHub macOS hosted runner 提供免密码 sudo;只修改 admin Trust Settings,避免弹认证对话框。
# 不传 -k,避免 sudo 以 root 身份把同一张证书重复写入临时钥匙串,破坏私钥匹配。
sudo -n security add-trusted-cert -d -r trustRoot -p codeSign "$app_cert_path"
sudo -n security add-trusted-cert -d -r trustRoot -p basic "$installer_cert_path"
security list-keychains -d user -s "$keychain_path"
security unlock-keychain -p "$keychain_password" "$keychain_path"
echo "MACOS_SIGNING_KEYCHAIN=$keychain_path" >> "$GITHUB_ENV"
- name: 构建 macOS arm64 与 amd64 安装包
env:
MACOS_SIGNING_IDENTITY: ${{ secrets.MACOS_SIGNING_IDENTITY }}
MACOS_INSTALLER_SIGNING_IDENTITY: ${{ secrets.MACOS_INSTALLER_SIGNING_IDENTITY }}
run: |
set -Eeuo pipefail
chmod +x packaging/macos/build-pkg.sh
for arch in arm64 amd64; do
packaging/macos/build-pkg.sh "$APP_VERSION" "$PWD/dist/macos" "$arch"
done
- name: 上传 macOS arm64 安装包
uses: actions/upload-artifact@v7
with:
name: ydisks-xianyu-helper-macos-arm64-${{ env.APP_VERSION }}
path: dist/macos/Ydisks-Xianyu-Helper-${{ env.APP_VERSION }}-arm64.pkg
if-no-files-found: error
- name: 上传 macOS amd64 安装包
uses: actions/upload-artifact@v7
with:
name: ydisks-xianyu-helper-macos-amd64-${{ env.APP_VERSION }}
path: dist/macos/Ydisks-Xianyu-Helper-${{ env.APP_VERSION }}-amd64.pkg
if-no-files-found: error
+172 -23
View File
@@ -4,6 +4,7 @@ on:
push:
branches:
- main
- codex/desktop-packaging
workflow_dispatch:
permissions:
@@ -15,21 +16,149 @@ 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
playwright_platform: debian13-x64
- arch: arm64
runner: ubuntu-24.04-arm
platform: linux/arm64
playwright_platform: debian13-arm64
steps:
- name: 检出代码
uses: actions/checkout@v4
uses: actions/checkout@v6
- name: 配置 QEMU
uses: docker/setup-qemu-action@v3
- 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: 配置 Go
uses: actions/setup-go@v7
with:
go-version-file: go.mod
cache: true
- name: 缓存 Docker Chromium runtime
id: cache-docker-playwright
uses: actions/cache@v5
with:
path: .docker/playwright-runtime/${{ matrix.arch }}
key: ydisks-playwright-runtime-v6-docker-${{ matrix.arch }}-${{ hashFiles('go.mod', 'go.sum') }}
- name: 准备 Docker Chromium runtime
if: steps.cache-docker-playwright.outputs.cache-hit != 'true'
shell: bash
env:
GOARCH: ${{ matrix.arch }}
PLAYWRIGHT_HOST_PLATFORM_OVERRIDE: ${{ matrix.playwright_platform }}
run: |
set -Eeuo pipefail
mkdir -p ".docker/playwright-runtime/$GOARCH/playwright-driver" ".docker/playwright-runtime/$GOARCH/playwright-browsers"
GOOS=linux GOARCH="$GOARCH" CGO_ENABLED=0 go build \
-trimpath -ldflags='-s -w' \
-o "$RUNNER_TEMP/browser-install" ./cmd/browser-install
"$RUNNER_TEMP/browser-install" \
-driver-dir "$PWD/.docker/playwright-runtime/$GOARCH/playwright-driver" \
-browser-dir "$PWD/.docker/playwright-runtime/$GOARCH/playwright-browsers"
- name: 校验 Docker Chromium runtime
shell: bash
env:
GOARCH: ${{ matrix.arch }}
run: |
set -Eeuo pipefail
runtime_dir=".docker/playwright-runtime/$GOARCH"
test -x "$runtime_dir/playwright-driver/node"
test -f "$runtime_dir/playwright-driver/package/cli.js"
chromium_path="$(find "$runtime_dir/playwright-browsers" -type f \
\( -name chrome -o -name headless_shell -o -name chrome-headless-shell \) -perm -111 -print -quit)"
test -n "$chromium_path"
chromium_revision="$(RUNTIME_SPEC="$runtime_dir/playwright-driver/package/browsers.json" node -e 'const b=require(process.env.RUNTIME_SPEC).browsers; console.log(b.find(x=>x.name==="chromium").revision)')"
headless_revision="$(RUNTIME_SPEC="$runtime_dir/playwright-driver/package/browsers.json" node -e 'const b=require(process.env.RUNTIME_SPEC).browsers; console.log(b.find(x=>x.name==="chromium-headless-shell").revision)')"
test -d "$runtime_dir/playwright-browsers/chromium-$chromium_revision"
test -d "$runtime_dir/playwright-browsers/chromium_headless_shell-$headless_revision"
- name: 配置 Docker Buildx
uses: docker/setup-buildx-action@v3
uses: docker/setup-buildx-action@v4
- name: 登录 GitHub Container Registry
uses: docker/login-action@v3
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: 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 }}
@@ -42,26 +171,46 @@ jobs:
- name: 生成镜像标签
id: meta
uses: docker/metadata-action@v5
uses: docker/metadata-action@v6
with:
images: ${{ steps.image.outputs.name }}
tags: |
type=ref,event=branch
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=sha,format=long
type=raw,value=main,enable=${{ github.ref == 'refs/heads/main' }}
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }}
type=raw,value=desktop-packaging,enable=${{ github.ref == 'refs/heads/codex/desktop-packaging' }}
type=raw,value=alpha,enable=${{ github.ref == 'refs/heads/codex/desktop-packaging' }}
- name: 构建并推送镜像
uses: docker/build-push-action@v6
with:
context: .
file: Dockerfile.debian13
platforms: linux/amd64,linux/arm64
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
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"
+1 -1
View File
@@ -19,7 +19,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: 检出主分支文档
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
ref: main
+87 -5
View File
@@ -4,7 +4,7 @@
The active application contains:
- `cmd/server/` — server entrypoint, administrator bootstrap (`-init-admin`), and HTTP server.
- `cmd/server/` — server entrypoint, administrator bootstrap (`/initialize` and `-init-admin`), and HTTP server.
- `cmd/init-admin/` — interactive administrator initialization CLI.
- `cmd/dbverify/` — migration + core CRUD verification tool across SQLite/MySQL/Postgres.
- `internal/server/` — chi HTTP API and SPA serving.
@@ -34,14 +34,18 @@ 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
and confirms an administrator password, creates the `admin` user, and signs the user in automatically.
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:
@@ -85,7 +89,85 @@ 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 Docker final image uses
`node:latest`, copies the cached runtime prepared by CI, and does not run `apt-get update`. The desktop CI workflow
runs on `main` and `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 `main` and `latest` from `main`, `desktop-packaging` and `alpha` 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
+52 -26
View File
@@ -1,21 +1,12 @@
# syntax=docker/dockerfile:1.7
FROM --platform=$BUILDPLATFORM node:22-trixie AS frontend
FROM --platform=$BUILDPLATFORM node:latest AS frontend
WORKDIR /src/frontend
COPY frontend/package*.json ./
RUN npm ci
COPY frontend/ ./
RUN npm run build
FROM --platform=$BUILDPLATFORM node:22-trixie AS playwright-driver
RUN npm install -g playwright@1.57.0 \
&& mkdir -p /ms-playwright-go/package \
&& cp -a /usr/local/lib/node_modules/playwright/. /ms-playwright-go/package/ \
&& if [ -d /usr/local/lib/node_modules/playwright-core ]; then \
mkdir -p /ms-playwright-go/package/node_modules \
&& cp -a /usr/local/lib/node_modules/playwright-core /ms-playwright-go/package/node_modules/playwright-core; \
fi
FROM --platform=$BUILDPLATFORM golang:1.26-trixie AS backend
ARG TARGETOS
ARG TARGETARCH
@@ -28,28 +19,63 @@ RUN CGO_ENABLED=0 GOOS="$TARGETOS" GOARCH="$TARGETARCH" go build -trimpath -ldfl
&& CGO_ENABLED=0 GOOS="$TARGETOS" GOARCH="$TARGETARCH" go build -trimpath -ldflags="-s -w" -o /out/xianyu-dbseed ./cmd/dbseed \
&& CGO_ENABLED=0 GOOS="$TARGETOS" GOARCH="$TARGETARCH" go build -trimpath -ldflags="-s -w" -o /out/xianyu-dbverify ./cmd/dbverify
FROM debian:13-slim AS runtime
# 本地 Docker 构建没有主机 runtime 缓存时使用此工具下载一次;CI 会优先复制缓存,
# 不会走这个兜底路径。
FROM --platform=$BUILDPLATFORM golang:1.26-trixie AS browser-install-builder
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY cmd/browser-install ./cmd/browser-install
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/browser-install-host ./cmd/browser-install
# Docker CI 会把与独立安装包相同的目标架构 runtime 放到
# .docker/playwright-runtime,构建时直接复制,不在 Dockerfile 内重复下载浏览器。
FROM --platform=$BUILDPLATFORM node:latest AS playwright-runtime
ARG TARGETARCH
ENV PLAYWRIGHT_DRIVER_PATH=/ms-playwright-go
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright
ENV PLAYWRIGHT_NODEJS_PATH=/usr/local/bin/node
COPY --from=browser-install-builder /out/browser-install-host /usr/local/bin/browser-install
COPY .docker/playwright-runtime /prebuilt-playwright-runtime
RUN set -eux; \
mkdir -p /ms-playwright-go /ms-playwright; \
case "$TARGETARCH" in \
amd64) runtime_arch=amd64 ;; \
arm64) runtime_arch=arm64 ;; \
*) echo "不支持的 Docker 架构:$TARGETARCH" >&2; exit 1 ;; \
esac; \
if [ -f "/prebuilt-playwright-runtime/$runtime_arch/playwright-driver/package/cli.js" ]; then \
cp -R "/prebuilt-playwright-runtime/$runtime_arch/playwright-driver/." /ms-playwright-go/; \
cp -R "/prebuilt-playwright-runtime/$runtime_arch/playwright-browsers/." /ms-playwright/; \
else \
case "$TARGETARCH" in \
amd64) playwright_platform=debian13-x64 ;; \
arm64) playwright_platform=debian13-arm64 ;; \
esac; \
PLAYWRIGHT_HOST_PLATFORM_OVERRIDE="$playwright_platform" /usr/local/bin/browser-install \
-driver-dir /ms-playwright-go \
-browser-dir /ms-playwright; \
fi; \
test -f /ms-playwright-go/package/cli.js; \
chromium_revision="$(node -e 'const b=require("/ms-playwright-go/package/browsers.json").browsers; process.stdout.write(b.find(x=>x.name==="chromium").revision)')"; \
headless_revision="$(node -e 'const b=require("/ms-playwright-go/package/browsers.json").browsers; process.stdout.write(b.find(x=>x.name==="chromium-headless-shell").revision)')"; \
test -d "/ms-playwright/chromium-$chromium_revision"; \
test -d "/ms-playwright/chromium_headless_shell-$headless_revision"; \
find /ms-playwright -type f -perm -111 \( -name chrome -o -name chrome-headless-shell -o -name headless_shell \) -print -quit | grep -q .
FROM node:latest AS runtime
ENV TZ=Asia/Shanghai
ENV BROWSER_HEADLESS=true
ENV PLAYWRIGHT_DRIVER_PATH=/ms-playwright-go
ENV PLAYWRIGHT_NODEJS_PATH=/usr/bin/node
ENV PLAYWRIGHT_NODEJS_PATH=/usr/local/bin/node
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright
ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1
ENV PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium
WORKDIR /app
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
ca-certificates \
chromium \
curl \
fonts-liberation \
fonts-noto-cjk \
nodejs \
tzdata \
&& rm -rf /var/lib/apt/lists/*
COPY --from=backend /out/xianyu-server /app/xianyu-server
COPY --from=backend /out/xianyu-dbseed /app/xianyu-dbseed
COPY --from=backend /out/xianyu-dbverify /app/xianyu-dbverify
COPY --from=playwright-driver /ms-playwright-go /ms-playwright-go
COPY --from=playwright-runtime /ms-playwright-go /ms-playwright-go
COPY --from=playwright-runtime /ms-playwright /ms-playwright
RUN mkdir -p /app/data /app/browser_data
EXPOSE 8080
CMD ["/app/xianyu-server", "-addr", ":8080"]
EXPOSE 59188
CMD ["/app/xianyu-server", "-addr", ":59188"]
+2 -2
View File
@@ -1,7 +1,7 @@
FROM alpine:3.22 AS sqlite-tools
RUN apk add --no-cache sqlite
FROM node:22-trixie AS frontend-assets
FROM node:latest AS frontend-assets
WORKDIR /src/frontend
COPY frontend/package*.json ./
RUN npm ci
@@ -24,7 +24,7 @@ COPY . .
COPY --from=frontend-assets /src/internal/webui/static ./internal/webui/static
CMD ["golangci-lint", "run", "./..."]
FROM node:22-trixie AS frontend-test
FROM node:latest AS frontend-test
WORKDIR /src/frontend
COPY frontend/package*.json ./
RUN npm ci
+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 ./...
+109 -21
View File
@@ -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 镜像公开时可以匿名拉取。若镜像仍为私有,请先执行
@@ -174,7 +174,81 @@ npm --prefix frontend run build
前端资源会在构建时通过 Go 的 `//go:embed` 嵌入服务;如果服务已经在运行,构建完成后
需要重启 Go 服务,浏览器硬刷新本身不会替换运行中进程已加载的前端资源。
初始化管理员:
### 方式三:桌面端安装包
桌面端由两个进程组成:后台 `xianyu-server` 负责 HTTP API、账号运行时和 Chromium;
`xianyu-tray` 只负责 Windows 托盘或 macOS 菜单栏状态、打开管理页面、打开日志目录和服务控制。
Chromium 不打进 Go 二进制,但 Linux、Windows 和 macOS 独立安装包会内置对应架构的
Playwright driver 与 Chromium runtime,安装后无需用户再下载浏览器。
- Windows:安装器注册 `YdisksXianyuHelper` Windows Service,并将托盘控制器加入当前用户登录启动项。安装阶段会为交互式登录用户授予该服务的状态查询、启动和停止权限;安装完成后从托盘启动、停止、重启或退出服务不再触发 UAC,也不会获得修改或删除服务的权限。
- macOS:安装器注册当前登录用户的两个 LaunchAgent,分别运行后台服务和菜单栏控制器。
- Linux:下载对应架构的 tar 包后,以 root 执行 `./install.sh`;安装包已经包含对应架构的
Playwright driver 与 Chromium,脚本只通过 Playwright 安装系统依赖,不会再下载浏览器。
脚本创建专用系统用户并安装 systemd unit。安装完成后打开管理页面,首次设置管理员密码。
卸载时执行 `./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 工作流在 `main` 和 `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:59188`。
4. 如果数据库尚未初始化,页面会要求设置并确认管理员密码;完成后会自动登录,管理员用户名为 `admin`。
Linux 需要先安装并启动 systemd 服务:
```bash
sudo ./install.sh
```
然后访问 `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 初始化:
```bash
mkdir -p data
@@ -187,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
```
首次启动会准备 Playwright 运行环境和 Chromium;下载速度取决于当前网络。启动完成后
访问 `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
```
此模式仍可运行管理后台,但浏览器指纹读取和滑块风控处理不可用,不建议用于需要登录
@@ -231,12 +305,13 @@ DATABASE_URL > -db-url > -db
| --- | --- | --- |
| `DATABASE_URL` | 空 | 数据库连接 URL;生产环境推荐 PostgreSQL |
| `XIANYU_DATA_KEY` | 空 | 敏感字段加密主密钥;生产环境必须固定并备份 |
| `XIANYU_ADMIN_PASSWORD` | 空 | 非交互初始化或重置管理员时使用 |
| `XIANYU_ADMIN_PASSWORD` | 空 | Docker Compose 非交互初始化或重置管理员时使用;源码和桌面端可通过首次打开页面设置密码 |
| `XIANYU_UPLOAD_DIR` | `data/uploads` | 批量铺货上传文件与临时资源目录 |
| `LOG_LEVEL` | 系统设置或 `info` | `debug`、`info`、`warn`、`error` |
| `LOG_FORMAT` | 系统设置或 `text` | `text` 或 `json` |
| `BROWSER_HEADLESS` | 按账号设置;Docker 为 `true` | 强制启用或关闭无头 Chromium |
| `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` | 自动发现 | 指定系统 Chromium 可执行文件 |
| `PLAYWRIGHT_BROWSERS_PATH` | 自动发现;Docker 为 `/ms-playwright` | Playwright Chromium runtime 目录 |
| `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` | 自动发现 | 仅在需要强制使用外部 Chromium 时指定 |
| `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` | 源码 `false` / Docker `true` | 跳过下载 |
| `TZ` | 系统时区;Docker 为 `Asia/Shanghai` | 容器和日志时区 |
@@ -251,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-<提交号>` 标签。
@@ -266,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 指纹读取和滑块处理 |
@@ -333,11 +408,12 @@ ARM64 Linux 拉取 arm64,不需要手动设置 `platform`。
| Git 引用 | 镜像标签 |
| --- | --- |
| `main` 分支 | `main`、`latest`、`sha-<完整提交号>` |
| `codex/desktop-packaging` 分支 | `alpha`、`desktop-packaging`、`sha-<完整提交号>` |
| `v1.2.3` 标签 | `1.2.3`、`1.2`、`sha-<完整提交号>` |
当前 Docker 发布工作流只在 `main` 分支推送和发布镜像;`dev` 分支不会自动生成
GHCR 标签。开发分支如需验证镜像,请在本地使用源码构建 Compose 文件,或手动运行
对应的构建流程。
当前 Docker 发布工作流会在 `main` 分支发布 `main` 和 `latest` 正式镜像,并在
`codex/desktop-packaging` 分支发布 `desktop-packaging` 和 `alpha` 标签用于验收;其他开发分支
不会自动生成 GHCR 标签。
生产环境建议使用明确的版本标签或 SHA 标签,避免上游更新导致未经验证的自动升级。
@@ -390,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
```
@@ -454,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"]
```
## 开发指南
@@ -465,6 +541,8 @@ services:
.
├── cmd/
│ ├── server/ # 主服务与管理员初始化入口
│ ├── browser-install/ # Playwright Chromium 安装辅助程序
│ ├── tray/ # Windows 托盘/macOS 菜单栏控制器
│ ├── init-admin/ # 交互式管理员初始化工具
│ ├── dbverify/ # 多数据库迁移和 CRUD 验证
│ └── dbseed/ # Docker 功能测试数据种子
@@ -481,6 +559,7 @@ services:
│ └── xianyu/ # MTOP、WebSocket、登录和协议实现
├── frontend/ # React、TypeScript、Vite 前端
├── docs/ # 专题文档和行为规范
├── packaging/ # Linux systemd、Windows Inno Setup、macOS pkg
├── scripts/ # Docker 与回归测试脚本
└── Dockerfile.debian13 # 多阶段生产镜像
```
@@ -490,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
```
启动前端开发服务器:
@@ -500,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 二进制:
@@ -541,15 +620,20 @@ go run ./cmd/dbverify "postgres://user:pass@127.0.0.1:5432/xianyu"
## 常见问题
### 首次部署无法完成管理员初始化
### 首次打开页面如何初始化管理员
确认 `.env` 已设置非空的 `XIANYU_ADMIN_PASSWORD`,然后执行:
启动服务后访问管理页面。如果数据库中还没有管理员,页面会显示“首次设置管理员密码”,
填写两次不少于 8 个字符的密码并提交即可。初始化成功后会自动登录,默认管理员用户名为
`admin`。
Docker Compose 使用非交互初始化,因此必须在 `.env` 中设置非空的
`XIANYU_ADMIN_PASSWORD`,然后执行:
```bash
docker compose up -d
```
源码运行时可执行:
无浏览器、自动化部署或需要重置管理员密码时可执行:
```bash
go run ./cmd/server -init-admin -db data/xianyu_data.db -admin-password '新密码'
@@ -565,7 +649,11 @@ go run ./cmd/server -init-admin -db data/xianyu_data.db -admin-password '新密
### Chromium 或 Playwright 初始化失败
- Docker 部署优先使用项目提供的镜像,镜像已包含 Chromium 和运行依赖。
- Docker 部署优先使用项目提供的镜像,镜像在构建阶段已下载并校验匹配架构的 Chromium runtime;
Docker CI 优先复用 GitHub Actions 缓存,不依赖 Debian 仓库中的 `chromium` 包,也不会在最终镜像
构建阶段执行 `apt-get update`。
- 独立安装包在 CI 构建阶段下载对应架构的 Playwright driver 和 Chromium;Linux 安装时只
安装系统库,不需要再次下载浏览器。
- 源码运行时确认系统允许下载 Playwright 驱动和 Chromium。
- 自带 Chromium 时设置 `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH`,并按需设置
`PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1`。
+69
View File
@@ -0,0 +1,69 @@
// 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/mxschmitt/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")
depsOnly := flag.Bool("deps-only", false, "only install Linux system dependencies; do not download Chromium")
flag.Parse()
if *depsOnly && !*withDeps {
*withDeps = true
}
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 *depsOnly {
args = []string{"install-deps", "chromium"}
} else if *withDeps {
args = append(args, "--with-deps")
args = append(args, "chromium")
} else {
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)
}
+258 -80
View File
@@ -1,25 +1,20 @@
// 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"
"io"
"log/slog"
"os"
"os/signal"
"path/filepath"
"runtime"
"strings"
"syscall"
@@ -36,123 +31,226 @@ import (
"xianyu-go/internal/server"
)
type serverOptions struct {
dbPath string
dbURL string
addr string
webDir string
workDir string
playwrightRuntimeRoot 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
}
const (
defaultDBPath = "data/xianyu_data.db"
userDataDirName = "YdisksXianyuHelper"
defaultDataKeyName = "data-key"
)
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", defaultDBPath, "SQLite 数据库路径(兼容旧用法)")
flag.StringVar(&opts.dbURL, "db-url", "", "数据库连接 URL(sqlite:// mysql:// postgres://),优先级高于 -db;也可用 DATABASE_URL 环境变量")
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 根目录")
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()
dataDir, err := resolveDataDir(opts.workDir)
if err != nil {
return err
}
applyPlaywrightRuntimeRoot(&opts)
if dataDir != "" {
if err := os.MkdirAll(dataDir, 0o700); err != nil {
return fmt.Errorf("创建应用数据目录失败: %w", err)
}
if opts.dataKeyFile == "" {
opts.dataKeyFile = filepath.Join(dataDir, defaultDataKeyName)
}
if opts.playwrightDriverDir == "" {
opts.playwrightDriverDir = filepath.Join(dataDir, "playwright-driver")
}
if opts.playwrightBrowserDir == "" {
opts.playwrightBrowserDir = filepath.Join(dataDir, "playwright-browsers")
}
}
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 = resolveDBPath(dataDir, opts.dbPath)
}
if dataDir != "" && resolvedDBURL == resolveDBPath(dataDir, defaultDBPath) {
if err := os.MkdirAll(filepath.Dir(resolvedDBURL), 0o700); err != nil {
return fmt.Errorf("创建数据库目录失败: %w", err)
}
}
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)
logWriter, closeLog, err := openServerLogWriter(dataDir)
if err != nil {
return err
}
defer closeLog()
logger := logging.NewLogger(logWriter, 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)
}
}
}
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)
}
}
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 +266,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 +282,102 @@ func main() {
_ = bm.Close()
}
notifier.Wait()
return runErr
}
// handlerAdapter 已下沉到 internal/adapter 包;本文件只负责装配。
// 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
}
root := strings.TrimSpace(opts.playwrightRuntimeRoot)
if root == "" {
return
}
archRoot := filepath.Join(root, runtime.GOARCH)
if opts.playwrightDriverDir == "" {
opts.playwrightDriverDir = filepath.Join(archRoot, "playwright-driver")
}
if opts.playwrightBrowserDir == "" {
opts.playwrightBrowserDir = filepath.Join(archRoot, "playwright-browsers")
}
}
// resolveDataDir 返回桌面端的标准用户数据目录。
// Linux/Docker 保留原有相对路径行为;macOS 和 Windows 在没有显式 -workdir
// 时使用当前用户的系统配置目录,避免把具体用户路径写进安装包或代码。
func resolveDataDir(workDir string) (string, error) {
if strings.TrimSpace(workDir) != "" {
return filepath.Clean(workDir), nil
}
if runtime.GOOS != "darwin" && runtime.GOOS != "windows" {
return "", nil
}
configDir, err := os.UserConfigDir()
if err != nil {
return "", fmt.Errorf("读取用户配置目录失败: %w", err)
}
return filepath.Join(configDir, userDataDirName), nil
}
func resolveDBPath(dataDir, configuredPath string) string {
if dataDir != "" && configuredPath == defaultDBPath {
return filepath.Join(dataDir, "data", "xianyu_data.db")
}
return configuredPath
}
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 +389,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) {
+95
View File
@@ -2,7 +2,10 @@ package main
import (
"context"
"io"
"os"
"path/filepath"
"runtime"
"testing"
"xianyu-go/internal/db"
@@ -32,3 +35,95 @@ 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)
}
}
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)
if err != nil {
t.Fatalf("resolve explicit data directory: %v", err)
}
if got != explicit {
t.Fatalf("explicit data directory changed: got %q want %q", got, explicit)
}
}
func TestUserDataDirName(t *testing.T) {
base := filepath.Join(t.TempDir(), "Application Support")
got := filepath.Join(base, userDataDirName)
want := filepath.Join(base, "YdisksXianyuHelper")
if got != want {
t.Fatalf("unexpected user data directory: got %q want %q", got, want)
}
}
func TestResolveDBPathUsesDataDirectoryForDefault(t *testing.T) {
dataDir := filepath.Join(t.TempDir(), "YdisksXianyuHelper")
got := resolveDBPath(dataDir, defaultDBPath)
want := filepath.Join(dataDir, "data", "xianyu_data.db")
if got != want {
t.Fatalf("unexpected default database path: got %q want %q", got, want)
}
}
func TestResolveDBPathPreservesCustomPath(t *testing.T) {
dataDir := filepath.Join(t.TempDir(), "YdisksXianyuHelper")
custom := filepath.Join(t.TempDir(), "custom.db")
if got := resolveDBPath(dataDir, custom); got != custom {
t.Fatalf("custom database path changed: got %q want %q", got, custom)
}
}
func TestPlaywrightRuntimeRootUsesProcessArchitecture(t *testing.T) {
opts := serverOptions{playwrightRuntimeRoot: filepath.Join(t.TempDir(), "playwright-runtime")}
applyPlaywrightRuntimeRoot(&opts)
wantRoot := filepath.Join(opts.playwrightRuntimeRoot, runtime.GOARCH)
if opts.playwrightDriverDir != filepath.Join(wantRoot, "playwright-driver") {
t.Fatalf("driver 目录=%q", opts.playwrightDriverDir)
}
if opts.playwrightBrowserDir != filepath.Join(wantRoot, "playwright-browsers") {
t.Fatalf("browser 目录=%q", opts.playwrightBrowserDir)
}
}
+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
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 117 KiB

+54
View File
@@ -0,0 +1,54 @@
package main
import (
_ "embed"
"encoding/binary"
"runtime"
)
// icon.png 是从根目录 icon/windows/icon.png 同步的彩色产品图标,并直接嵌入托盘二进制。
//
//go:embed icon.png
var productIconPNG []byte
//go:embed icon-gray.png
var productIconGrayPNG []byte
// trayIconBytes 返回当前服务状态对应的图标,避免运行时依赖外部图标文件。
// Windows 的 Shell_NotifyIcon 需要 ICO;macOS/Linux 可以直接使用 PNG。
func trayIconBytes(running bool) []byte {
data := productIconGrayPNG
if running {
data = productIconPNG
}
if runtime.GOOS != "windows" {
return data
}
return pngToICO(data, 256)
}
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]
if size >= 256 {
entry[0] = 0
entry[1] = 0
} else {
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
}
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 171 KiB

+43
View File
@@ -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
}
+29
View File
@@ -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")
}
}
+27
View File
@@ -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
}
+365
View File
@@ -0,0 +1,365 @@
// 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"
"log"
"net/http"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"strings"
"sync"
"sync/atomic"
"syscall"
"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:59188"), "/")
var (
actionMu sync.Mutex
transitioning atomic.Bool
exitRequested atomic.Bool
)
func main() {
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() {
systray.SetTitle("")
systray.SetIcon(trayIconBytes(false))
systray.SetTooltip("Ydisks闲鱼助手服务")
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("退出托盘", "停止后台服务并退出菜单栏控制器")
// 安装脚本只负责注册平台服务。用户再次打开托盘时,托盘本身必须确保
// 后台服务已启动。首次启动动作完成后再进入轮询,避免“检查中”的旧请求
// 覆盖“启动中”等中间状态。
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", startItem, stopItem, restartItem, quitItem)
}
}()
go func() {
for range stopItem.ClickedCh {
runServiceAction(statusItem, "停止服务", "正在停止", "stop", startItem, stopItem, restartItem, quitItem)
}
}()
go func() {
for range restartItem.ClickedCh {
runServiceAction(statusItem, "重启服务", "正在重启", "restart", startItem, stopItem, restartItem, quitItem)
}
}()
go func() {
for range quitItem.ClickedCh {
exitTray(statusItem, startItem, stopItem, restartItem, quitItem)
}
}()
}
func refreshStatus(item *systray.MenuItem) {
client := &http.Client{Timeout: 2 * time.Second}
for {
// 与菜单动作使用同一把锁,避免一次已经开始的健康检查在“启动中”
// 或“正在停止”之后才返回,并把中间状态错误覆盖掉。
actionMu.Lock()
if !transitioning.Load() {
refreshStatusOnce(item, client)
}
actionMu.Unlock()
time.Sleep(5 * time.Second)
}
}
func refreshStatusOnce(item *systray.MenuItem, client *http.Client) {
status, err := readHealth(client)
if err != nil {
systray.SetIcon(trayIconBytes(false))
item.SetTitle("服务状态:未运行")
systray.SetTooltip("Ydisks闲鱼助手:后台服务未运行")
} else if status.Status == "ok" && status.Database == "ok" {
systray.SetIcon(trayIconBytes(true))
item.SetTitle("服务状态:运行正常")
systray.SetTooltip("Ydisks闲鱼助手:运行正常")
} else {
systray.SetIcon(trayIconBytes(false))
item.SetTitle("服务状态:异常")
systray.SetTooltip("Ydisks闲鱼助手:数据库或服务异常")
}
}
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("服务状态:" + 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)
}
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{}, false, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
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{}, true, err
}
return health, true, 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 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
}
return fallback
}
+66
View File
@@ -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)
}
}
+105
View File
@@ -0,0 +1,105 @@
//go:build darwin
package main
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
func serviceAction(action string) error {
label := envOr("XIANYU_SERVICE_NAME", "com.ydisks.xianyu-helper.server")
uid := fmt.Sprint(os.Getuid())
domain := "gui/" + uid
target := domain + "/" + label
home, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("获取用户目录失败: %w", err)
}
plistPath := filepath.Join(home, "Library", "LaunchAgents", label+".plist")
switch action {
case "start":
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
}
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
}
return launchctl("kickstart", target)
default:
return fmt.Errorf("未知服务操作: %s", action)
}
}
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)
}
}
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 {
cmd := exec.Command("launchctl", args...)
output, err := cmd.CombinedOutput()
if err != nil {
message := strings.TrimSpace(string(output))
if message == "" {
return fmt.Errorf("launchctl %s 失败: %w", strings.Join(args, " "), err)
}
return fmt.Errorf("launchctl %s 失败: %s", strings.Join(args, " "), message)
}
return nil
}
+18
View File
@@ -0,0 +1,18 @@
//go:build !windows && !darwin
package main
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
}
+183
View File
@@ -0,0 +1,183 @@
//go:build windows
package main
import (
"errors"
"fmt"
"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 {
if action != "start" && action != "stop" && action != "restart" {
return fmt.Errorf("未知服务操作: %s", action)
}
name := envOr("XIANYU_SERVICE_NAME", "YdisksXianyuHelper")
controller, err := openWindowsServiceController(name)
if err != nil {
if action == "stop" && errors.Is(err, windows.ERROR_SERVICE_DOES_NOT_EXIST) {
return nil
}
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 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
}
+83
View File
@@ -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)
}
}
+5 -5
View File
@@ -9,9 +9,9 @@ x-app-env: &app-env
LOG_FORMAT: ${LOG_FORMAT:-json}
BROWSER_HEADLESS: ${BROWSER_HEADLESS:-true}
PLAYWRIGHT_DRIVER_PATH: ${PLAYWRIGHT_DRIVER_PATH:-/ms-playwright-go}
PLAYWRIGHT_NODEJS_PATH: ${PLAYWRIGHT_NODEJS_PATH:-/usr/bin/node}
PLAYWRIGHT_NODEJS_PATH: ${PLAYWRIGHT_NODEJS_PATH:-/usr/local/bin/node}
PLAYWRIGHT_BROWSERS_PATH: ${PLAYWRIGHT_BROWSERS_PATH:-/ms-playwright}
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: ${PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD:-1}
PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH: ${PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH:-/usr/bin/chromium}
x-app-volumes: &app-volumes
- app_data:/app/data
@@ -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", "node", "-e", "require('http').get('http://127.0.0.1:59188/health',r=>process.exit(r.statusCode===200?0:1)).on('error',()=>process.exit(1))"]
interval: 30s
timeout: 5s
retries: 5
+5 -5
View File
@@ -7,9 +7,9 @@ x-app-env: &app-env
LOG_FORMAT: ${LOG_FORMAT:-json}
BROWSER_HEADLESS: ${BROWSER_HEADLESS:-true}
PLAYWRIGHT_DRIVER_PATH: ${PLAYWRIGHT_DRIVER_PATH:-/ms-playwright-go}
PLAYWRIGHT_NODEJS_PATH: ${PLAYWRIGHT_NODEJS_PATH:-/usr/bin/node}
PLAYWRIGHT_NODEJS_PATH: ${PLAYWRIGHT_NODEJS_PATH:-/usr/local/bin/node}
PLAYWRIGHT_BROWSERS_PATH: ${PLAYWRIGHT_BROWSERS_PATH:-/ms-playwright}
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: ${PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD:-1}
PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH: ${PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH:-/usr/bin/chromium}
x-app-volumes: &app-volumes
- app_data:/app/data
@@ -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", "node", "-e", "require('http').get('http://127.0.0.1:59188/health',r=>process.exit(r.statusCode===200?0:1)).on('error',()=>process.exit(1))"]
interval: 30s
timeout: 5s
retries: 5
+9 -9
View File
@@ -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", "node", "-e", "require('http').get('http://127.0.0.1:59188/health',r=>process.exit(r.statusCode===200?0:1)).on('error',()=>process.exit(1))"]
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", "node", "-e", "require('http').get('http://127.0.0.1:59188/health',r=>process.exit(r.statusCode===200?0:1)).on('error',()=>process.exit(1))"]
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", "node", "-e", "require('http').get('http://127.0.0.1:59188/health',r=>process.exit(r.statusCode===200?0:1)).on('error',()=>process.exit(1))"]
interval: 5s
timeout: 5s
retries: 30
+62 -21
View File
@@ -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 -->
@@ -1133,14 +1134,15 @@
<span class="command">cd</span> Ydisks-Xianyu-Helper
<span class="command">cp</span> .env.example .env
<span class="comment"># 2. 修改 .env 填入自己的强密码与主密钥</span>
<span class="comment"># 2. 修改 .env 填入数据库密码、管理员密码与主密钥</span>
<span class="comment"># POSTGRES_PASSWORD=...</span>
<span class="comment"># XIANYU_DATA_KEY=...</span>
<span class="comment"># XIANYU_ADMIN_PASSWORD=...</span>
<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 -->
@@ -1153,15 +1155,38 @@
<span class="command">npm</span> --prefix frontend ci
<span class="command">npm</span> --prefix frontend run build
<span class="comment"># 2. 初始化管理员账号 (使用默认 SQLite)</span>
<span class="comment"># 2. 启动服务端 (默认监听 :59188)</span>
<span class="command">mkdir</span> -p data
<span class="command">go run</span> ./cmd/server \
-init-admin \
-db data/xianyu_data.db \
-admin-password <span class="string">'设置管理员密码'</span>
-addr :59188
<span class="comment"># 3. 启动服务端 (默认监听 :8080)</span>
<span class="command">go run</span> ./cmd/server -db data/xianyu_data.db -addr :8080</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>
@@ -1183,7 +1208,7 @@
<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">
使用 Docker Compose 部署时,服务在启动时会自动读取 <code>.env</code> 文件中的 <code>XIANYU_ADMIN_PASSWORD</code> 创建管理员,默认用户名统一为 <code>admin</code>。使用源码构建时,可运行 <code>go run ./cmd/server -init-admin -db ... -admin-password '你的密码'</code> 初始化。
使用 Docker Compose 部署时,服务会读取 <code>.env</code> 文件中的 <code>XIANYU_ADMIN_PASSWORD</code>,在首次启动时自动创建管理员,默认用户名为 <code>admin</code>。源码运行或桌面端安装后,首次访问管理页面会显示密码设置表单,填写并确认密码即可完成初始化并自动登录。无浏览器或自动化部署场景仍可使用 <code>-init-admin</code> CLI。
</div>
</div>
@@ -1213,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>
@@ -1274,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 -10
View File
@@ -5,16 +5,28 @@
## 推荐上线路径
1. 选择并启动数据库;生产环境推荐 PostgreSQL。
2. 设置并备份 `XIANYU_DATA_KEY`,初始化管理员后登录后台。
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 仓库版本。
## 先读这些页面
+51 -5
View File
@@ -18,18 +18,56 @@
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`,用管理员账号登录。若未自动初始化,可按 README 的 `-init-admin` 命令执行。
6. 打开 `http://服务器地址:59188`。设置了 `XIANYU_ADMIN_PASSWORD` 时,Compose 会在首次启动
自动创建 `admin`;如果使用其他方式启动且数据库尚未初始化,页面会显示初始化表单,填写
两次不少于 8 个字符的密码即可。
默认连接已由 `compose.yml` 注入,不需要手写 PostgreSQL URL。若修改 `COMPOSE_PROJECT_NAME`,新卷名前缀也会变化;已有部署升级时保留原 `.env`,避免误用新空卷。
Docker 中的自动续期会使用容器内 Chromium 检测到的 Linux 原生浏览器指纹请求闲鱼官网;不会因为宿主系统是 Linux 而跳过静默续期。续期结果仍以闲鱼响应和账号登录态为准。
## 独立安装包
独立安装包与 Docker 使用同一套 Playwright Chromium 版本来源:Chromium、headless shell 和
Playwright driver 都在构建阶段下载并放入包内,不使用 Debian 仓库的 Chromium。Docker CI 会优先
复用架构专属的 GitHub Actions runtime 缓存,Dockerfile 最终使用 `node:latest` 运行时,不执行
`apt-get update` 或安装 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
```
也可显式指定:
@@ -46,7 +84,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 的环境请按数据库驱动/基础设施要求配置安全连接,不要把真实密码写进命令历史。
@@ -55,14 +93,22 @@ 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。数据库账号只应拥有该应用数据库的必要权限。
## 初始化、备份和升级
初始化管理员:
### Web 页面初始化(推荐)
启动服务后访问管理页面。系统尚未存在管理员时,会显示“首次设置管理员密码”页面。输入并
确认不少于 8 个字符的密码,提交后系统会创建 `admin` 账号并自动登录。此流程不需要用户
知道 SQLite 文件路径,也不需要打开终端执行初始化命令。
### CLI 初始化(运维备用)
无浏览器、自动化部署或需要重置管理员密码时,可以使用 CLI:
```bash
go run ./cmd/server -init-admin -db data/xianyu_data.db -admin-password '强密码'
+73 -18
View File
@@ -11,7 +11,7 @@ import Notifications from './components/Notifications';
import Chat from './components/Chat';
import { readSidebarCollapsed, writeSidebarCollapsed } from './components/sidebarState';
import { YdisksBrandIcon } from './components/YdisksLogo';
import { login, logout, verifySession } from './services/api';
import { initializeAdmin, login, logout, verifySession } from './services/api';
import { ShieldCheck, ArrowRight, Loader2, User, Lock } from 'lucide-react';
interface DeliveryRuleTarget {
@@ -39,9 +39,6 @@ const TAB_TO_PATH: Record<string, string> = Object.fromEntries(
);
const tabFromPath = (): string => ROUTES[window.location.pathname] || 'dashboard';
// 检测 Windows 以显示对应的 CLI 命令(路径分隔符、引号、.exe 后缀)。
const isWindows = /Win/i.test(navigator.platform || navigator.userAgent);
const App: React.FC = () => {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [isAdmin, setIsAdmin] = useState(false);
@@ -52,6 +49,10 @@ const App: React.FC = () => {
const [password, setPassword] = useState('');
const [loginLoading, setLoginLoading] = useState(false);
const [loginError, setLoginError] = useState('');
const [initialPassword, setInitialPassword] = useState('');
const [initialPasswordConfirm, setInitialPasswordConfirm] = useState('');
const [initializing, setInitializing] = useState(false);
const [initializationError, setInitializationError] = useState('');
const [deliveryRuleTarget, setDeliveryRuleTarget] = useState<DeliveryRuleTarget | undefined>();
const [sidebarCollapsed, setSidebarCollapsed] = useState(readSidebarCollapsed);
@@ -133,6 +134,38 @@ const App: React.FC = () => {
}
};
const handleInitialize = async (e: React.FormEvent) => {
e.preventDefault();
setInitializationError('');
if (initialPassword.length < 8) {
setInitializationError('密码至少需要 8 个字符');
return;
}
if (initialPassword !== initialPasswordConfirm) {
setInitializationError('两次输入的密码不一致');
return;
}
setInitializing(true);
try {
const res = await initializeAdmin(initialPassword);
if (!res.success) {
setInitializationError(res.message || '初始化失败,请重试');
return;
}
setNeedsInit(false);
setIsLoggedIn(true);
setIsAdmin(res.is_admin === true);
setInitialPassword('');
setInitialPasswordConfirm('');
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
setInitializationError(msg || '初始化失败,请重试');
} finally {
setInitializing(false);
}
};
const handleLogout = async () => {
try {
await logout();
@@ -165,27 +198,49 @@ const App: React.FC = () => {
<div className="mx-auto mb-6 flex justify-center">
<YdisksBrandIcon sizeClass="w-24 h-24" />
</div>
<h2 className="text-3xl font-extrabold text-gray-900 mb-2 tracking-tight">系统尚未初始化</h2>
<p className="text-gray-600 font-medium">为避免默认口令风险,管理员必须通过服务器本机 CLI 初始化。</p>
<h2 className="text-3xl font-extrabold text-gray-900 mb-2 tracking-tight">首次设置管理员密码</h2>
<p className="text-gray-600 font-medium">设置完成后会自动进入系统,管理员账号为 admin。</p>
</div>
<div className="space-y-4">
<div className="p-4 rounded-2xl bg-gray-50 border border-gray-100">
<div className="text-sm font-bold text-gray-900 mb-2">请在服务器上执行:</div>
<pre className="text-xs bg-black text-white p-4 rounded-2xl overflow-x-auto">{isWindows
? '.\\xianyu-server.exe -init-admin -db data\\xianyu_data.db -admin-password "请设置密码"'
: './xianyu-server -init-admin -db data/xianyu_data.db -admin-password \'请设置密码\''}</pre>
<div className="text-xs text-gray-500 mt-2">完成后刷新页面即可进入登录。</div>
<form onSubmit={handleInitialize} className="space-y-5">
<div className="space-y-4">
<div className="relative group">
<Lock className="absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors" />
<input
type="password"
placeholder="设置管理员密码(至少 8 个字符)"
value={initialPassword}
onChange={e => setInitialPassword(e.target.value)}
autoFocus
className="w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"
/>
</div>
<div className="relative group">
<ShieldCheck className="absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors" />
<input
type="password"
placeholder="再次输入密码"
value={initialPasswordConfirm}
onChange={e => setInitialPasswordConfirm(e.target.value)}
className="w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"
/>
</div>
</div>
{initializationError && (
<div className="p-3 rounded-xl bg-red-50 text-red-500 text-sm text-center font-bold flex items-center justify-center gap-2">
<ShieldCheck className="w-4 h-4" /> {initializationError}
</div>
)}
<button
type="button"
onClick={() => window.location.reload()}
className="w-full ios-btn-primary h-14 rounded-2xl text-lg shadow-xl shadow-blue-200 mt-2 flex items-center justify-center gap-2 group"
type="submit"
disabled={initializing}
className="w-full ios-btn-primary h-14 rounded-2xl text-lg shadow-xl shadow-blue-200 mt-2 flex items-center justify-center gap-2 group disabled:opacity-70"
>
我已初始化,刷新 <ArrowRight className="w-5 h-5 group-hover:translate-x-1 transition-transform" />
{initializing ? <Loader2 className="w-5 h-5 animate-spin" /> : <>设置密码并进入系统 <ArrowRight className="w-5 h-5 group-hover:translate-x-1 transition-transform" /></>}
</button>
</div>
</form>
<div className="mt-8 pt-6 border-t border-gray-100 text-center">
<span className="text-xs text-gray-400 font-medium tracking-widest uppercase">Secure Bootstrap</span>
+10 -5
View File
@@ -8,12 +8,12 @@ React + Vite + TypeScript 单页应用,作为 Ydisks闲鱼助手 Go 后端的
frontend/
index.html 入口 HTML
index.tsx 应用入口(挂载 React、登录态判断、tab 路由)
App.tsx 主壳:侧边栏 + 内容区 + 登录/初始化
App.tsx 主壳:侧边栏 + 内容区 + 登录/首次初始化
components/ 业务组件(Dashboard / OrderList / CardList / Rules / Settings ...)
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 开发服务器地址,不是应用服务端口。
## 构建产物
@@ -48,7 +50,10 @@ Dashboard 的营收趋势柱状图使用统一的品牌蓝 `#0094f7` 表示同
应用使用 `window.history.pushState` 做 tab 导航,路径包括 `/app/dashboard`、`/app/accounts`、
`/app/chat`、`/app/cards`、`/app/items`、`/app/orders`、`/app/rules`、
`/app/notifications` 和管理员可见的 `/app/settings`。
未登录时显示登录表单(客户端状态,非独立路由)。后端 SPA catch-all 对非 API 的 GET 请求返回 `index.html`,支持深链刷新。
未登录时显示登录表单(客户端状态,非独立路由)。当后端 `/verify` 返回
`initialized: false` 时,显示首次初始化表单;用户确认不少于 8 个字符的管理员密码后,
前端调用 `/initialize` 创建 `admin` 并使用返回的会话自动进入系统。后端 SPA catch-all
对非 API 的 GET 请求返回 `index.html`,支持深链刷新。
## 测试
+4
View File
@@ -22,6 +22,10 @@ export const login = async (data: { username?: string; password?: string; email?
return post('/login', data, { skipAuthLogout: true });
};
export const initializeAdmin = async (password: string): Promise<LoginResponse> => {
return post('/initialize', { password }, { skipAuthLogout: true });
};
export const verifySession = async (): Promise<{ authenticated: boolean; initialized?: boolean; user_id?: number; username?: string; is_admin?: boolean }> => {
return get('/verify');
};
+27 -27
View File
@@ -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,
},
},
+6 -4
View File
@@ -3,15 +3,18 @@ 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
github.com/jackc/pgx/v5 v5.10.0
github.com/playwright-community/playwright-go v0.5700.1
github.com/mxschmitt/playwright-go v0.6100.0
github.com/pressly/goose/v3 v3.27.1
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
)
@@ -20,8 +23,9 @@ require (
filippo.io/edwards25519 v1.2.0 // indirect
github.com/deckarep/golang-set/v2 v2.8.0 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/go-jose/go-jose/v3 v3.0.4 // indirect
github.com/go-jose/go-jose/v3 v3.0.5 // 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
+8 -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=
@@ -11,12 +13,14 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/go-chi/chi/v5 v5.3.0 h1:halUjDxhshgXHMrao5bB8eNBXo/rnzwr8m5m36glehM=
github.com/go-chi/chi/v5 v5.3.0/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
github.com/go-jose/go-jose/v3 v3.0.4 h1:Wp5HA7bLQcKnf6YYao/4kpRpVMp/yf6+pJKV8WFSaNY=
github.com/go-jose/go-jose/v3 v3.0.4/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ=
github.com/go-jose/go-jose/v3 v3.0.5 h1:BLLJWbC4nMZOfuPVxoZIxeYsn6Nl2r1fITaJ78UQlVQ=
github.com/go-jose/go-jose/v3 v3.0.5/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ=
github.com/go-sql-driver/mysql v1.10.0 h1:Q+1LV8DkHJvSYAdR83XzuhDaTykuDx0l6fkXxoWCWfw=
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=
@@ -36,10 +40,10 @@ github.com/mattn/go-isatty v0.0.21 h1:xYae+lCNBP7QuW4PUnNG61ffM4hVIfm+zUzDuSzYLG
github.com/mattn/go-isatty v0.0.21/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg=
github.com/mxschmitt/playwright-go v0.6100.0 h1:HYNnbGZsTHz8veJyDGe4fU1iPxfvXqzmwKchzuvGCsY=
github.com/mxschmitt/playwright-go v0.6100.0/go.mod h1:A7VtrS3j/c8ToGnSVUaOfNtQQVxi6JotUS0jeuus6r4=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/playwright-community/playwright-go v0.5700.1 h1:PNFb1byWqrTT720rEO0JL88C6Ju0EmUnR5deFLvtP/U=
github.com/playwright-community/playwright-go v0.5700.1/go.mod h1:MlSn1dZrx8rszbCxY6x3qK89ZesJUYVx21B2JnkoNF0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pressly/goose/v3 v3.27.1 h1:6uEvcprBybDmW4hcz3gYujhARhye+GoWKhEWyzD5sh4=
Binary file not shown.

After

Width:  |  Height:  |  Size: 171 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 171 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 171 KiB

+1 -1
View File
@@ -1,5 +1,5 @@
// Package auth 实现 HttpOnly Cookie 会话认证,沿用 Fork 版安全基线:
// - 无默认口令(管理员必须经 init-admin CLI 初始化)
// - 无默认口令(管理员可经首次启动 Web UI 或 init-admin CLI 初始化)
// - 会话存 DB(sessions 表),HttpOnly + SameSite=Lax Cookie 传递
// - bcrypt 哈希,兼容老库无盐 SHA-26(首次登录静默升级)
//
+1 -1
View File
@@ -10,7 +10,7 @@ import (
"sync/atomic"
"time"
"github.com/playwright-community/playwright-go"
"github.com/mxschmitt/playwright-go"
"xianyu-go/internal/xianyu/cookierefresh"
)
+1 -1
View File
@@ -6,7 +6,7 @@ import (
"sync"
"time"
"github.com/playwright-community/playwright-go"
"github.com/mxschmitt/playwright-go"
"xianyu-go/internal/xianyu/cookierefresh"
)
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"fmt"
"time"
"github.com/playwright-community/playwright-go"
"github.com/mxschmitt/playwright-go"
"xianyu-go/internal/xianyu/cookierefresh"
)
+49 -2
View File
@@ -1,5 +1,5 @@
// Package browser 用 playwright-go 在进程内驱动 Chromium。
// 首次使用时自动下载 Chromium(playwright.Install),无需手动启动外部服务。
// 安装包提供预置 runtime;开发环境没有预置 runtime 时才自动下载。
package browser
import (
@@ -10,11 +10,13 @@ import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
"github.com/playwright-community/playwright-go"
"github.com/mxschmitt/playwright-go"
"golang.org/x/sync/singleflight"
"xianyu-go/internal/xianyu"
@@ -58,6 +60,48 @@ func skipPlaywrightBrowserDownload() bool {
}
}
func packagedPlaywrightRuntimeReady() bool {
driverDir := strings.TrimSpace(os.Getenv("PLAYWRIGHT_DRIVER_PATH"))
if driverDir == "" {
return false
}
nodeReady := false
if nodePath := strings.TrimSpace(os.Getenv("PLAYWRIGHT_NODEJS_PATH")); nodePath != "" {
_, err := os.Stat(nodePath)
nodeReady = err == nil
} else {
nodeName := "node"
if runtime.GOOS == "windows" {
nodeName = "node.exe"
}
_, err := os.Stat(filepath.Join(driverDir, nodeName))
nodeReady = err == nil
}
if !nodeReady {
return false
}
if _, err := os.Stat(filepath.Join(driverDir, "package", "cli.js")); err != nil {
return false
}
if strings.TrimSpace(os.Getenv("PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH")) != "" {
return true
}
browserDir := strings.TrimSpace(os.Getenv("PLAYWRIGHT_BROWSERS_PATH"))
if browserDir == "" {
return false
}
matches, err := filepath.Glob(filepath.Join(browserDir, "chromium-*"))
if err != nil {
return false
}
for _, match := range matches {
if info, statErr := os.Stat(match); statErr == nil && info.IsDir() {
return true
}
}
return false
}
// Manager 管理浏览器生命周期与按账号复用的上下文池。
type Manager struct {
pw *playwright.Playwright
@@ -108,6 +152,9 @@ func NewManager(logger *slog.Logger) *Manager {
renewLocks: make(map[string]*sync.Mutex),
renewSlots: make(chan struct{}, 3),
installFn: func() error {
if packagedPlaywrightRuntimeReady() {
return nil
}
opts := &playwright.RunOptions{
Browsers: []string{"chromium"},
Verbose: false,
+60 -1
View File
@@ -1,10 +1,13 @@
package browser
import (
"os"
"path/filepath"
"runtime"
"testing"
"time"
playwright "github.com/playwright-community/playwright-go"
playwright "github.com/mxschmitt/playwright-go"
)
// TestChromiumLaunchArgs 验证启动参数含关键安全/反检测项。
@@ -28,6 +31,62 @@ func TestChromiumLaunchArgs(t *testing.T) {
}
}
func TestPackagedPlaywrightRuntimeReady(t *testing.T) {
runtimeRoot := t.TempDir()
driverDir := filepath.Join(runtimeRoot, "driver")
browserDir := filepath.Join(runtimeRoot, "browsers")
if err := os.MkdirAll(filepath.Join(driverDir, "package"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Join(browserDir, "chromium-1228"), 0o755); err != nil {
t.Fatal(err)
}
nodeName := "node"
if runtime.GOOS == "windows" {
nodeName = "node.exe"
}
for _, path := range []string{
filepath.Join(driverDir, nodeName),
filepath.Join(driverDir, "package", "cli.js"),
} {
if err := os.WriteFile(path, []byte("runtime"), 0o755); err != nil {
t.Fatal(err)
}
}
t.Setenv("PLAYWRIGHT_DRIVER_PATH", driverDir)
t.Setenv("PLAYWRIGHT_BROWSERS_PATH", browserDir)
t.Setenv("PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH", "")
if !packagedPlaywrightRuntimeReady() {
t.Fatal("预置 Playwright runtime 应被识别")
}
}
func TestPackagedPlaywrightRuntimeReadyWithExternalNode(t *testing.T) {
runtimeRoot := t.TempDir()
driverDir := filepath.Join(runtimeRoot, "driver")
browserDir := filepath.Join(runtimeRoot, "browsers")
if err := os.MkdirAll(filepath.Join(driverDir, "package"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Join(browserDir, "chromium-1228"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(driverDir, "package", "cli.js"), []byte("runtime"), 0o644); err != nil {
t.Fatal(err)
}
nodePath := filepath.Join(runtimeRoot, "node")
if err := os.WriteFile(nodePath, []byte("runtime"), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("PLAYWRIGHT_DRIVER_PATH", driverDir)
t.Setenv("PLAYWRIGHT_NODEJS_PATH", nodePath)
t.Setenv("PLAYWRIGHT_BROWSERS_PATH", browserDir)
t.Setenv("PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH", "")
if !packagedPlaywrightRuntimeReady() {
t.Fatal("配置外部 Node.js 的预置 Playwright runtime 应被识别")
}
}
// newTestManager 构造一个不触网的 Manager(pool 空,maxSize 小便于测试驱逐)。
func newTestManager(maxSize int) *Manager {
return &Manager{
+1 -1
View File
@@ -9,7 +9,7 @@ import (
"sync"
"time"
"github.com/playwright-community/playwright-go"
"github.com/mxschmitt/playwright-go"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"strings"
"time"
"github.com/playwright-community/playwright-go"
"github.com/mxschmitt/playwright-go"
)
// loginFormSelectors 登录表单选择器,主页面和 iframe 中都要找。
+1 -1
View File
@@ -7,7 +7,7 @@ import (
"strings"
"time"
"github.com/playwright-community/playwright-go"
"github.com/mxschmitt/playwright-go"
"xianyu-go/internal/logsafe"
)
+1 -1
View File
@@ -7,7 +7,7 @@ import (
"strings"
"time"
"github.com/playwright-community/playwright-go"
"github.com/mxschmitt/playwright-go"
)
// sliderSelectors 按优先级排列的滑块相关选择器(移植自 xianyu_slider_stealth.py)。
+1 -1
View File
@@ -10,7 +10,7 @@ import (
"strings"
"time"
"github.com/playwright-community/playwright-go"
"github.com/mxschmitt/playwright-go"
)
const (
+1 -1
View File
@@ -12,7 +12,7 @@ import (
"strings"
"time"
"github.com/playwright-community/playwright-go"
"github.com/mxschmitt/playwright-go"
)
var fallbackTrackSelectors = []string{
@@ -11,7 +11,7 @@ import (
"testing"
"time"
"github.com/playwright-community/playwright-go"
"github.com/mxschmitt/playwright-go"
)
func TestReferencePlaywrightSliderBrowserIntegration(t *testing.T) {
+1 -1
View File
@@ -7,7 +7,7 @@ import (
"testing"
"time"
"github.com/playwright-community/playwright-go"
"github.com/mxschmitt/playwright-go"
)
type cookieReadResult struct {
+47
View File
@@ -30,6 +30,53 @@ type loginResponse struct {
IsAdmin bool `json:"is_admin"`
}
// initialize 首次启动时通过 Web UI 创建管理员账号。
// 该接口只允许在系统尚未存在管理员时调用,避免把初始化能力变成重置密码入口。
func (s *Server) initialize(w http.ResponseWriter, r *http.Request) {
var req struct {
Password string `json:"password"`
}
if err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
if utf8.RuneCountInString(req.Password) < 8 {
writeErr(w, http.StatusBadRequest, "密码至少需要 8 个字符")
return
}
// 同一进程内串行化初始化,避免两个首次打开的页面同时重置管理员密码。
s.initializationMu.Lock()
defer s.initializationMu.Unlock()
initialized, err := s.Store.Users.IsSystemInitialized(r.Context())
if err != nil {
writeErr(w, http.StatusInternalServerError, "检查系统初始化状态失败")
return
}
if initialized {
writeErr(w, http.StatusConflict, "系统已经初始化,请直接登录")
return
}
if _, err := auth.InitAdmin(r.Context(), s.Store, "admin@example.com", req.Password); err != nil {
writeErr(w, http.StatusInternalServerError, "初始化管理员失败")
return
}
// 初始化完成后立即建立会话,用户无需再手动输入一次 admin 账号和密码。
sid, user, err := s.Auth.Login(r.Context(), "admin", req.Password)
if err != nil || user == nil || sid == "" {
writeErr(w, http.StatusInternalServerError, "初始化完成,但自动登录失败,请使用 admin 账号登录")
return
}
s.Auth.SetSessionCookie(w, sid)
writeJSON(w, http.StatusOK, loginResponse{
Success: true, Message: "初始化成功", UserID: user.ID,
Username: user.Username, IsAdmin: user.IsAdmin,
})
}
// login 用户名密码登录(邮箱登录同走此接口,按字段判断)。
func (s *Server) login(w http.ResponseWriter, r *http.Request) {
var req loginRequest
+5 -3
View File
@@ -83,8 +83,9 @@ type Server struct {
qrOwners map[string]qrLoginOwner
// qrPersistLocks 按扫码会话串行化持久化,避免持有全局 qrMu 执行数据库、
// 资料刷新和账号重启等慢操作。
qrPersistLocks sync.Map
loginLimiter *loginFailureLimiter
qrPersistLocks sync.Map
loginLimiter *loginFailureLimiter
initializationMu sync.Mutex
}
// SetChatService installs the shared chat persistence and live event hub.
@@ -142,6 +143,7 @@ func (s *Server) Router() http.Handler {
r.Group(func(r chi.Router) {
r.Use(s.Auth.Middleware) // 解析 session,不强制登录
r.Post("/login", s.login)
r.Post("/initialize", s.initialize)
r.Get("/verify", s.verify)
r.Post("/logout", s.logout)
})
@@ -320,7 +322,7 @@ func setNoStore(w http.ResponseWriter) {
// 仅保留实际挂载的路由前缀,与 Router() 中的 mount* 一一对应。
func isAPIPath(path string) bool {
apiPrefixes := []string{
"/api/", "/admin/", "/health", "/login", "/logout", "/verify",
"/api/", "/admin/", "/health", "/login", "/initialize", "/logout", "/verify",
"/change-password", "/change-admin-password", "/account/",
"/cookies", "/cookie/", "/orders", "/analytics",
"/cards", "/automation-rules", "/items", "/keywords", "/default-replies", "/default-reply",
+74
View File
@@ -51,6 +51,22 @@ func newTestServer(t *testing.T) (*Server, *db.Store, func()) {
}
}
func newUninitializedTestServer(t *testing.T) (*Server, *db.Store, func()) {
t.Helper()
dbPath := filepath.Join(t.TempDir(), "test.db")
d, _, err := db.Open(context.Background(), dbPath)
if err != nil {
t.Fatalf("Open: %v", err)
}
store := db.NewStore(d, db.DialectSQLite)
mgr := account.NewManager(store, noopHandler{}, nil)
srv := New(store, mgr, false, "", ":0", nil, nil, nil)
return srv, store, func() {
mgr.StopAll()
_ = d.Close()
}
}
type roundTripFunc func(*http.Request) (*http.Response, error)
func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
@@ -143,6 +159,64 @@ func TestLoginWrongPassword(t *testing.T) {
}
}
func TestInitializeFromWebUI(t *testing.T) {
srv, store, cleanup := newUninitializedTestServer(t)
defer cleanup()
h := srv.Router()
shortReq := httptest.NewRequest(http.MethodPost, "/initialize", strings.NewReader(`{"password":"short"}`))
shortRec := httptest.NewRecorder()
h.ServeHTTP(shortRec, shortReq)
if shortRec.Code != http.StatusBadRequest {
t.Fatalf("短密码应返回 400,got %d body=%s", shortRec.Code, shortRec.Body.String())
}
initReq := httptest.NewRequest(http.MethodPost, "/initialize", strings.NewReader(`{"password":"newpassword"}`))
initRec := httptest.NewRecorder()
h.ServeHTTP(initRec, initReq)
if initRec.Code != http.StatusOK {
t.Fatalf("初始化 status=%d body=%s", initRec.Code, initRec.Body.String())
}
var initResult loginResponse
if err := json.Unmarshal(initRec.Body.Bytes(), &initResult); err != nil {
t.Fatalf("解析初始化响应: %v", err)
}
if !initResult.Success || !initResult.IsAdmin || initResult.Username != "admin" {
t.Fatalf("初始化响应异常: %+v", initResult)
}
admin, err := store.Users.GetAdmin(context.Background())
if err != nil || admin == nil {
t.Fatalf("初始化后 admin 不存在: admin=%+v err=%v", admin, err)
}
if _, ok, err := store.Users.VerifyAndUpgrade(context.Background(), "admin", "newpassword"); err != nil || !ok {
t.Fatalf("初始化密码不可用: ok=%v err=%v", ok, err)
}
cookies := initRec.Result().Cookies()
if len(cookies) == 0 || cookies[0].Name != "session" || cookies[0].Value == "" {
t.Fatalf("初始化后应自动建立会话: %+v", cookies)
}
verifyReq := httptest.NewRequest(http.MethodGet, "/verify", nil)
verifyReq.AddCookie(cookies[0])
verifyRec := httptest.NewRecorder()
h.ServeHTTP(verifyRec, verifyReq)
var verifyResult map[string]any
if err := json.Unmarshal(verifyRec.Body.Bytes(), &verifyResult); err != nil {
t.Fatalf("解析 verify 响应: %v", err)
}
if verifyResult["authenticated"] != true || verifyResult["initialized"] != true {
t.Fatalf("初始化后 verify 异常: %+v", verifyResult)
}
secondReq := httptest.NewRequest(http.MethodPost, "/initialize", strings.NewReader(`{"password":"anotherpw"}`))
secondRec := httptest.NewRecorder()
h.ServeHTTP(secondRec, secondReq)
if secondRec.Code != http.StatusConflict {
t.Fatalf("重复初始化应返回 409,got %d body=%s", secondRec.Code, secondRec.Body.String())
}
}
func TestUpdateCredentialsRenamesUserAndRevokesSessions(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
@@ -0,0 +1,19 @@
import{j as e,r,b as qe,c as ia,d as Ea}from"./react-vendor-C_od1ZSF.js";import{L as Ta,U as oa,M as as,C as ls,B as ca,S as da,Z as rs,a as yt,b as hs,c as gs,d as bs,e as Ma,f as nt,A as Cs,D as qa,g as Ss,P as xa,h as $t,E as ma,T as Fa,i as Ba,j as Re,X as De,k as za,l as Ua,m as fs,n as pa,o as Ye,Q as Kt,p as mt,q as Ze,r as ft,s as At,t as Ls,R as Ue,u as ua,v as Wa,w as Ke,K as Va,x as xt,y as rt,z as at,F as Os,G as Nt,H as jt,I as It,J as ha,N as Ja,O as Is,V as As,W as Qa,Y as Ga,_ as Ka,$ as Ha,a0 as Ht,a1 as Tt,a2 as ns,a3 as Za,a4 as Ya,a5 as is,a6 as Xa,a7 as el,a8 as Rt,a9 as Rs,aa as Wt,ab as ga,ac as tl,ad as sl,ae as Jt,af as ba,ag as al,ah as ll,ai as rl,aj as nl,ak as il,al as ol,am as $s}from"./icons-vendor-DjsKcZkz.js";import{R as Mt,B as cl,X as Ps,Y as Ds,T as qt,a as dl,C as Zt,A as xl,b as ml,c as pl,P as Es,d as Ts,L as ul}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const p of document.querySelectorAll('link[rel="modulepreload"]'))i(p);new MutationObserver(p=>{for(const v of p)if(v.type==="childList")for(const k of v.addedNodes)k.tagName==="LINK"&&k.rel==="modulepreload"&&i(k)}).observe(document,{childList:!0,subtree:!0});function l(p){const v={};return p.integrity&&(v.integrity=p.integrity),p.referrerPolicy&&(v.referrerPolicy=p.referrerPolicy),p.crossOrigin==="use-credentials"?v.credentials="include":p.crossOrigin==="anonymous"?v.credentials="omit":v.credentials="same-origin",v}function i(p){if(p.ep)return;p.ep=!0;const v=l(p);fetch(p.href,v)}})();const hl=({className:t="w-full h-full text-white"})=>e.jsx("svg",{className:t,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),os=({sizeClass:t="w-12 h-12",logoClassName:s="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${t} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23.51 12.25 L 27.29 Line truncated
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(hs,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:Et,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:I,children:"取消"}),e.jsxs("button",{onClick:Ge,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:I,children:[I?e.jsx(Re,{className:"w-4 h-4 animate-spin"}):e.jsx(Ye,{className:"w-4 h-4"}),I?"保存中...":"保存"]})]})})]})}),document.body)]})},Zr=t=>({total:Number((t==null?void 0:t.total)||0),success_count:Number((t==null?void 0:t.success_count)||0),failed_count:Number((t==null?void 0:t.failed_count)||0),results:Array.isArray(t==null?void 0:t.results)?t.results.map(s=>({order_id:String((s==null?void 0:s.order_id)||"unknown"),success:(s==null?void 0:s.success)===!0,message:String((s==null?void 0:s.message)||"")})):[]}),Yr=t=>(t==null?void 0:t.results.filter(s=>!s.success))||[],Ks=({status:t})=>{const s={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-brand text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${s[t]||s.cancelled}`,children:l[t]||t})},Xr=()=>{const[t,s]=r.useState([]),[l,i]=r.useState([]),[p,v]=r.useState([]),[k,D]=r.useState({}),[g,R]=r.useState("all"),[y,J]=r.useState(""),[Z,pe]=r.useState(""),[de,N]=r.useState(""),q=r.useRef(0),[xe,Q]=r.useState(1),[Y,U]=r.useState(1),[be,ge]=r.useState(!1),[L,G]=r.useState(!1),[ae,H]=r.useState(!1),[me,$]=r.useState(!1),[T,X]=r.useState(null),[M,se]=r.useState(null),[we,je]=r.useState({}),[F,d]=r.useState(!1),[h,W]=r.useState(""),[w,ee]=r.useState(!1),[ie,_e]=r.useState(null),[$e,fe]=r.useState(null),[c,_]=r.useState(null),[re,x]=r.useState(!1),[u,I]=r.useState(null),[A,K]=r.useState(null),P=async()=>{const m=++q.current;ge(!0);try{const E=await Jl(y||void 0,g,xe,20,de);if(m!==q.current)return;s(E.data),U(E.total_pages)}catch(E){console.error("加载订单失败:",E)}finally{m===q.current&&ge(!1)}},ke=(m,E,oe)=>{if(oe&&oe.trim())return oe;if(k[`${m}:${E}`])return k[`${m}:${E}`];const ne=l.find(We=>{if(oe&&We.item_title){const et=oe.toLowerCase(),tt=We.item_title.toLowerCase();return tt.includes(et)||et.includes(tt)}return!1});return ne!=null&&ne.item_title?ne.item_title:"未知商品"},Oe=m=>{const E={};m.forEach(oe=>{oe.item_id&&(E[`${oe.cookie_id}:${oe.item_id}`]=oe.item_title||oe.item_id)}),D(E)};r.useEffect(()=>{const m=window.setTimeout(()=>{Q(1),N(Z.trim())},300);return()=>window.clearTimeout(m)},[Z]),r.useEffect(()=>{P()},[y,g,xe,de]),r.useEffect(()=>{Promise.all([Pt(),_t()]).then(([m,E])=>{v(m),i(E),Oe(E)}).catch(m=>{console.error("加载商品列表失败:",m)})},[]);const Pe=r.useMemo(()=>new Map(p.map(m=>[m.id,m])),[p]),Ee=m=>{const E=Pe.get(m),oe=(E==null?void 0:E.remark)||(E==null?void 0:E.nickname);return oe?`${oe} · ${m.slice(0,6)}`:`账号 ${m.slice(0,8)}`},Te=m=>{const E=Pe.get(m);return(E==null?void 0:E.remark)||(E==null?void 0:E.nickname)||"未命名账号"},f=async()=>{ge(!0);try{const m=await Kl(y||void 0,g);await P(),m!=null&&m.message&&alert(m.message)}catch(m){console.error("同步订单失败:",m),alert((m==null?void 0:m.message)||"同步失败,请重试")}finally{ge(!1)}},C=m=>{W(m),_e(null),d(!0)},B=async m=>{var E;ee(!0),_e(null);try{const oe=await Zl([h],m),ne=(E=oe==null?void 0:oe.results)==null?void 0:E[0];ne!=null&&ne.success?(_e({success:!0,message:ne.message}),P()):_e({success:!1,message:(ne==null?void 0:ne.message)||"发货失败"})}catch(oe){_e({success:!1,message:(oe==null?void 0:oe.message)||"请求失败"})}finally{ee(!1)}},V=m=>{X(m),G(!0)},Ce=m=>{se({...m}),H(!0)},Me=async()=>{if(!(!M||!M.order_id))try{const m={};M.status!==void 0&&(m.order_status=M.status),M.buyer_id!==void 0&&(m.buyer_id=M.buyer_id),M.amount!==void 0&&(m.amount=M.amount),M.receiver_name!==void 0&&(m.receiver_name=M.receiver_name),M.receiver_phone!= Line truncated
VIP-MONTH-002
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(A=>A.map(K=>`"${String(K).replace(/"/g,'""')}"`).join(",")).join(`
`),x=new Blob(["\uFEFF"+re],{type:"text/csv;charset=utf-8"}),u=URL.createObjectURL(x),I=document.createElement("a");I.href=u,I.download="卡密组批量导入模板.csv",document.body.appendChild(I),I.click(),I.remove(),URL.revokeObjectURL(u)},_e=async()=>{if(q){be(!0),Y(null);try{const c=await lr(q);if(Y(c),c.created>0){const _=await st();s(_)}}catch(c){Y({error:(c==null?void 0:c.message)||"上传失败"})}finally{be(!1)}}},$e=async()=>{if(!(!ge||!G.trim())){be(!0),me(null);try{const c=await rr(ge,G);me({added:c.added}),ae("");const _=await st();s(_)}catch(c){alert("追加失败:"+((c==null?void 0:c.message)||"未知错误"))}finally{be(!1)}}},fe=()=>{var c;N("create"),xe(null),Y(null),L((c=w[0])!=null&&c.id?String(w[0].id):""),ae(""),me(null),pe(!0)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:fe,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(It,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>v(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(at,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-surface-muted p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(ha,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按卡密类型筛选",value:$,onChange:c=>T(c.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(Nt,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"按卡密名称搜索",placeholder:"搜索卡密名称...",value:X,onChange:c=>M(c.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",ee.length," / ",t.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:ee.map(c=>{let _="";return c.type==="data"&&c.data_content?_=`库存: ${c.data_content.split(`
`).filter(x=>x.trim()).length} 条`:c.type==="text"&&c.text_content?_=c.text_content:c.type==="api"&&c.api_config?_=c.api_config.url:c.type==="image"&&c.image_url&&(_="图片链接"),e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(se,{type:c.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:c.name,children:c.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:()=>W(c.id),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:c.id}),e.jsx(Ja,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${c.type==="text"?"bg-blue-50 text-blue-600":c.type==="data"?"bg-purple-50 text-purple-600":c.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:c.type==="text"?"文本":c.type==="data"?"批量":c.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:_,children:_})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:c.description||"-",children:c.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:()=>h(c),className:`w-12 h-8 rounded-full relative transition-colors ${c.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${c.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:()=>we(c),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(jt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>F(c.id),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Ke,{className:"h-4 w-4"})})]})})]},c.id)})})]})}),ee.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(xa,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:t.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),l&&k&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:()=>i(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(De,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:g.name||"",onChange:c=>R({...g,name:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:g.type||"text",onChange:c=>R({...g,type:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(k==null?void 0:k.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),g.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:g.api_url||"",onChange:c=>R({...g,api_url:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsLine truncated
卡号1:密码1
卡号2:密码2
或者
兑换码1
兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:g.data_content?g.data_content.split(`
`).filter(c=>c.trim()).length:0})," 条"]})]})]}),g.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:g.image_url||"",onChange:c=>R({...g,image_url:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),g.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:g.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:c=>{c.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:g.delay_seconds||0,onChange:c=>R({...g,delay_seconds:parseInt(c.target.value)||0}),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:g.description||"",onChange:c=>R({...g,description:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:()=>R({...g,enabled:!g.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${g.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${g.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>i(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:je,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ye,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),p&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:()=>v(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(De,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:y.name,onChange:c=>J({...y,name:c.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>J({...y,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${y.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(ls,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>J({...y,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${y.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Is,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>J({...y,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${y.type==="image"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children Line truncated
CODE-789012
...`:"请输入每次发货时发送的固定文字"}),y.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-brand",children:y.content.split(`
`).filter(c=>c.trim()).length})," 条"]})]}),y.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:y.api_method,onChange:c=>J({...y,api_method:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:y.api_timeout,onChange:c=>J({...y,api_timeout:parseInt(c.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:y.api_headers,onChange:c=>J({...y,api_headers:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:y.api_params,onChange:c=>J({...y,api_params:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:y.description,onChange:c=>J({...y,description:c.target.value}),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:y.delay_seconds,onChange:c=>J({...y,delay_seconds:parseInt(c.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>v(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:d,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(at,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),Z&&qe.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:()=>pe(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(De,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:()=>N("create"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${de==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Qa,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>N("append"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${de==="append"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(It,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),de==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),'。 类型填 text/data/image;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:ie,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm tran Line truncated
VIP-002
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsx("p",{className:"text-xs text-gray-500",children:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),H&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",H.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:()=>pe(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),de==="create"?e.jsxs("button",{onClick:_e,disabled:!q||U,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[U?e.jsx(Re,{className:"w-4 h-4 animate-spin"}):e.jsx(It,{className:"w-4 h-4"}),U?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:$e,disabled:!ge||!G.trim()||U||w.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[U?e.jsx(Re,{className:"w-4 h-4 animate-spin"}):e.jsx(at,{className:"w-4 h-4"}),U?"处理中...":"追加卡密"]})]})]})}),document.body)]})},sn=t=>t.find(s=>s.status==="running"||s.status==="canceling"),an=t=>{const s=String(t||"").trim();return s?/^[¥¥]/.test(s)?s:`¥${s}`:"-"},ln=({onConfigureDelivery:t})=>{const[s,l]=r.useState([]),[i,p]=r.useState([]),[v,k]=r.useState([]),[D,g]=r.useState(""),[R,y]=r.useState(""),[J,Z]=r.useState(!1),[pe,de]=r.useState(!1),[N,q]=r.useState(!1),[xe,Q]=r.useState(!1),[Y,U]=r.useState(!1),[be,ge]=r.useState(!1),[L,G]=r.useState(!1),[ae,H]=r.useState("upload"),[me,$]=r.useState(null),[T,X]=r.useState(null),[M,se]=r.useState(""),[we,je]=r.useState(!1),[F,d]=r.useState({catId:"",catName:"",channelCatId:"",tbCatId:""}),[h,W]=r.useState(null),[w,ee]=r.useState(null),[ie,_e]=r.useState(null),$e=r.useRef(!1),[fe,c]=r.useState(null),[_,re]=r.useState({}),[x,u]=r.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[I,A]=r.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[K,P]=r.useState([]);r.useEffect(()=>{if(!be||I.images.length===0){P([]);return}const n=I.images.map((O,le)=>({key:O.name+le,url:URL.createObjectURL(O)}));return P(n),()=>{n.forEach(O=>URL.revokeObjectURL(O.url))}},[be,I.images]);const ke=async()=>{const n=await _t();l(n)},Oe=async()=>{p(await ms())};r.useEffect(()=>{Promise.all([Pt(),_t(),ms(),Us(20)]).then(([n,O,le,Je])=>{k(n),l(O),p(le);const Ge=Je.find(ze=>["running","canceling"].includes(ze.status))||Je.find(ze=>ze.status!=="preview");_e(Ge||null)}).catch(n=>console.error("加载商品配置失败:",n))},[]),r.useEffect(()=>{if(!L||!(w!=null&&w.id)||!["running","canceling"].includes(w.status))return;const n=window.setInterval(async()=>{if(!$e.current){$e.current=!0;try{const O=await gt(w.id);ee(O),_e(O),["running","canceling"].includes(O.status)||(H("done"),await ke(),await Oe())}catch(O){console.error("刷新批量铺货进度失败:",O)}finally{$e.current=!1}}},3e3);return()=>{window.clearInterval(n)}},[L,w==null?void 0:w.id,w==null?void 0:w.status]);const Pe=async()=>{if(!D)return alert("请先选择账号");Z(!0);try{const n=await nr(D);await ke(),alert((n==null?void 0:n.message)||"商品同步完成")}catch(n){console.error("同步商品失败:",n),alert((n==null?void 0:n.message)||"同步失败,请重试")}finally{Z(!1)}},Ee=n=>{c(n),re({...n}),Q(!0)},Te=async()=>{if(fe)try{await gr(fe.cookie_id,fe.item_id,{item_title:_.item_title||"",item_description:_.item_description||"",item_category:_.item_category||"",item_price:_.item_price||"",item_detail:_.item_detail||fe.item_detail||""}),await ke(),await Oe(),Q(!1),c(null)}catch(n){console.error("更新商品失败:",n),alert("更新失败,请重试")}},f=async n=>{if(confirm(`确认删除商品"${n.item_title}"吗?`))try{await ir(n.cookie_id,n.item_id),l(O=>O.filter(le=>!(le.cookie_id===n.cookie_id&&le.item_id===n.item_id)))}catch(O){console.error("删除商品失败:",O),alert("删除失败,请重试")}},C=async()=>{try{if(!x.cookie_id||!x.item_id){alert("请选择账号并填写商品ID");return}await or(x.cookie_id,{item_id:x.item_id,item_title:x.item_title,item_price:x.item_price,item_detail:x.item_image?JSON.stringify({item_image:x.item_image}):""}),await ke(),U(!1),u({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(n){console.error("添加商品失败:",n),alert("添加失败,请重试")}},B=async()=>{if(!I.cookie_id)return alert("请选择发布账号");if(!I.title.trim())return alert("请填写商品标题");if(!I.price.trim())return alert("请填写商品价格");if(!I.quantity||Number(I.quantity)<=0)return alert("库存数量必须大于 0");if(I.images.length===0)return alert("至少上传 1 张商品图片");if(I.postage_mode==="f Line truncated
`),Je=new Blob(["\uFEFF"+le],{type:"text/csv;charset=utf-8"}),Ge=URL.createObjectURL(Je),ze=document.createElement("a");ze.href=Ge,ze.download="批量铺货模板.csv",document.body.appendChild(ze),ze.click(),ze.remove(),URL.revokeObjectURL(Ge)},ne=()=>{u(n=>({...n,cookie_id:D||n.cookie_id})),U(!0)},We=()=>{A(n=>({...n,cookie_id:D||n.cookie_id})),ge(!0)},et=n=>i.filter(O=>O.cookie_id===n.cookie_id&&O.item_id===n.item_id).length>0?i.filter(O=>O.cookie_id===n.cookie_id&&O.item_id===n.item_id):i.filter(O=>O.cookie_id===n.cookie_id&&!O.item_id),tt=n=>{switch(n){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"canceling":return"正在安全取消";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return n||"-"}},it=n=>{switch(n){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"partially_failed":case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}},Ve=r.useMemo(()=>new Map(v.map(n=>[n.id,n])),[v]),Qe=r.useMemo(()=>R?s.filter(n=>n.cookie_id===R):s,[R,s]),He=n=>{const O=Ve.get(n),le=(O==null?void 0:O.remark)||(O==null?void 0:O.nickname);return le?`${le} · ${n.slice(0,6)}`:`账号 ${n.slice(0,8)}`},pt=n=>{const O=Ve.get(n);return(O==null?void 0:O.remark)||(O==null?void 0:O.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ha,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:R,onChange:n=>y(n.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),v.map(n=>e.jsx("option",{value:n.id,children:He(n.id)},n.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(mt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:D,onChange:n=>g(n.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),v.map(n=>e.jsx("option",{value:n.id,children:He(n.id)},n.id))]})]})]}),e.jsxs("button",{onClick:Pe,disabled:J||!D,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(Ue,{className:`w-4 h-4 ${J?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:ne,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(at,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:We,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-500 text-white hover:bg-emerald-600 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(Ht,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void V(),className:"px-5 py-3 rounded-2xl font-bold bg-brand text-white hover:bg-brand-highlight transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(Tt,{className:"w-4 h-4"}),ie&&["running","canceling"].includes(ie.status)?"继续批量任务":"批量铺货"]}),ie&&!["running","canceling"].includes(ie.status)&&e.jsx("button",{onClick:()=>void Me(),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[Qe.map(n=>{const O=et(n),le=O.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all gro Line truncated
@@ -1,19 +0,0 @@
import{j as e,r,b as qe,c as na,d as Da}from"./react-vendor-C_od1ZSF.js";import{L as Ta,U as ia,M as ss,C as as,B as oa,S as ca,Z as ls,a as ft,b as hs,c as gs,d as bs,e as Ea,f as nt,A as Cs,D as Ma,g as Ss,P as da,h as Rt,E as xa,T as qa,i as Fa,j as Pe,X as De,k as Ba,l as za,m as ys,n as ma,o as Ye,Q as Gt,p as mt,q as Ze,r as yt,s as At,t as Ls,R as Ue,u as pa,v as Ua,w as Ke,K as Wa,x as xt,y as rt,z as at,F as Os,G as _t,H as jt,I as It,J as ua,N as Va,O as Is,V as As,W as Ja,Y as Qa,_ as Ga,$ as Ka,a0 as Kt,a1 as Tt,a2 as rs,a3 as Ha,a4 as Za,a5 as ns,a6 as Ya,a7 as Xa,a8 as is,a9 as Rs,aa as Ut,ab as ha,ac as el,ad as tl,ae as Vt,af as ga,ag as sl,ah as al,ai as ll,aj as rl,ak as nl,al as il,am as ol}from"./icons-vendor-DjsKcZkz.js";import{R as Et,B as cl,X as $s,Y as Ps,T as Mt,a as dl,C as Ht,A as xl,b as ml,c as pl,P as Ds,d as Ts,L as ul}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const m of document.querySelectorAll('link[rel="modulepreload"]'))i(m);new MutationObserver(m=>{for(const v of m)if(v.type==="childList")for(const k of v.addedNodes)k.tagName==="LINK"&&k.rel==="modulepreload"&&i(k)}).observe(document,{childList:!0,subtree:!0});function l(m){const v={};return m.integrity&&(v.integrity=m.integrity),m.referrerPolicy&&(v.referrerPolicy=m.referrerPolicy),m.crossOrigin==="use-credentials"?v.credentials="include":m.crossOrigin==="anonymous"?v.credentials="omit":v.credentials="same-origin",v}function i(m){if(m.ep)return;m.ep=!0;const v=l(m);fetch(m.href,v)}})();const hl=({className:t="w-full h-full text-white"})=>e.jsx("svg",{className:t,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),os=({sizeClass:t="w-12 h-12",logoClassName:s="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${t} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23.51 12.25 L 27.29 Line truncated
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(hs,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:Dt,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:I,children:"取消"}),e.jsxs("button",{onClick:Ge,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:I,children:[I?e.jsx(Pe,{className:"w-4 h-4 animate-spin"}):e.jsx(Ye,{className:"w-4 h-4"}),I?"保存中...":"保存"]})]})})]})}),document.body)]})},Hr=t=>({total:Number((t==null?void 0:t.total)||0),success_count:Number((t==null?void 0:t.success_count)||0),failed_count:Number((t==null?void 0:t.failed_count)||0),results:Array.isArray(t==null?void 0:t.results)?t.results.map(s=>({order_id:String((s==null?void 0:s.order_id)||"unknown"),success:(s==null?void 0:s.success)===!0,message:String((s==null?void 0:s.message)||"")})):[]}),Zr=t=>(t==null?void 0:t.results.filter(s=>!s.success))||[],Gs=({status:t})=>{const s={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-brand text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${s[t]||s.cancelled}`,children:l[t]||t})},Yr=()=>{const[t,s]=r.useState([]),[l,i]=r.useState([]),[m,v]=r.useState([]),[k,D]=r.useState({}),[g,R]=r.useState("all"),[f,Q]=r.useState(""),[Z,me]=r.useState(""),[ce,_]=r.useState(""),q=r.useRef(0),[de,G]=r.useState(1),[Y,U]=r.useState(1),[fe,ge]=r.useState(!1),[O,K]=r.useState(!1),[xe,F]=r.useState(!1),[J,$]=r.useState(!1),[E,se]=r.useState(null),[M,ae]=r.useState(null),[Le,Ne]=r.useState({}),[pe,u]=r.useState(!1),[h,W]=r.useState(""),[w,X]=r.useState(!1),[ne,_e]=r.useState(null),[Re,be]=r.useState(null),[c,N]=r.useState(null),[le,d]=r.useState(!1),[p,I]=r.useState(null),[A,H]=r.useState(null),P=async()=>{const x=++q.current;ge(!0);try{const T=await Vl(f||void 0,g,de,20,ce);if(x!==q.current)return;s(T.data),U(T.total_pages)}catch(T){console.error("加载订单失败:",T)}finally{x===q.current&&ge(!1)}},we=(x,T,ie)=>{if(ie&&ie.trim())return ie;if(k[`${x}:${T}`])return k[`${x}:${T}`];const re=l.find(We=>{if(ie&&We.item_title){const et=ie.toLowerCase(),tt=We.item_title.toLowerCase();return tt.includes(et)||et.includes(tt)}return!1});return re!=null&&re.item_title?re.item_title:"未知商品"},Oe=x=>{const T={};x.forEach(ie=>{ie.item_id&&(T[`${ie.cookie_id}:${ie.item_id}`]=ie.item_title||ie.item_id)}),D(T)};r.useEffect(()=>{const x=window.setTimeout(()=>{G(1),_(Z.trim())},300);return()=>window.clearTimeout(x)},[Z]),r.useEffect(()=>{P()},[f,g,de,ce]),r.useEffect(()=>{Promise.all([$t(),Nt()]).then(([x,T])=>{v(x),i(T),Oe(T)}).catch(x=>{console.error("加载商品列表失败:",x)})},[]);const $e=r.useMemo(()=>new Map(m.map(x=>[x.id,x])),[m]),Te=x=>{const T=$e.get(x),ie=(T==null?void 0:T.remark)||(T==null?void 0:T.nickname);return ie?`${ie} · ${x.slice(0,6)}`:`账号 ${x.slice(0,8)}`},Ee=x=>{const T=$e.get(x);return(T==null?void 0:T.remark)||(T==null?void 0:T.nickname)||"未命名账号"},y=async()=>{ge(!0);try{const x=await Gl(f||void 0,g);await P(),x!=null&&x.message&&alert(x.message)}catch(x){console.error("同步订单失败:",x),alert((x==null?void 0:x.message)||"同步失败,请重试")}finally{ge(!1)}},C=x=>{W(x),_e(null),u(!0)},B=async x=>{var T;X(!0),_e(null);try{const ie=await Hl([h],x),re=(T=ie==null?void 0:ie.results)==null?void 0:T[0];re!=null&&re.success?(_e({success:!0,message:re.message}),P()):_e({success:!1,message:(re==null?void 0:re.message)||"发货失败"})}catch(ie){_e({success:!1,message:(ie==null?void 0:ie.message)||"请求失败"})}finally{X(!1)}},V=x=>{se(x),K(!0)},ke=x=>{ae({...x}),F(!0)},Me=async()=>{if(!(!M||!M.order_id))try{const x={};M.status!==void 0&&(x.order_status=M.status),M.buyer_id!==void 0&&(x.buyer_id=M.buyer_id),M.amount!==void 0&&(x.amount=M.amount),M.receiver_name!==void 0&&(x.receiver_name=M.receiver_name),M.receiver_phone!== Line truncated
VIP-MONTH-002
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(A=>A.map(H=>`"${String(H).replace(/"/g,'""')}"`).join(",")).join(`
`),d=new Blob(["\uFEFF"+le],{type:"text/csv;charset=utf-8"}),p=URL.createObjectURL(d),I=document.createElement("a");I.href=p,I.download="卡密组批量导入模板.csv",document.body.appendChild(I),I.click(),I.remove(),URL.revokeObjectURL(p)},_e=async()=>{if(q){fe(!0),Y(null);try{const c=await ar(q);if(Y(c),c.created>0){const N=await st();s(N)}}catch(c){Y({error:(c==null?void 0:c.message)||"上传失败"})}finally{fe(!1)}}},Re=async()=>{if(!(!ge||!K.trim())){fe(!0),J(null);try{const c=await lr(ge,K);J({added:c.added}),xe("");const N=await st();s(N)}catch(c){alert("追加失败:"+((c==null?void 0:c.message)||"未知错误"))}finally{fe(!1)}}},be=()=>{var c;_("create"),de(null),Y(null),O((c=w[0])!=null&&c.id?String(w[0].id):""),xe(""),J(null),me(!0)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:be,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(It,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>v(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(at,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-surface-muted p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(ua,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按卡密类型筛选",value:$,onChange:c=>E(c.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(_t,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"按卡密名称搜索",placeholder:"搜索卡密名称...",value:se,onChange:c=>M(c.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",X.length," / ",t.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:X.map(c=>{let N="";return c.type==="data"&&c.data_content?N=`库存: ${c.data_content.split(`
`).filter(d=>d.trim()).length} 条`:c.type==="text"&&c.text_content?N=c.text_content:c.type==="api"&&c.api_config?N=c.api_config.url:c.type==="image"&&c.image_url&&(N="图片链接"),e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(ae,{type:c.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:c.name,children:c.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:()=>W(c.id),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:c.id}),e.jsx(Va,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${c.type==="text"?"bg-blue-50 text-blue-600":c.type==="data"?"bg-purple-50 text-purple-600":c.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:c.type==="text"?"文本":c.type==="data"?"批量":c.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:N,children:N})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:c.description||"-",children:c.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:()=>h(c),className:`w-12 h-8 rounded-full relative transition-colors ${c.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${c.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:()=>Le(c),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(jt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>pe(c.id),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Ke,{className:"h-4 w-4"})})]})})]},c.id)})})]})}),X.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(da,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:t.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),l&&k&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:()=>i(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(De,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:g.name||"",onChange:c=>R({...g,name:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:g.type||"text",onChange:c=>R({...g,type:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(k==null?void 0:k.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),g.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:g.api_url||"",onChange:c=>R({...g,api_url:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsLine truncated
卡号1:密码1
卡号2:密码2
或者
兑换码1
兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:g.data_content?g.data_content.split(`
`).filter(c=>c.trim()).length:0})," 条"]})]})]}),g.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:g.image_url||"",onChange:c=>R({...g,image_url:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),g.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:g.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:c=>{c.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:g.delay_seconds||0,onChange:c=>R({...g,delay_seconds:parseInt(c.target.value)||0}),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:g.description||"",onChange:c=>R({...g,description:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:()=>R({...g,enabled:!g.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${g.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${g.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>i(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:Ne,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ye,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),m&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:()=>v(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(De,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:f.name,onChange:c=>Q({...f,name:c.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>Q({...f,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${f.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(as,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>Q({...f,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${f.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Is,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>Q({...f,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${f.type==="image"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children Line truncated
CODE-789012
...`:"请输入每次发货时发送的固定文字"}),f.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-brand",children:f.content.split(`
`).filter(c=>c.trim()).length})," 条"]})]}),f.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:f.api_method,onChange:c=>Q({...f,api_method:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:f.api_timeout,onChange:c=>Q({...f,api_timeout:parseInt(c.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:f.api_headers,onChange:c=>Q({...f,api_headers:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:f.api_params,onChange:c=>Q({...f,api_params:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:f.description,onChange:c=>Q({...f,description:c.target.value}),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:f.delay_seconds,onChange:c=>Q({...f,delay_seconds:parseInt(c.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>v(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:u,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(at,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),Z&&qe.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:()=>me(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(De,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:()=>_("create"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${ce==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Ja,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>_("append"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${ce==="append"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(It,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),ce==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),'。 类型填 text/data/image;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:ne,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm tran Line truncated
VIP-002
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsx("p",{className:"text-xs text-gray-500",children:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),F&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",F.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:()=>me(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),ce==="create"?e.jsxs("button",{onClick:_e,disabled:!q||U,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[U?e.jsx(Pe,{className:"w-4 h-4 animate-spin"}):e.jsx(It,{className:"w-4 h-4"}),U?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:Re,disabled:!ge||!K.trim()||U||w.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[U?e.jsx(Pe,{className:"w-4 h-4 animate-spin"}):e.jsx(at,{className:"w-4 h-4"}),U?"处理中...":"追加卡密"]})]})]})}),document.body)]})},tn=t=>t.find(s=>s.status==="running"||s.status==="canceling"),sn=t=>{const s=String(t||"").trim();return s?/^[¥¥]/.test(s)?s:`¥${s}`:"-"},an=({onConfigureDelivery:t})=>{const[s,l]=r.useState([]),[i,m]=r.useState([]),[v,k]=r.useState([]),[D,g]=r.useState(""),[R,f]=r.useState(""),[Q,Z]=r.useState(!1),[me,ce]=r.useState(!1),[_,q]=r.useState(!1),[de,G]=r.useState(!1),[Y,U]=r.useState(!1),[fe,ge]=r.useState(!1),[O,K]=r.useState(!1),[xe,F]=r.useState("upload"),[J,$]=r.useState(null),[E,se]=r.useState(null),[M,ae]=r.useState(""),[Le,Ne]=r.useState(!1),[pe,u]=r.useState({catId:"",catName:"",channelCatId:"",tbCatId:""}),[h,W]=r.useState(null),[w,X]=r.useState(null),[ne,_e]=r.useState(null),Re=r.useRef(!1),[be,c]=r.useState(null),[N,le]=r.useState({}),[d,p]=r.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[I,A]=r.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[H,P]=r.useState([]);r.useEffect(()=>{if(!fe||I.images.length===0){P([]);return}const n=I.images.map((L,te)=>({key:L.name+te,url:URL.createObjectURL(L)}));return P(n),()=>{n.forEach(L=>URL.revokeObjectURL(L.url))}},[fe,I.images]);const we=async()=>{const n=await Nt();l(n)},Oe=async()=>{m(await ms())};r.useEffect(()=>{Promise.all([$t(),Nt(),ms(),zs(20)]).then(([n,L,te,Je])=>{k(n),l(L),m(te);const Ge=Je.find(ze=>["running","canceling"].includes(ze.status))||Je.find(ze=>ze.status!=="preview");_e(Ge||null)}).catch(n=>console.error("加载商品配置失败:",n))},[]),r.useEffect(()=>{if(!O||!(w!=null&&w.id)||!["running","canceling"].includes(w.status))return;const n=window.setInterval(async()=>{if(!Re.current){Re.current=!0;try{const L=await gt(w.id);X(L),_e(L),["running","canceling"].includes(L.status)||(F("done"),await we(),await Oe())}catch(L){console.error("刷新批量铺货进度失败:",L)}finally{Re.current=!1}}},3e3);return()=>{window.clearInterval(n)}},[O,w==null?void 0:w.id,w==null?void 0:w.status]);const $e=async()=>{if(!D)return alert("请先选择账号");Z(!0);try{const n=await rr(D);await we(),alert((n==null?void 0:n.message)||"商品同步完成")}catch(n){console.error("同步商品失败:",n),alert((n==null?void 0:n.message)||"同步失败,请重试")}finally{Z(!1)}},Te=n=>{c(n),le({...n}),G(!0)},Ee=async()=>{if(be)try{await hr(be.cookie_id,be.item_id,{item_title:N.item_title||"",item_description:N.item_description||"",item_category:N.item_category||"",item_price:N.item_price||"",item_detail:N.item_detail||be.item_detail||""}),await we(),await Oe(),G(!1),c(null)}catch(n){console.error("更新商品失败:",n),alert("更新失败,请重试")}},y=async n=>{if(confirm(`确认删除商品"${n.item_title}"吗?`))try{await nr(n.cookie_id,n.item_id),l(L=>L.filter(te=>!(te.cookie_id===n.cookie_id&&te.item_id===n.item_id)))}catch(L){console.error("删除商品失败:",L),alert("删除失败,请重试")}},C=async()=>{try{if(!d.cookie_id||!d.item_id){alert("请选择账号并填写商品ID");return}await ir(d.cookie_id,{item_id:d.item_id,item_title:d.item_title,item_price:d.item_price,item_detail:d.item_image?JSON.stringify({item_image:d.item_image}):""}),await we(),U(!1),p({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(n){console.error("添加商品失败:",n),alert("添加失败,请重试")}},B=async()=>{if(!I.cookie_id)return alert("请选择发布账号");if(!I.title.trim())return alert("请填写商品标题");if(!I.price.trim())return alert("请填写商品价格");if(!I.quantity||Number(I.quantity)<=0)return alert("库存数量必须大于 0");if(I.images.length===0)return alert("至少上传 1 张商品图片");if(I.postage_mode==="fi Line truncated
`),Je=new Blob(["\uFEFF"+te],{type:"text/csv;charset=utf-8"}),Ge=URL.createObjectURL(Je),ze=document.createElement("a");ze.href=Ge,ze.download="批量铺货模板.csv",document.body.appendChild(ze),ze.click(),ze.remove(),URL.revokeObjectURL(Ge)},re=()=>{p(n=>({...n,cookie_id:D||n.cookie_id})),U(!0)},We=()=>{A(n=>({...n,cookie_id:D||n.cookie_id})),ge(!0)},et=n=>i.filter(L=>L.cookie_id===n.cookie_id&&L.item_id===n.item_id).length>0?i.filter(L=>L.cookie_id===n.cookie_id&&L.item_id===n.item_id):i.filter(L=>L.cookie_id===n.cookie_id&&!L.item_id),tt=n=>{switch(n){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"canceling":return"正在安全取消";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return n||"-"}},it=n=>{switch(n){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"partially_failed":case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}},Ve=r.useMemo(()=>new Map(v.map(n=>[n.id,n])),[v]),Qe=r.useMemo(()=>R?s.filter(n=>n.cookie_id===R):s,[R,s]),He=n=>{const L=Ve.get(n),te=(L==null?void 0:L.remark)||(L==null?void 0:L.nickname);return te?`${te} · ${n.slice(0,6)}`:`账号 ${n.slice(0,8)}`},pt=n=>{const L=Ve.get(n);return(L==null?void 0:L.remark)||(L==null?void 0:L.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ka,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:R,onChange:n=>f(n.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),v.map(n=>e.jsx("option",{value:n.id,children:He(n.id)},n.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(mt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:D,onChange:n=>g(n.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),v.map(n=>e.jsx("option",{value:n.id,children:He(n.id)},n.id))]})]})]}),e.jsxs("button",{onClick:$e,disabled:Q||!D,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(Ue,{className:`w-4 h-4 ${Q?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:re,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(at,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:We,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-500 text-white hover:bg-emerald-600 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(Kt,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void V(),className:"px-5 py-3 rounded-2xl font-bold bg-brand text-white hover:bg-brand-highlight transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(Tt,{className:"w-4 h-4"}),ne&&["running","canceling"].includes(ne.status)?"继续批量任务":"批量铺货"]}),ne&&!["running","canceling"].includes(ne.status)&&e.jsx("button",{onClick:()=>void Me(),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[Qe.map(n=>{const L=et(n),te=L.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all gro Line truncated
+1 -1
View File
@@ -6,7 +6,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ydisks闲鱼助手 - 自动发货与管家系统</title>
<meta name="description" content="Ydisks闲鱼助手 - 自动回复、自动发货、订单管理、AI智能议价一体化解决方案" />
<script type="module" crossorigin src="/static/assets/index-DLBJvCyf.js"></script>
<script type="module" crossorigin src="/static/assets/index-Bp6jEzSl.js"></script>
<link rel="modulepreload" crossorigin href="/static/assets/react-vendor-C_od1ZSF.js">
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-DjsKcZkz.js">
<link rel="modulepreload" crossorigin href="/static/assets/vendor-D-Edl3pr.js">
+95
View File
@@ -0,0 +1,95 @@
#!/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"
LOG_DIR="/var/log/$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}"
RUNTIME_SOURCE="${XIANYU_PLAYWRIGHT_RUNTIME_SOURCE:-$SCRIPT_DIR/playwright-runtime}"
ICON_SOURCE="${XIANYU_ICON_SOURCE:-$SCRIPT_DIR/icon.png}"
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
case "$(uname -m)" in
x86_64|amd64) RUNTIME_ARCH="amd64" ;;
aarch64|arm64) RUNTIME_ARCH="arm64" ;;
*) echo "不支持的 Linux 架构:$(uname -m)" >&2; exit 1 ;;
esac
if [[ ! -d "$RUNTIME_SOURCE/$RUNTIME_ARCH/playwright-driver" ]] || \
[[ ! -d "$RUNTIME_SOURCE/$RUNTIME_ARCH/playwright-browsers" ]]; then
echo "找不到 $RUNTIME_ARCH 架构的 Playwright runtime:$RUNTIME_SOURCE/$RUNTIME_ARCH" >&2
exit 1
fi
if [[ ! -f "$ICON_SOURCE" ]]; then
echo "找不到应用图标:$ICON_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 "$LOG_DIR"
rm -rf "$INSTALL_DIR/playwright-runtime"
install -d -m 0755 "$INSTALL_DIR/playwright-runtime"
cp -R "$RUNTIME_SOURCE/." "$INSTALL_DIR/playwright-runtime/"
chmod -R a+rX "$INSTALL_DIR/playwright-runtime"
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 -D -m 0644 "$ICON_SOURCE" "/usr/share/icons/hicolor/512x512/apps/$APP_NAME.png"
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_DEPS:-0}" != "1" ]]; then
"$INSTALL_DIR/browser-install" \
-driver-dir "$INSTALL_DIR/playwright-runtime/$RUNTIME_ARCH/playwright-driver" \
-deps-only
fi
systemctl daemon-reload
systemctl enable --now "$SERVICE_NAME"
systemctl --no-pager --full status "$SERVICE_NAME" || true
echo "安装完成:systemctl status $SERVICE_NAME"
+17
View File
@@ -0,0 +1,17 @@
#!/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"
rm -f "/usr/share/icons/hicolor/512x512/apps/$APP_NAME.png"
echo "程序和服务已移除;数据仍保留在 /var/lib/$APP_NAME。"
@@ -0,0 +1,22 @@
[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
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
TimeoutStopSec=30s
NoNewPrivileges=true
PrivateTmp=true
[Install]
WantedBy=multi-user.target
+26
View File
@@ -0,0 +1,26 @@
<?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.ydisks.xianyu-helper</string>
<key>CFBundleName</key>
<string>Ydisks闲鱼助手</string>
<key>CFBundleDisplayName</key>
<string>Ydisks闲鱼助手</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>Ydisks闲鱼助手</string>
<key>CFBundleIconName</key>
<string>AppIcon</string>
<key>CFBundleIconFile</key>
<string>icon.icns</string>
</dict>
</plist>
+159
View File
@@ -0,0 +1,159 @@
#!/bin/sh
set -eu
VERSION="${1:?version is required}"
DIST_DIR="${2:?dist directory is required}"
ARCH="${3:?architecture is required (arm64 or amd64)}"
SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
PROJECT_ROOT="$(CDPATH= cd -- "$SCRIPT_DIR/../.." && pwd)"
BIN_DIR="$DIST_DIR/$ARCH"
ROOT_DIR="$DIST_DIR/pkgroot-$ARCH"
APP_DIR="$ROOT_DIR/Applications/Ydisks闲鱼助手"
APP="$APP_DIR/Ydisks闲鱼助手.app"
PACKAGE_PATH="$DIST_DIR/Ydisks-Xianyu-Helper-$VERSION-$ARCH.pkg"
UNSIGNED_PACKAGE_PATH="$DIST_DIR/.Ydisks-Xianyu-Helper-$VERSION-$ARCH.unsigned.pkg"
case "$ARCH" in
arm64|amd64) ;;
*) echo "不支持的 macOS 架构:$ARCH" >&2; exit 1 ;;
esac
if [ ! -x "$BIN_DIR/xianyu-server" ] || [ ! -x "$BIN_DIR/xianyu-tray" ]; then
echo "缺少 $ARCH 架构的桌面二进制:$BIN_DIR" >&2
exit 1
fi
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
rm -rf "$ROOT_DIR"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Helpers" "$APP/Contents/Resources"
cp "$BIN_DIR/xianyu-server" "$APP/Contents/Helpers/xianyu-server"
cp "$BIN_DIR/xianyu-tray" "$APP/Contents/MacOS/Ydisks闲鱼助手"
cp "$SCRIPT_DIR/uninstall.command" "$APP_DIR/卸载 Ydisks闲鱼助手.command"
cp "$SCRIPT_DIR/com.ydisks.xianyu-helper.server.plist.template" "$APP/Contents/Resources/"
cp "$SCRIPT_DIR/com.ydisks.xianyu-helper.tray.plist.template" "$APP/Contents/Resources/"
mkdir -p "$APP/Contents/Resources/playwright-runtime/$ARCH"
cp -R "$DIST_DIR/playwright-runtime/$ARCH/." "$APP/Contents/Resources/playwright-runtime/$ARCH/"
cp "$PROJECT_ROOT/icon/macos/Assets.car" "$APP/Contents/Resources/Assets.car"
cp "$PROJECT_ROOT/icon/macos/icon.icns" "$APP/Contents/Resources/icon.icns"
sed "s/__VERSION__/$VERSION/g" "$SCRIPT_DIR/Info.plist" > "$APP/Contents/Info.plist"
chmod 0755 "$APP/Contents/MacOS/Ydisks闲鱼助手" "$APP/Contents/Helpers/xianyu-server" "$APP_DIR/卸载 Ydisks闲鱼助手.command"
# pkgbuild 会保留 runtime 文件的原始权限;Playwright 下载的 Node 和
# Chromium Mach-O 可能只有所有者可执行。安装包由 root 安装后,普通用户
# 启动 LaunchAgent 时会因 permission denied 无法执行,因此统一授予执行权限。
runtime_files="$(mktemp)"
trap 'rm -f "$runtime_files"' EXIT
find "$APP/Contents/Resources/playwright-runtime" -type f -print > "$runtime_files"
while IFS= read -r runtime_file; do
if file "$runtime_file" | grep -q 'Mach-O'; then
chmod 0755 "$runtime_file"
fi
done < "$runtime_files"
if [ -n "${MACOS_SIGNING_IDENTITY:-}" ]; then
sign_code() {
target="$1"
if [ -n "${MACOS_SIGNING_KEYCHAIN:-}" ]; then
codesign --force --sign "$MACOS_SIGNING_IDENTITY" \
--keychain "$MACOS_SIGNING_KEYCHAIN" --timestamp=none "$target"
else
codesign --force --sign "$MACOS_SIGNING_IDENTITY" \
--timestamp=none "$target"
fi
}
sign_nested_bundle() {
nested_bundle="$1"
echo "Signing nested bundle: $nested_bundle"
if [ -n "${MACOS_SIGNING_KEYCHAIN:-}" ]; then
codesign --force --deep --sign "$MACOS_SIGNING_IDENTITY" \
--keychain "$MACOS_SIGNING_KEYCHAIN" --timestamp=none "$nested_bundle"
else
codesign --force --deep --sign "$MACOS_SIGNING_IDENTITY" \
--timestamp=none "$nested_bundle"
fi
}
# Playwright runtime 中包含独立 Node 和 Chromium.app。bundle 主程序不能
# 提前作为单个 Mach-O 签名,否则 codesign 会先校验尚未签名的内层 Framework。
# 因此这里只签 bundle 外的独立 Mach-O,再按目录深度递归签名所有 bundle。
signing_list="$runtime_files"
find "$APP/Contents/Resources/playwright-runtime" -type f -print > "$signing_list"
while IFS= read -r executable; do
case "$executable" in
*.app/*|*.framework/*|*.xpc/*) continue ;;
esac
if file "$executable" | grep -q 'Mach-O'; then
sign_code "$executable"
fi
done < "$signing_list"
find "$APP/Contents/Resources/playwright-runtime" -depth -type d \
\( -name '*.framework' -o -name '*.xpc' -o -name '*.app' \) -print > "$signing_list"
while IFS= read -r nested_bundle; do
sign_nested_bundle "$nested_bundle"
done < "$signing_list"
# macOS 代码签名必须从内部组件开始,最后再签名 App 包本身。
sign_code "$APP/Contents/Helpers/xianyu-server"
sign_code "$APP/Contents/MacOS/Ydisks闲鱼助手"
sign_code "$APP"
codesign --verify --deep --strict --verbose=2 "$APP"
fi
if [ -n "${MACOS_SIGNING_IDENTITY:-}" ] && [ -z "${MACOS_INSTALLER_SIGNING_IDENTITY:-}" ]; then
echo 'MACOS_INSTALLER_SIGNING_IDENTITY 未设置,不能生成已签名 macOS 安装包' >&2
exit 1
fi
rm -f "$PACKAGE_PATH" "$UNSIGNED_PACKAGE_PATH"
pkgbuild \
--root "$ROOT_DIR" \
--component-plist "$SCRIPT_DIR/component.plist" \
--scripts "$SCRIPT_DIR/scripts" \
--identifier com.ydisks.xianyu-helper \
--version "$VERSION" \
--install-location / \
"$UNSIGNED_PACKAGE_PATH"
if [ -n "${MACOS_INSTALLER_SIGNING_IDENTITY:-}" ]; then
if [ -n "${MACOS_SIGNING_KEYCHAIN:-}" ]; then
productsign --sign "$MACOS_INSTALLER_SIGNING_IDENTITY" \
--keychain "$MACOS_SIGNING_KEYCHAIN" \
"$UNSIGNED_PACKAGE_PATH" "$PACKAGE_PATH"
else
productsign --sign "$MACOS_INSTALLER_SIGNING_IDENTITY" \
"$UNSIGNED_PACKAGE_PATH" "$PACKAGE_PATH"
fi
pkgutil --check-signature "$PACKAGE_PATH"
rm -f "$UNSIGNED_PACKAGE_PATH"
else
mv "$UNSIGNED_PACKAGE_PATH" "$PACKAGE_PATH"
fi
@@ -0,0 +1,18 @@
<?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.ydisks.xianyu-helper.server</string>
<key>ProgramArguments</key>
<array>
<string>__SERVER__</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>
<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,13 @@
<?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.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>
</plist>
+18
View File
@@ -0,0 +1,18 @@
<?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">
<array>
<dict>
<key>RootRelativeBundlePath</key>
<string>Applications/Ydisks闲鱼助手/Ydisks闲鱼助手.app</string>
<key>BundleIsRelocatable</key>
<false/>
<key>BundleIsVersionChecked</key>
<false/>
<key>BundleHasStrictIdentifier</key>
<true/>
<key>BundleOverwriteAction</key>
<string>upgrade</string>
</dict>
</array>
</plist>
+72
View File
@@ -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"
+119
View File
@@ -0,0 +1,119 @@
#!/bin/sh
set -eu
INSTALL_LOG="/var/log/ydisks-xianyu-helper-install.log"
exec >>"$INSTALL_LOG" 2>&1
trap 'exit_code=$?; printf "[%s] postinstall exit code: %s\\n" "$(date -u "+%Y-%m-%dT%H:%M:%SZ")" "$exit_code"' EXIT
printf '\n[%s] postinstall start; uid=%s; user=%s; args=%s\n' \
"$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$(id -u)" "$(id -un)" "$*"
set -x
SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
APP=""
for app_path in \
"/Applications/Ydisks闲鱼助手/Ydisks闲鱼助手.app" \
"/Applications/Ydisks Xianyu Helper.app" \
"/Applications/Ydisks Xianyu Helper.localized/Ydisks Xianyu Helper.app"
do
if [ -f "$app_path/Contents/Info.plist" ]; then
APP="$app_path"
break
fi
done
if [ -z "$APP" ]; then
echo "找不到已安装的 Ydisks闲鱼助手.app,无法继续注册服务。"
exit 1
fi
SERVER="$APP/Contents/Helpers/xianyu-server"
TRAY="$APP/Contents/MacOS/Ydisks闲鱼助手"
RUNTIME_ROOT="$APP/Contents/Resources/playwright-runtime"
CONSOLE_USER="$(stat -f '%Su' /dev/console)"
if [ "$CONSOLE_USER" = "root" ] || [ -z "$CONSOLE_USER" ]; then
echo "没有登录用户,跳过 LaunchAgent;登录后请重新打开应用。"
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"
LOG_DIR="$HOME_DIR/Library/Logs/YdisksXianyuHelper"
AGENT_DIR="$HOME_DIR/Library/LaunchAgents"
RUNTIME_ARCH=""
for candidate_arch in arm64 amd64; do
if [ -d "$RUNTIME_ROOT/$candidate_arch/playwright-driver" ] && [ -d "$RUNTIME_ROOT/$candidate_arch/playwright-browsers" ]; then
RUNTIME_ARCH="$candidate_arch"
break
fi
done
if [ -z "$RUNTIME_ARCH" ]; then
echo "安装包缺少完整的 Playwright runtime:$RUNTIME_ROOT"
exit 1
fi
echo "使用 $RUNTIME_ARCH 架构的 Playwright runtime。"
mkdir -p "$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'
}
SERVER_ESCAPED="$(escape_sed "$SERVER")"
TRAY_ESCAPED="$(escape_sed "$TRAY")"
DATA_ESCAPED="$(escape_sed "$DATA_DIR")"
LOG_ESCAPED="$(escape_sed "$LOG_DIR")"
RUNTIME_ROOT_ESCAPED="$(escape_sed "$RUNTIME_ROOT")"
SERVER_LABEL="com.ydisks.xianyu-helper.server"
TRAY_LABEL="com.ydisks.xianyu-helper.tray"
server_plist="$AGENT_DIR/$SERVER_LABEL.plist"
tray_plist="$AGENT_DIR/$TRAY_LABEL.plist"
sed -e "s|__SERVER__|$SERVER_ESCAPED|g" \
-e "s|__DATA_DIR__|$DATA_ESCAPED|g" \
-e "s|__LOG_DIR__|$LOG_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"
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"
launchctl bootout "gui/$UID_VALUE/$LEGACY_SERVER_LABEL" >/dev/null 2>&1 || true
launchctl bootout "gui/$UID_VALUE/$LEGACY_TRAY_LABEL" >/dev/null 2>&1 || true
rm -f "$AGENT_DIR/$LEGACY_SERVER_LABEL.plist" "$AGENT_DIR/$LEGACY_TRAY_LABEL.plist"
launchctl bootstrap "gui/$UID_VALUE" "$server_plist"
launchctl bootstrap "gui/$UID_VALUE" "$tray_plist"
# bootstrap 会根据 RunAtLoad 自动启动两个 LaunchAgent。这里不能再调用
# kickstart -k:它会给刚由 bootstrap 启动的托盘发送 SIGTERM,托盘会按
# 正常退出流程停止服务,导致安装完成后第一次启动就被自己关掉。
+51
View File
@@ -0,0 +1,51 @@
#!/bin/sh
set -eu
INSTALL_LOG="/var/log/ydisks-xianyu-helper-install.log"
exec >>"$INSTALL_LOG" 2>&1
trap 'exit_code=$?; printf "[%s] preinstall exit code: %s\\n" "$(date -u "+%Y-%m-%dT%H:%M:%SZ")" "$exit_code"' EXIT
printf '\n[%s] preinstall start; uid=%s; user=%s; args=%s\n' \
"$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$(id -u)" "$(id -un)" "$*"
set -x
EXPECTED_BUNDLE_ID="com.ydisks.xianyu-helper"
CANONICAL_APP_DIR="/Applications/Ydisks闲鱼助手"
CANONICAL_APP_PATH="$CANONICAL_APP_DIR/Ydisks闲鱼助手.app"
LEGACY_APP_PATH="/Applications/Ydisks Xianyu Helper.app"
LEGACY_LOCALIZED_APP_DIR="/Applications/Ydisks Xianyu Helper.localized"
LEGACY_LOCALIZED_APP_PATH="$LEGACY_LOCALIZED_APP_DIR/Ydisks Xianyu Helper.app"
CONSOLE_USER="$(stat -f '%Su' /dev/console)"
if [ "$CONSOLE_USER" != "root" ] && [ -n "$CONSOLE_USER" ]; then
UID_VALUE="$(id -u "$CONSOLE_USER")"
for label in \
"com.ydisks.xianyu-helper.server" \
"com.ydisks.xianyu-helper.tray" \
"com.christ.ydisks-xianyu-helper.server" \
"com.christ.ydisks-xianyu-helper.tray"
do
launchctl bootout "gui/$UID_VALUE/$label" >/dev/null 2>&1 || true
done
fi
for app_path in \
"$CANONICAL_APP_PATH" \
"$LEGACY_APP_PATH" \
"$LEGACY_LOCALIZED_APP_PATH"
do
if [ ! -d "$app_path" ]; then
continue
fi
existing_bundle_id="$(/usr/bin/plutil -extract CFBundleIdentifier raw -o - \
"$app_path/Contents/Info.plist" 2>/dev/null || true)"
if [ "$app_path" != "$CANONICAL_APP_PATH" ] || [ "$existing_bundle_id" != "$EXPECTED_BUNDLE_ID" ]; then
echo "清理旧 Bundle ID 的应用:${existing_bundle_id:-未知}($app_path)"
rm -rf "$app_path"
fi
done
# 只删除空的旧目录,不影响用户可能放在 Applications 中的其他内容。
rmdir "$LEGACY_LOCALIZED_APP_DIR/.localized" >/dev/null 2>&1 || true
rmdir "$LEGACY_LOCALIZED_APP_DIR" >/dev/null 2>&1 || true
+66
View File
@@ -0,0 +1,66 @@
#!/bin/sh
set -eu
PRODUCT_NAME="Ydisks闲鱼助手"
EXPECTED_BUNDLE_ID="com.ydisks.xianyu-helper"
CONSOLE_USER="$(/usr/bin/stat -f '%Su' /dev/console)"
if [ "${1:-}" != "--confirmed" ]; then
if ! /usr/bin/osascript <<'APPLESCRIPT'
tell application "System Events"
display dialog "卸载后将删除 Ydisks闲鱼助手、后台服务、配置、数据库、Chromium 和日志。此操作不可恢复。" buttons {"取消", "卸载"} default button "取消" cancel button "取消" with title "卸载 Ydisks闲鱼助手"
end tell
APPLESCRIPT
then
exit 0
fi
fi
if [ "$(id -u)" -ne 0 ]; then
exec /usr/bin/sudo "$0" --confirmed
fi
if [ "$CONSOLE_USER" != "root" ] && [ -n "$CONSOLE_USER" ]; then
UID_VALUE="$(/usr/bin/id -u "$CONSOLE_USER")"
HOME_DIR="$(/usr/bin/dscl . -read "/Users/$CONSOLE_USER" NFSHomeDirectory | /usr/bin/awk '{print $2}')"
for label in \
"com.ydisks.xianyu-helper.server" \
"com.ydisks.xianyu-helper.tray" \
"com.christ.ydisks-xianyu-helper.server" \
"com.christ.ydisks-xianyu-helper.tray"
do
/bin/launchctl bootout "gui/$UID_VALUE/$label" >/dev/null 2>&1 || true
done
# 处理用户手动启动、但没有被 LaunchAgent 管理的旧进程。
for process_path in \
"/Applications/Ydisks闲鱼助手/Ydisks闲鱼助手.app/Contents/Helpers/xianyu-server" \
"/Applications/Ydisks闲鱼助手/Ydisks闲鱼助手.app/Contents/MacOS/Ydisks闲鱼助手" \
"/Applications/Ydisks Xianyu Helper.app/Contents/Helpers/xianyu-server" \
"/Applications/Ydisks Xianyu Helper.app/Contents/MacOS/xianyu-tray" \
"/Applications/Ydisks Xianyu Helper.localized/Ydisks Xianyu Helper.app/Contents/Helpers/xianyu-server" \
"/Applications/Ydisks Xianyu Helper.localized/Ydisks Xianyu Helper.app/Contents/MacOS/xianyu-tray"
do
/usr/bin/pkill -TERM -f "$process_path" >/dev/null 2>&1 || true
done
/bin/rm -f \
"$HOME_DIR/Library/LaunchAgents/com.ydisks.xianyu-helper.server.plist" \
"$HOME_DIR/Library/LaunchAgents/com.ydisks.xianyu-helper.tray.plist" \
"$HOME_DIR/Library/LaunchAgents/com.christ.ydisks-xianyu-helper.server.plist" \
"$HOME_DIR/Library/LaunchAgents/com.christ.ydisks-xianyu-helper.tray.plist"
/bin/rm -rf \
"$HOME_DIR/Library/Application Support/YdisksXianyuHelper" \
"$HOME_DIR/Library/Logs/YdisksXianyuHelper"
fi
/bin/rm -rf \
"/Applications/Ydisks闲鱼助手" \
"/Applications/Ydisks Xianyu Helper.app" \
"/Applications/Ydisks Xianyu Helper.localized"
/usr/bin/pkgutil --forget "$EXPECTED_BUNDLE_ID" >/dev/null 2>&1 || true
/bin/rm -f /var/log/ydisks-xianyu-helper-install.log
echo "$PRODUCT_NAME 已卸载完成。"
+63
View File
@@ -0,0 +1,63 @@
#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}\icon.ico
SetupIconFile=..\..\icon\windows\icon.ico
Compression=lzma2
SolidCompression=yes
[Files]
Source: "..\..\dist\windows\xianyu-server.exe"; DestDir: "{app}"; Flags: ignoreversion
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
[Run]
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}\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;
+134
View File
@@ -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
}
}
}
+49
View File
@@ -0,0 +1,49 @@
param(
[Parameter(Mandatory = $true)]
[string]$PfxPath,
[Parameter(Mandatory = $true)]
[string[]]$Files
)
$ErrorActionPreference = 'Stop'
$pfxPassword = $env:WINDOWS_SIGNING_PFX_PASSWORD
$description = $env:WINDOWS_SIGNING_IDENTITY
if ([string]::IsNullOrWhiteSpace($pfxPassword)) {
throw 'WINDOWS_SIGNING_PFX_PASSWORD 未设置'
}
if ([string]::IsNullOrWhiteSpace($description)) {
throw 'WINDOWS_SIGNING_IDENTITY 未设置'
}
$signtool = Get-ChildItem -Path "${env:ProgramFiles(x86)}\Windows Kits\10\bin" -Filter 'signtool.exe' -Recurse |
Where-Object { $_.FullName -match '\\x64\\signtool\.exe$' } |
Sort-Object FullName |
Select-Object -Last 1
if ($null -eq $signtool) {
throw 'Windows SDK 中未找到 x64 signtool.exe'
}
foreach ($file in $Files) {
if (-not (Test-Path -LiteralPath $file -PathType Leaf)) {
throw "待签名文件不存在: $file"
}
& $signtool.FullName sign `
/f $PfxPath `
/p $pfxPassword `
/fd SHA256 `
/tr 'http://timestamp.acs.microsoft.com' `
/td SHA256 `
/d $description `
$file
if ($LASTEXITCODE -ne 0) {
throw "signtool 签名失败: $file"
}
$signature = Get-AuthenticodeSignature -FilePath $file
if ($null -eq $signature.SignerCertificate) {
throw "未找到 Authenticode 签名: $file"
}
}
+3 -3
View File
@@ -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
+42
View File
@@ -0,0 +1,42 @@
// Command iconconv wraps a PNG image in the Windows ICO container format.
// It is used to generate the checked-in installer icon from the product asset.
package main
import (
"encoding/binary"
"fmt"
"os"
)
func main() {
if len(os.Args) != 3 {
fmt.Fprintln(os.Stderr, "usage: iconconv input.png output.ico")
os.Exit(2)
}
data, err := os.ReadFile(os.Args[1])
if err != nil {
panic(err)
}
// A PNG-compressed 256x256 image is valid in an ICO file and keeps the
// alpha channel of the original product icon.
const headerSize = 6
const entrySize = 16
result := make([]byte, headerSize+entrySize+len(data))
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] = 0 // 0 means 256 in the ICO format.
entry[1] = 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)
if err := os.WriteFile(os.Args[2], result, 0644); err != nil {
panic(err)
}
}