Compare commits
46
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8215cc0e95 | ||
|
|
3f77cdba3d | ||
|
|
782bea1115 | ||
|
|
1833020caf | ||
|
|
36798dcced | ||
|
|
1a9be54355 | ||
|
|
17deffcfb5 | ||
|
|
e3a9404d0d | ||
|
|
59b1061ec5 | ||
|
|
ca00c159f0 | ||
|
|
96aa8f1ced | ||
|
|
1c8e2ab163 | ||
|
|
ac85ac8a0a | ||
|
|
65bcb8f15c | ||
|
|
7ec0b4a078 | ||
|
|
d36c357bab | ||
|
|
70e03a8523 | ||
|
|
542241d241 | ||
|
|
2df324647a | ||
|
|
94f4e070f6 | ||
|
|
6032dfed0f | ||
|
|
80baba46ff | ||
|
|
b7444e8090 | ||
|
|
fed5d582e7 | ||
|
|
0bafa50dbf | ||
|
|
3aabc3e8e4 | ||
|
|
1ac6912c7b | ||
|
|
d4e9717570 | ||
|
|
bfa72fd9b7 | ||
|
|
9cb50a229c | ||
|
|
13b57891fb | ||
|
|
8c5c305221 | ||
|
|
137a08489d | ||
|
|
07fea7d1e6 | ||
|
|
761d57f9bf | ||
|
|
3d715e916b | ||
|
|
07e91afc22 | ||
|
|
733a536031 | ||
|
|
c21a3a33dc | ||
|
|
86d659cf40 | ||
|
|
f0accce14a | ||
|
|
430fbc0767 | ||
|
|
bac5aa0c4f | ||
|
|
07b5be626b | ||
|
|
a99ea5c20d | ||
|
|
1204655170 |
No files matched your search
@@ -0,0 +1 @@
|
||||
|
||||
@@ -14,3 +14,6 @@ init-admin
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
cover.out
|
||||
!/.docker/
|
||||
!/.docker/playwright-runtime/
|
||||
!/.docker/playwright-runtime/**
|
||||
+1
-1
@@ -13,7 +13,7 @@ DATABASE_URL=postgres://xianyu:请替换为URL编码后的数据库密码@postgr
|
||||
XIANYU_IMAGE=ghcr.io/christ9038/ydisks-xianyu-helper:latest
|
||||
XIANYU_DATA_KEY=请替换为稳定且足够长的随机密钥
|
||||
XIANYU_BIND_ADDRESS=0.0.0.0
|
||||
XIANYU_HTTP_PORT=8080
|
||||
XIANYU_HTTP_PORT=59188
|
||||
XIANYU_UPLOAD_DIR=/app/data/uploads
|
||||
TZ=Asia/Shanghai
|
||||
LOG_LEVEL=info
|
||||
|
||||
@@ -0,0 +1,756 @@
|
||||
name: 构建桌面端安装包
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- dev
|
||||
workflow_dispatch:
|
||||
workflow_call:
|
||||
inputs:
|
||||
app_version:
|
||||
description: 正式发布版本号(不含 v)
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: desktop-cd-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
prepare:
|
||||
name: 准备发布版本
|
||||
runs-on: ubuntu-24.04
|
||||
outputs:
|
||||
app_version: ${{ steps.version.outputs.app_version }}
|
||||
build_version: ${{ steps.version.outputs.build_version }}
|
||||
build_time: ${{ steps.version.outputs.build_time }}
|
||||
steps:
|
||||
- name: 解析并校验版本号
|
||||
id: version
|
||||
shell: bash
|
||||
run: |
|
||||
set -Eeuo pipefail
|
||||
if [ -n "${{ inputs.app_version }}" ]; then
|
||||
app_version="${{ inputs.app_version }}"
|
||||
build_version="$app_version"
|
||||
else
|
||||
app_version="0.0.${GITHUB_RUN_NUMBER}"
|
||||
build_version="${GITHUB_REF_NAME}-${GITHUB_SHA::12}"
|
||||
fi
|
||||
if [[ ! "$app_version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "安装包版本必须符合 1.2.3 格式:$app_version" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "app_version=$app_version" >> "$GITHUB_OUTPUT"
|
||||
echo "build_version=$build_version" >> "$GITHUB_OUTPUT"
|
||||
echo "build_time=$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
linux:
|
||||
name: Linux 安装包 (${{ matrix.arch }})
|
||||
needs: prepare
|
||||
runs-on: ${{ matrix.runner }}
|
||||
env:
|
||||
APP_VERSION: ${{ needs.prepare.outputs.app_version }}
|
||||
BUILD_VERSION: ${{ needs.prepare.outputs.build_version }}
|
||||
BUILD_TIME: ${{ needs.prepare.outputs.build_time }}
|
||||
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: 24
|
||||
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"
|
||||
version_ldflags="-s -w -X xianyu-go/internal/version.Version=$BUILD_VERSION -X xianyu-go/internal/version.Commit=$GITHUB_SHA -X xianyu-go/internal/version.BuildTime=$BUILD_TIME"
|
||||
go build -trimpath -ldflags="$version_ldflags" -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/restore@v5
|
||||
with:
|
||||
path: dist/ydisks-xianyu-helper-linux-${{ matrix.arch }}/playwright-runtime
|
||||
key: ydisks-playwright-runtime-v6-linux-${{ matrix.arch }}-${{ matrix.playwright_platform }}-${{ hashFiles('go.mod', 'go.sum', 'cmd/browser-install/**') }}
|
||||
|
||||
- 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="$PWD/$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="$PWD/$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 Chromium runtime 缓存
|
||||
if: steps.cache-linux-playwright.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/save@v5
|
||||
with:
|
||||
path: dist/ydisks-xianyu-helper-linux-${{ matrix.arch }}/playwright-runtime
|
||||
key: ${{ steps.cache-linux-playwright.outputs.cache-primary-key }}
|
||||
|
||||
- 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 安装包
|
||||
needs: prepare
|
||||
runs-on: windows-latest
|
||||
env:
|
||||
APP_VERSION: ${{ needs.prepare.outputs.app_version }}
|
||||
BUILD_VERSION: ${{ needs.prepare.outputs.build_version }}
|
||||
BUILD_TIME: ${{ needs.prepare.outputs.build_time }}
|
||||
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: 24
|
||||
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
|
||||
$serviceScript = (Resolve-Path 'packaging/windows/service-control.ps1').Path
|
||||
$tokens = $null
|
||||
$parseErrors = $null
|
||||
[void][System.Management.Automation.Language.Parser]::ParseFile(
|
||||
$serviceScript,
|
||||
[ref]$tokens,
|
||||
[ref]$parseErrors
|
||||
)
|
||||
if ($parseErrors.Count -gt 0) {
|
||||
$parseErrors | ForEach-Object { Write-Error $_.Message }
|
||||
throw 'Windows 服务安装脚本在 PowerShell 7 下语法检查失败'
|
||||
}
|
||||
|
||||
& "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" `
|
||||
-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass `
|
||||
-File $serviceScript -Mode stop -ServiceName "YdisksSyntaxCheck-$PID"
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Windows 服务安装脚本在 Windows PowerShell 5.1 下检查失败,错误码: $LASTEXITCODE"
|
||||
}
|
||||
|
||||
- name: 编译 Windows 桌面程序
|
||||
shell: pwsh
|
||||
run: |
|
||||
& packaging/windows/build-resources.ps1
|
||||
New-Item -ItemType Directory -Force -Path dist/windows | Out-Null
|
||||
$versionLdflags = "-s -w -X xianyu-go/internal/version.Version=$env:BUILD_VERSION -X xianyu-go/internal/version.Commit=$env:GITHUB_SHA -X xianyu-go/internal/version.BuildTime=$env:BUILD_TIME"
|
||||
go build -trimpath -ldflags $versionLdflags -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/restore@v5
|
||||
with:
|
||||
path: dist/windows/playwright-runtime/amd64
|
||||
key: ydisks-playwright-runtime-v6-windows-amd64-${{ hashFiles('go.mod', 'go.sum', 'cmd/browser-install/**') }}
|
||||
|
||||
- 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
|
||||
run: |
|
||||
$serviceName = 'YdisksXianyuHelper'
|
||||
$workDir = Join-Path $env:RUNNER_TEMP $serviceName
|
||||
$runtimeRoot = (Resolve-Path 'dist/windows/playwright-runtime/amd64').Path
|
||||
$serviceScript = (Resolve-Path 'packaging/windows/service-control.ps1').Path
|
||||
$serverPath = (Resolve-Path 'dist/windows/xianyu-server.exe').Path
|
||||
try {
|
||||
foreach ($registerAttempt in 1..2) {
|
||||
& "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" `
|
||||
-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass `
|
||||
-File $serviceScript -Mode register -ServiceName $serviceName `
|
||||
-ExePath $serverPath -WorkDir $workDir -RuntimeRoot $runtimeRoot
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Windows 服务第 $registerAttempt 次注册失败,错误码: $LASTEXITCODE"
|
||||
}
|
||||
}
|
||||
& "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" `
|
||||
-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass `
|
||||
-File $serviceScript -Mode start -ServiceName $serviceName
|
||||
if ($LASTEXITCODE -ne 0) { throw "Windows 服务启动失败,错误码: $LASTEXITCODE" }
|
||||
|
||||
$service = Get-Service -Name $serviceName -ErrorAction Stop
|
||||
$serviceStatus = $service.Status
|
||||
$service.Dispose()
|
||||
if ($serviceStatus -ne [System.ServiceProcess.ServiceControllerStatus]::Running) {
|
||||
throw "Windows 服务未进入运行状态: $serviceStatus"
|
||||
}
|
||||
|
||||
$serviceConfig = Get-CimInstance -ClassName Win32_Service -Filter "Name='$serviceName'" -ErrorAction Stop
|
||||
if ($null -eq $serviceConfig) { throw 'Windows 服务注册后无法读取配置' }
|
||||
# Win32_Service.PathName 可能会省略不含空格路径两侧的引号,比较前统一去掉引号。
|
||||
$actualServiceCommand = $serviceConfig.PathName.Replace('"', '')
|
||||
$requiredServiceArguments = @(
|
||||
$serverPath,
|
||||
'-service',
|
||||
"-workdir $workDir",
|
||||
"-playwright-runtime-root $runtimeRoot"
|
||||
)
|
||||
$invalidServiceArgument = $requiredServiceArguments |
|
||||
Where-Object {
|
||||
$actualServiceCommand.IndexOf($_, [StringComparison]::OrdinalIgnoreCase) -lt 0
|
||||
} |
|
||||
Select-Object -First 1
|
||||
if ($null -ne $invalidServiceArgument) {
|
||||
throw "Windows 服务命令行不正确: $($serviceConfig.PathName)"
|
||||
}
|
||||
$delayedStart = Get-ItemPropertyValue `
|
||||
-LiteralPath "Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\$serviceName" `
|
||||
-Name DelayedAutostart -ErrorAction Stop
|
||||
if ($delayedStart -ne 1) { throw "Windows 服务未配置延迟自动启动: $delayedStart" }
|
||||
$sddl = (& "$env:SystemRoot\System32\sc.exe" sdshow $serviceName 2>&1) -join ''
|
||||
if ($LASTEXITCODE -ne 0 -or -not $sddl.Contains('(A;;LCRPWP;;;IU)')) {
|
||||
throw "Windows 服务未授予交互用户启停权限: $sddl"
|
||||
}
|
||||
|
||||
$health = $null
|
||||
$deadline = [DateTime]::UtcNow.AddSeconds(60)
|
||||
while ([DateTime]::UtcNow -lt $deadline -and $null -eq $health) {
|
||||
try {
|
||||
$health = Invoke-RestMethod -Uri 'http://127.0.0.1:59188/health' -TimeoutSec 2
|
||||
} catch {
|
||||
Start-Sleep -Seconds 1
|
||||
}
|
||||
}
|
||||
if ($null -eq $health -or $health.status -ne 'ok' -or $health.database -ne 'ok') {
|
||||
throw "Windows 服务健康检查失败: $($health | ConvertTo-Json -Compress)"
|
||||
}
|
||||
} catch {
|
||||
$serverLog = Join-Path $workDir 'logs\server.log'
|
||||
if (Test-Path -LiteralPath $serverLog) {
|
||||
Get-Content -LiteralPath $serverLog -Tail 200
|
||||
}
|
||||
throw
|
||||
} finally {
|
||||
& "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" `
|
||||
-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass `
|
||||
-File $serviceScript -Mode uninstall -ServiceName $serviceName
|
||||
if ($LASTEXITCODE -ne 0) { throw "Windows 服务清理失败,错误码: $LASTEXITCODE" }
|
||||
if ($null -ne (Get-Service -Name $serviceName -ErrorAction SilentlyContinue)) {
|
||||
throw 'Windows 服务卸载后仍然存在'
|
||||
}
|
||||
}
|
||||
|
||||
- name: 保存 Windows Chromium runtime 缓存
|
||||
if: steps.cache-windows-playwright.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/save@v5
|
||||
with:
|
||||
path: dist/windows/playwright-runtime/amd64
|
||||
key: ${{ steps.cache-windows-playwright.outputs.cache-primary-key }}
|
||||
|
||||
- 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: |
|
||||
$shortDrive = 'R:'
|
||||
if (Test-Path -LiteralPath "$shortDrive\") {
|
||||
throw "短路径盘符已被占用: $shortDrive"
|
||||
}
|
||||
& "$env:SystemRoot\System32\subst.exe" $shortDrive $env:GITHUB_WORKSPACE
|
||||
if ($LASTEXITCODE -ne 0 -or -not (Test-Path -LiteralPath "$shortDrive\")) {
|
||||
throw "无法创建 Windows 安装器短路径盘符: $shortDrive"
|
||||
}
|
||||
$locationPushed = $false
|
||||
try {
|
||||
Push-Location "$shortDrive\"
|
||||
$locationPushed = $true
|
||||
$requiredSources = @(
|
||||
'dist/windows/xianyu-server.exe',
|
||||
'dist/windows/xianyu-tray.exe',
|
||||
'dist/windows/playwright-runtime/amd64',
|
||||
'icon/windows/icon.ico',
|
||||
'packaging/windows/languages/ChineseSimplified.isl',
|
||||
'packaging/windows/languages/ChineseTraditional.isl',
|
||||
'packaging/windows/service-control.ps1'
|
||||
)
|
||||
foreach ($source in $requiredSources) {
|
||||
if (-not (Test-Path -LiteralPath $source)) {
|
||||
throw "Windows 安装器源文件或目录不存在: $source"
|
||||
}
|
||||
}
|
||||
$runtimeFiles = Get-ChildItem -LiteralPath 'dist/windows/playwright-runtime/amd64' -Recurse -File
|
||||
if ($null -eq ($runtimeFiles | Select-Object -First 1)) {
|
||||
throw 'Windows 安装器 Playwright runtime 为空'
|
||||
}
|
||||
$longestRuntimeFile = $runtimeFiles |
|
||||
Sort-Object { $_.FullName.Length } -Descending |
|
||||
Select-Object -First 1
|
||||
Write-Host "Windows runtime 最长源路径长度: $($longestRuntimeFile.FullName.Length)"
|
||||
Write-Host "Windows runtime 最长源路径: $($longestRuntimeFile.FullName)"
|
||||
|
||||
$compiler = 'C:\Program Files (x86)\Inno Setup 6\ISCC.exe'
|
||||
$scriptPath = (Resolve-Path 'packaging/windows/installer.iss').Path
|
||||
$outputDir = (Resolve-Path 'dist/windows').Path
|
||||
& $compiler /Qp "/O$outputDir" $scriptPath
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Inno Setup 编译失败,错误码: $LASTEXITCODE"
|
||||
}
|
||||
$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 }
|
||||
} finally {
|
||||
if ($locationPushed) {
|
||||
Pop-Location
|
||||
}
|
||||
& "$env:SystemRoot\System32\subst.exe" $shortDrive /D | Out-Null
|
||||
}
|
||||
|
||||
- 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: 使用安装器验证服务安装与卸载
|
||||
shell: pwsh
|
||||
run: |
|
||||
$serviceName = 'YdisksXianyuHelper'
|
||||
$installer = (Resolve-Path 'dist/windows/Ydisks-Xianyu-Helper-Setup.exe').Path
|
||||
$installLog = Join-Path $env:RUNNER_TEMP 'ydisks-windows-installer.log'
|
||||
$installDir = Join-Path $env:ProgramFiles 'Ydisks Xianyu Helper'
|
||||
$uninstaller = Join-Path $installDir 'unins000.exe'
|
||||
try {
|
||||
$installerProcess = Start-Process -FilePath $installer `
|
||||
-ArgumentList @('/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART', "/LOG=$installLog") `
|
||||
-Wait -PassThru
|
||||
$installerExitCode = $installerProcess.ExitCode
|
||||
if ($installerExitCode -ne 0) {
|
||||
if (Test-Path -LiteralPath $installLog) {
|
||||
Get-Content -LiteralPath $installLog -Tail 200
|
||||
}
|
||||
throw "Windows 安装器执行失败,错误码: $installerExitCode"
|
||||
}
|
||||
|
||||
$service = Get-Service -Name $serviceName -ErrorAction Stop
|
||||
$serviceStatus = $service.Status
|
||||
$service.Dispose()
|
||||
if ($serviceStatus -ne [System.ServiceProcess.ServiceControllerStatus]::Running) {
|
||||
throw "安装器未启动 Windows 服务: $serviceStatus"
|
||||
}
|
||||
|
||||
$expectedServer = Join-Path $installDir 'xianyu-server.exe'
|
||||
$expectedRuntime = Join-Path $installDir 'playwright-runtime'
|
||||
$serviceConfig = Get-CimInstance -ClassName Win32_Service -Filter "Name='$serviceName'" -ErrorAction Stop
|
||||
$actualServiceCommand = if ($null -eq $serviceConfig) { '' } else { $serviceConfig.PathName.Replace('"', '') }
|
||||
$requiredServiceArguments = @(
|
||||
$expectedServer,
|
||||
'-service',
|
||||
"-playwright-runtime-root $expectedRuntime"
|
||||
)
|
||||
$invalidServiceArgument = $requiredServiceArguments |
|
||||
Where-Object {
|
||||
$actualServiceCommand.IndexOf($_, [StringComparison]::OrdinalIgnoreCase) -lt 0
|
||||
} |
|
||||
Select-Object -First 1
|
||||
if ($null -ne $invalidServiceArgument) {
|
||||
throw "安装器注册的服务命令行不正确: $($serviceConfig.PathName)"
|
||||
}
|
||||
|
||||
$health = $null
|
||||
$deadline = [DateTime]::UtcNow.AddSeconds(60)
|
||||
while ([DateTime]::UtcNow -lt $deadline -and $null -eq $health) {
|
||||
try {
|
||||
$health = Invoke-RestMethod -Uri 'http://127.0.0.1:59188/health' -TimeoutSec 2
|
||||
} catch {
|
||||
Start-Sleep -Seconds 1
|
||||
}
|
||||
}
|
||||
if ($null -eq $health -or $health.status -ne 'ok' -or $health.database -ne 'ok') {
|
||||
throw "安装器服务健康检查失败: $($health | ConvertTo-Json -Compress)"
|
||||
}
|
||||
if (-not (Test-Path -LiteralPath $uninstaller -PathType Leaf)) {
|
||||
throw "Windows 卸载器不存在: $uninstaller"
|
||||
}
|
||||
$expectedTray = Join-Path $installDir 'xianyu-tray.exe'
|
||||
$startMenuRoots = @(
|
||||
(Join-Path $env:ProgramData 'Microsoft\Windows\Start Menu\Programs'),
|
||||
(Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs')
|
||||
)
|
||||
$startMenuShortcut = $startMenuRoots |
|
||||
Where-Object { Test-Path -LiteralPath $_ -PathType Container } |
|
||||
ForEach-Object {
|
||||
Get-ChildItem -LiteralPath $_ -Filter '*.lnk' -Recurse -File -ErrorAction SilentlyContinue
|
||||
} |
|
||||
Where-Object {
|
||||
$shortcutShell = New-Object -ComObject WScript.Shell
|
||||
$shortcutTarget = $shortcutShell.CreateShortcut($_.FullName).TargetPath
|
||||
[StringComparer]::OrdinalIgnoreCase.Equals($shortcutTarget, $expectedTray)
|
||||
} |
|
||||
Select-Object -First 1
|
||||
if ($null -eq $startMenuShortcut) {
|
||||
throw '安装器未创建开始菜单快捷方式'
|
||||
}
|
||||
} catch {
|
||||
if (Test-Path -LiteralPath $installLog) {
|
||||
Get-Content -LiteralPath $installLog -Tail 200
|
||||
}
|
||||
$serverLog = Join-Path $env:ProgramData 'YdisksXianyuHelper\logs\server.log'
|
||||
if (Test-Path -LiteralPath $serverLog) {
|
||||
Get-Content -LiteralPath $serverLog -Tail 200
|
||||
}
|
||||
throw
|
||||
} finally {
|
||||
if (Test-Path -LiteralPath $uninstaller -PathType Leaf) {
|
||||
$uninstallerProcess = Start-Process -FilePath $uninstaller `
|
||||
-ArgumentList @('/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART') `
|
||||
-Wait -PassThru
|
||||
if ($uninstallerProcess.ExitCode -ne 0) {
|
||||
throw "Windows 卸载器执行失败,错误码: $($uninstallerProcess.ExitCode)"
|
||||
}
|
||||
} elseif ($null -ne (Get-CimInstance -ClassName Win32_Service -Filter "Name='$serviceName'" -ErrorAction SilentlyContinue)) {
|
||||
& "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" `
|
||||
-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass `
|
||||
-File (Resolve-Path 'packaging/windows/service-control.ps1') `
|
||||
-Mode uninstall -ServiceName $serviceName
|
||||
if ($LASTEXITCODE -ne 0) { throw "Windows 服务兜底清理失败,错误码: $LASTEXITCODE" }
|
||||
}
|
||||
if ($null -ne (Get-CimInstance -ClassName Win32_Service -Filter "Name='$serviceName'" -ErrorAction SilentlyContinue)) {
|
||||
throw 'Windows 安装器卸载后服务仍然存在'
|
||||
}
|
||||
}
|
||||
|
||||
- name: 准备唯一 Windows 构建产物
|
||||
shell: pwsh
|
||||
run: |
|
||||
$artifactDir = 'dist/windows-artifact'
|
||||
New-Item -ItemType Directory -Force -Path $artifactDir | Out-Null
|
||||
Copy-Item -LiteralPath 'dist/windows/Ydisks-Xianyu-Helper-Setup.exe' -Destination $artifactDir
|
||||
$artifactFiles = @(Get-ChildItem -LiteralPath $artifactDir -Recurse -File)
|
||||
if ($artifactFiles.Count -ne 1 -or $artifactFiles[0].Name -ne 'Ydisks-Xianyu-Helper-Setup.exe') {
|
||||
throw "Windows 构建产物必须且只能包含安装器: $($artifactFiles.FullName -join ', ')"
|
||||
}
|
||||
|
||||
- name: 上传 Windows 安装包
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: ydisks-xianyu-helper-windows-${{ env.APP_VERSION }}
|
||||
path: dist/windows-artifact/Ydisks-Xianyu-Helper-Setup.exe
|
||||
if-no-files-found: error
|
||||
|
||||
macos:
|
||||
name: macOS 安装包
|
||||
needs: prepare
|
||||
runs-on: macos-14
|
||||
env:
|
||||
APP_VERSION: ${{ needs.prepare.outputs.app_version }}
|
||||
BUILD_VERSION: ${{ needs.prepare.outputs.build_version }}
|
||||
BUILD_TIME: ${{ needs.prepare.outputs.build_time }}
|
||||
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: 24
|
||||
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
|
||||
version_ldflags="-s -w -X xianyu-go/internal/version.Version=$BUILD_VERSION -X xianyu-go/internal/version.Commit=$GITHUB_SHA -X xianyu-go/internal/version.BuildTime=$BUILD_TIME"
|
||||
for arch in arm64 amd64; do
|
||||
GOOS=darwin GOARCH="$arch" CGO_ENABLED=1 go build -trimpath -ldflags="$version_ldflags" -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-mac14-universal-${{ hashFiles('go.mod', 'go.sum', 'cmd/browser-install/**') }}
|
||||
|
||||
- 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
|
||||
run: |
|
||||
set -Eeuo pipefail
|
||||
for runtime_arch in arm64 amd64; do
|
||||
runtime_dir="dist/macos/playwright-runtime/$runtime_arch"
|
||||
node_path="$runtime_dir/playwright-driver/node"
|
||||
spec_path="$PWD/$runtime_dir/playwright-driver/package/browsers.json"
|
||||
test -x "$node_path"
|
||||
test -f "$runtime_dir/playwright-driver/package/cli.js"
|
||||
test -f "$spec_path"
|
||||
chromium_revision="$(RUNTIME_SPEC="$spec_path" node -e 'const b=require(process.env.RUNTIME_SPEC).browsers; console.log(b.find(x=>x.name==="chromium").revision)')"
|
||||
headless_revision="$(RUNTIME_SPEC="$spec_path" 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_path="$(find "$runtime_dir/playwright-browsers/chromium-$chromium_revision" -type f -path '*/Contents/MacOS/Google Chrome for Testing' -print -quit)"
|
||||
headless_path="$(find "$runtime_dir/playwright-browsers/chromium_headless_shell-$headless_revision" -type f -name chrome-headless-shell -print -quit)"
|
||||
test -n "$chromium_path"
|
||||
test -n "$headless_path"
|
||||
node_type="$(file -b "$node_path")"
|
||||
chromium_type="$(file -b "$chromium_path")"
|
||||
headless_type="$(file -b "$headless_path")"
|
||||
case "$runtime_arch:$node_type:$chromium_type:$headless_type" in
|
||||
arm64:*arm64*:*arm64*:*arm64*) ;;
|
||||
amd64:*x86_64*:*x86_64*:*x86_64*) ;;
|
||||
*) echo "macOS Playwright runtime 架构错误:$runtime_arch / $node_type / $chromium_type / $headless_type" >&2; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
- 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
|
||||
@@ -4,7 +4,14 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- dev
|
||||
workflow_dispatch:
|
||||
workflow_call:
|
||||
inputs:
|
||||
app_version:
|
||||
description: 正式发布版本号(不含 v)
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -15,21 +22,262 @@ concurrency:
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
name: 发布多架构镜像
|
||||
runs-on: ubuntu-latest
|
||||
verify:
|
||||
name: Docker 发布测试门禁
|
||||
runs-on: ubuntu-24.04
|
||||
outputs:
|
||||
app_version: ${{ steps.version.outputs.app_version }}
|
||||
build_time: ${{ steps.version.outputs.build_time }}
|
||||
steps:
|
||||
- name: 准备构建版本
|
||||
id: version
|
||||
shell: bash
|
||||
run: |
|
||||
set -Eeuo pipefail
|
||||
if [ -n "${{ inputs.app_version }}" ]; then
|
||||
app_version="${{ inputs.app_version }}"
|
||||
else
|
||||
app_version="${GITHUB_REF_NAME}-${GITHUB_SHA::12}"
|
||||
fi
|
||||
if [ -n "${{ inputs.app_version }}" ] && [[ ! "$app_version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "正式版本必须符合 1.2.3 格式:$app_version" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "app_version=$app_version" >> "$GITHUB_OUTPUT"
|
||||
echo "build_time=$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$GITHUB_OUTPUT"
|
||||
- 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: 24
|
||||
cache: npm
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: 验证前端
|
||||
shell: bash
|
||||
run: |
|
||||
set -Eeuo pipefail
|
||||
npm ci --prefix frontend
|
||||
npm run typecheck --prefix frontend
|
||||
npm test --prefix frontend
|
||||
npm run build --prefix frontend
|
||||
|
||||
- name: 验证 Go 服务
|
||||
run: |
|
||||
go vet ./...
|
||||
go test ./...
|
||||
|
||||
build:
|
||||
name: 构建镜像 (${{ matrix.arch }})
|
||||
needs: verify
|
||||
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: 配置 Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
- name: 恢复 Docker Chromium runtime 缓存
|
||||
id: cache-docker-playwright
|
||||
uses: actions/cache/restore@v5
|
||||
with:
|
||||
path: .docker/playwright-runtime/${{ matrix.arch }}
|
||||
key: ydisks-playwright-runtime-v6-docker-${{ matrix.arch }}-${{ matrix.playwright_platform }}-${{ hashFiles('go.mod', 'go.sum', 'cmd/browser-install/**') }}
|
||||
|
||||
- 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="$PWD/$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="$PWD/$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 Chromium runtime 缓存
|
||||
if: steps.cache-docker-playwright.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/save@v5
|
||||
with:
|
||||
path: .docker/playwright-runtime/${{ matrix.arch }}
|
||||
key: ${{ steps.cache-docker-playwright.outputs.cache-primary-key }}
|
||||
|
||||
- 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 }}
|
||||
build-args: |
|
||||
APP_VERSION=${{ needs.verify.outputs.app_version }}
|
||||
VCS_REF=${{ github.sha }}
|
||||
BUILD_TIME=${{ needs.verify.outputs.build_time }}
|
||||
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: 验证待发布镜像中的 Chromium 与服务
|
||||
shell: bash
|
||||
env:
|
||||
IMAGE_NAME: ${{ steps.image.outputs.name }}
|
||||
IMAGE_DIGEST: ${{ steps.build.outputs.digest }}
|
||||
run: |
|
||||
set -Eeuo pipefail
|
||||
image_ref="$IMAGE_NAME@$IMAGE_DIGEST"
|
||||
docker pull "$image_ref"
|
||||
|
||||
docker run --rm --entrypoint sh "$image_ref" -ec '
|
||||
chromium_path="$(find /ms-playwright/chromium-* -type f \
|
||||
-name chrome -perm -111 -print -quit)"
|
||||
test -n "$chromium_path"
|
||||
timeout 45 "$chromium_path" \
|
||||
--headless --no-sandbox --disable-gpu --disable-dev-shm-usage \
|
||||
--dump-dom about:blank | grep -q "<html"
|
||||
'
|
||||
|
||||
container_id="$(docker run -d -p 127.0.0.1::59188 "$image_ref")"
|
||||
cleanup() {
|
||||
docker logs "$container_id" || true
|
||||
docker rm -f "$container_id" >/dev/null 2>&1 || true
|
||||
}
|
||||
trap cleanup EXIT
|
||||
host_port="$(docker port "$container_id" 59188/tcp | sed -n 's/.*://p' | head -n 1)"
|
||||
test -n "$host_port"
|
||||
for attempt in $(seq 1 60); do
|
||||
if health="$(curl --fail --silent --show-error "http://127.0.0.1:$host_port/health" 2>/dev/null)"; then
|
||||
printf '%s' "$health" | grep -q '"status":"ok"'
|
||||
printf '%s' "$health" | grep -q '"database":"ok"'
|
||||
exit 0
|
||||
fi
|
||||
if ! docker inspect -f '{{.State.Running}}' "$container_id" | grep -q true; then
|
||||
echo '待发布镜像中的服务提前退出。' >&2
|
||||
exit 1
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
echo '待发布镜像未能在 60 秒内通过健康检查。' >&2
|
||||
exit 1
|
||||
|
||||
- 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: 30
|
||||
|
||||
publish:
|
||||
name: 合并多架构镜像
|
||||
if: inputs.app_version == ''
|
||||
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 +290,42 @@ 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=latest,enable=${{ github.ref == 'refs/heads/main' }}
|
||||
type=raw,value=main,enable=${{ github.ref == 'refs/heads/main' }}
|
||||
type=raw,value=dev,enable=${{ github.ref == 'refs/heads/dev' }}
|
||||
|
||||
- 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"
|
||||
@@ -0,0 +1,178 @@
|
||||
name: 发布正式版本
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*.*.*'
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
packages: write
|
||||
|
||||
concurrency:
|
||||
group: release-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
prepare:
|
||||
name: 校验正式版本
|
||||
runs-on: ubuntu-24.04
|
||||
outputs:
|
||||
app_version: ${{ steps.version.outputs.app_version }}
|
||||
steps:
|
||||
- name: 检出完整 Git 历史
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: 校验标签、来源与版本顺序
|
||||
id: version
|
||||
shell: bash
|
||||
run: |
|
||||
set -Eeuo pipefail
|
||||
if [[ ! "$GITHUB_REF_NAME" =~ ^v([0-9]+\.[0-9]+\.[0-9]+)$ ]]; then
|
||||
echo "正式版本标签必须符合 v1.2.3 格式:$GITHUB_REF_NAME" >&2
|
||||
exit 1
|
||||
fi
|
||||
git fetch origin main --no-tags
|
||||
if ! git merge-base --is-ancestor "$GITHUB_SHA" origin/main; then
|
||||
echo "正式版本标签必须指向 main 已包含的提交。" >&2
|
||||
exit 1
|
||||
fi
|
||||
newest_tag="$(git tag --list | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | sort -V | tail -n 1)"
|
||||
if [ "$newest_tag" != "$GITHUB_REF_NAME" ]; then
|
||||
echo "拒绝用旧版本 $GITHUB_REF_NAME 覆盖 latest;当前最高版本是 $newest_tag。" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "app_version=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
desktop:
|
||||
name: 构建桌面端安装包
|
||||
needs: prepare
|
||||
uses: ./.github/workflows/desktop-cd.yml
|
||||
with:
|
||||
app_version: ${{ needs.prepare.outputs.app_version }}
|
||||
secrets: inherit
|
||||
|
||||
docker:
|
||||
name: 构建 Docker 镜像
|
||||
needs: prepare
|
||||
uses: ./.github/workflows/docker-publish.yml
|
||||
with:
|
||||
app_version: ${{ needs.prepare.outputs.app_version }}
|
||||
secrets: inherit
|
||||
|
||||
publish:
|
||||
name: 审批并发布正式版本
|
||||
needs:
|
||||
- prepare
|
||||
- desktop
|
||||
- docker
|
||||
runs-on: ubuntu-24.04
|
||||
environment:
|
||||
name: production-release
|
||||
steps:
|
||||
- name: 检出正式版本代码
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: 下载全部构建产物
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
pattern: ydisks-*
|
||||
path: dist/artifacts
|
||||
merge-multiple: true
|
||||
|
||||
- name: 校验桌面产物并生成校验和
|
||||
shell: bash
|
||||
env:
|
||||
APP_VERSION: ${{ needs.prepare.outputs.app_version }}
|
||||
run: |
|
||||
set -Eeuo pipefail
|
||||
mkdir -p dist/release dist/digests
|
||||
|
||||
echo "下载后的构建产物:"
|
||||
find dist/artifacts -maxdepth 2 -type f -printf '%P\n' | sort
|
||||
|
||||
expected_release_files=(
|
||||
"ydisks-xianyu-helper-linux-amd64-$APP_VERSION.tar.gz"
|
||||
"ydisks-xianyu-helper-linux-arm64-$APP_VERSION.tar.gz"
|
||||
"Ydisks-Xianyu-Helper-Setup.exe"
|
||||
"Ydisks-Xianyu-Helper-$APP_VERSION-arm64.pkg"
|
||||
"Ydisks-Xianyu-Helper-$APP_VERSION-amd64.pkg"
|
||||
)
|
||||
for release_file in "${expected_release_files[@]}"; do
|
||||
source_file="dist/artifacts/$release_file"
|
||||
if [ ! -f "$source_file" ]; then
|
||||
echo "缺少正式发布产物:$release_file" >&2
|
||||
exit 1
|
||||
fi
|
||||
cp -- "$source_file" dist/release/
|
||||
done
|
||||
|
||||
digest_count=0
|
||||
while IFS= read -r artifact_file; do
|
||||
artifact_name="$(basename "$artifact_file")"
|
||||
if [[ "$artifact_name" =~ ^[0-9a-f]{64}$ ]]; then
|
||||
cp -- "$artifact_file" dist/digests/
|
||||
digest_count=$((digest_count + 1))
|
||||
fi
|
||||
done < <(find dist/artifacts -maxdepth 2 -type f -print)
|
||||
if [ "$digest_count" -ne 2 ]; then
|
||||
echo "Docker 镜像摘要数量错误:预期 2 个,实际 $digest_count 个。" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "准备发布的桌面产物:"
|
||||
find dist/release -maxdepth 1 -type f -printf '%f\n' | sort
|
||||
echo "准备发布的 Docker 摘要:"
|
||||
find dist/digests -maxdepth 1 -type f -printf '%f\n' | sort
|
||||
(cd dist/release && sha256sum * > SHA256SUMS)
|
||||
|
||||
- name: 配置 Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: 登录 GitHub Container Registry
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: 发布正式 Docker manifest
|
||||
shell: bash
|
||||
env:
|
||||
APP_VERSION: ${{ needs.prepare.outputs.app_version }}
|
||||
run: |
|
||||
set -Eeuo pipefail
|
||||
image_name="ghcr.io/${GITHUB_REPOSITORY,,}"
|
||||
minor_version="${APP_VERSION%.*}"
|
||||
digest_args=()
|
||||
while IFS= read -r digest_file; do
|
||||
digest_args+=("$image_name@sha256:$(basename "$digest_file")")
|
||||
done < <(find dist/digests -maxdepth 1 -type f -print | sort)
|
||||
docker buildx imagetools create \
|
||||
--tag "$image_name:$GITHUB_REF_NAME" \
|
||||
--tag "$image_name:$APP_VERSION" \
|
||||
--tag "$image_name:$minor_version" \
|
||||
--tag "$image_name:latest" \
|
||||
--tag "$image_name:sha-$GITHUB_SHA" \
|
||||
"${digest_args[@]}"
|
||||
docker buildx imagetools inspect "$image_name:$GITHUB_REF_NAME"
|
||||
docker buildx imagetools inspect "$image_name:latest"
|
||||
|
||||
- name: 创建或更新 GitHub Release
|
||||
shell: bash
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
APP_VERSION: ${{ needs.prepare.outputs.app_version }}
|
||||
run: |
|
||||
set -Eeuo pipefail
|
||||
mapfile -t release_files < <(find dist/release -maxdepth 1 -type f -print | sort)
|
||||
if gh release view "$GITHUB_REF_NAME" >/dev/null 2>&1; then
|
||||
gh release upload "$GITHUB_REF_NAME" "${release_files[@]}" --clobber
|
||||
else
|
||||
gh release create "$GITHUB_REF_NAME" "${release_files[@]}" \
|
||||
--verify-tag \
|
||||
--generate-notes \
|
||||
--title "Ydisks 闲鱼助手 $APP_VERSION"
|
||||
fi
|
||||
@@ -19,7 +19,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: 检出主分支文档
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: main
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
*.test
|
||||
!/Dockerfile.test
|
||||
*.out
|
||||
/cmd/server/rsrc_windows_amd64.syso
|
||||
/cmd/tray/rsrc_windows_amd64.syso
|
||||
|
||||
# Local deployment environment (keep secrets out of Git)
|
||||
/.env
|
||||
|
||||
@@ -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,90 @@ 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:24-trixie-slim`, copies the cached runtime prepared by CI, installs only the Chromium system libraries
|
||||
through the bundled Playwright driver, and clears apt indexes and temporary caches in the same image layer.
|
||||
The desktop CI workflow runs on `main` and `dev`; formal desktop builds are invoked by the unified
|
||||
`release.yml` workflow for `v*.*.*` version tags. 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: branch builds publish `main` or `dev` plus a full-commit `sha-*` tag, while formal builds publish semantic
|
||||
version tags, `latest`, and the full-commit `sha-*` tag only after the `production-release` Environment approval.
|
||||
Version tags create a GitHub Release containing all platform packages and SHA-256 checksums. Never publish a Docker
|
||||
manifest until Go/frontend tests, an actual Chromium launch, and the packaged server health check have passed for
|
||||
every architecture.
|
||||
|
||||
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
|
||||
|
||||
|
||||
+74
-28
@@ -1,55 +1,101 @@
|
||||
# syntax=docker/dockerfile:1.7
|
||||
|
||||
FROM --platform=$BUILDPLATFORM node:22-trixie AS frontend
|
||||
FROM --platform=$BUILDPLATFORM node:24-trixie-slim 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
|
||||
ARG APP_VERSION=dev
|
||||
ARG VCS_REF=unknown
|
||||
ARG BUILD_TIME=unknown
|
||||
WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY . .
|
||||
COPY --from=frontend /src/internal/webui/static ./internal/webui/static
|
||||
RUN CGO_ENABLED=0 GOOS="$TARGETOS" GOARCH="$TARGETARCH" go build -trimpath -ldflags="-s -w" -o /out/xianyu-server ./cmd/server \
|
||||
RUN CGO_ENABLED=0 GOOS="$TARGETOS" GOARCH="$TARGETARCH" go build -trimpath \
|
||||
-ldflags="-s -w -X xianyu-go/internal/version.Version=$APP_VERSION -X xianyu-go/internal/version.Commit=$VCS_REF -X xianyu-go/internal/version.BuildTime=$BUILD_TIME" \
|
||||
-o /out/xianyu-server ./cmd/server \
|
||||
&& 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:24-trixie-slim 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:24-trixie-slim 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
|
||||
ENV SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt
|
||||
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
|
||||
RUN mkdir -p /app/data /app/browser_data
|
||||
EXPOSE 8080
|
||||
CMD ["/app/xianyu-server", "-addr", ":8080"]
|
||||
COPY --from=playwright-runtime /ms-playwright-go /ms-playwright-go
|
||||
COPY --from=playwright-runtime /ms-playwright /ms-playwright
|
||||
# 浏览器文件本身不包含 Linux 动态链接库。使用与 runtime 同捆的 Playwright
|
||||
# driver 只安装 Chromium 所需系统依赖,并在同一镜像层清理 apt/npm/临时缓存。
|
||||
RUN set -eux; \
|
||||
node /ms-playwright-go/package/cli.js install-deps chromium; \
|
||||
apt-get update; \
|
||||
apt-get install --reinstall -y --no-install-recommends ca-certificates; \
|
||||
update-ca-certificates --fresh; \
|
||||
test -s "$SSL_CERT_FILE"; \
|
||||
grep -q -- '-----BEGIN CERTIFICATE-----' "$SSL_CERT_FILE"; \
|
||||
test -x "$PLAYWRIGHT_NODEJS_PATH"; \
|
||||
test -f "$PLAYWRIGHT_DRIVER_PATH/package/cli.js"; \
|
||||
find "$PLAYWRIGHT_BROWSERS_PATH" -type f -perm -111 \( -name chrome -o -name chrome-headless-shell -o -name headless_shell \) -print -quit | grep -q .; \
|
||||
apt-get clean; \
|
||||
rm -rf /var/lib/apt/lists/* /var/cache/apt/* /root/.cache /tmp/* /var/tmp/*; \
|
||||
mkdir -p /app/data /app/browser_data
|
||||
EXPOSE 59188
|
||||
CMD ["/app/xianyu-server", "-addr", ":59188"]
|
||||
+2
-2
@@ -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:24-trixie-slim 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:24-trixie-slim AS frontend-test
|
||||
WORKDIR /src/frontend
|
||||
COPY frontend/package*.json ./
|
||||
RUN npm ci
|
||||
|
||||
@@ -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 ./...
|
||||
|
||||
@@ -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 镜像公开时可以匿名拉取。若镜像仍为私有,请先执行
|
||||
@@ -158,7 +158,7 @@ docker compose up -d
|
||||
环境要求:
|
||||
|
||||
- Go 1.26.4 或兼容版本
|
||||
- Node.js 22 与 npm
|
||||
- Node.js 24 与 npm
|
||||
- Chromium 运行所需的系统依赖
|
||||
- 默认可直接使用 SQLite,无需额外数据库服务
|
||||
|
||||
@@ -174,7 +174,86 @@ 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/workflows/desktop-cd.yml` 在 `dev`、`main` 分支上持续构建;正式版本由统一的
|
||||
`.github/workflows/release.yml` 在 `v1.2.3` 格式的版本标签上协调构建:
|
||||
Linux 上传 amd64/arm64 tar 包,Windows 上传安装器,macOS 分别上传 arm64 和 amd64 安装包。
|
||||
分支构建只保留非正式 Actions artifacts;版本标签必须指向 `main` 中的提交,全部桌面端和 Docker
|
||||
构建验证成功后等待 `production-release` Environment 人工审批,审批通过才创建 GitHub Release、
|
||||
上传各平台安装包及 `SHA256SUMS`,并发布正式 Docker 标签。Windows
|
||||
和 macOS 安装包使用工作流中配置的固定签名证书签名;未配置对应 GitHub Secrets 时,签名
|
||||
步骤会失败,不会生成可分发的安装包。当前仓库未配置正式签名证书时,Windows/macOS 正式发布
|
||||
会停在签名步骤;Linux 安装包不依赖桌面端签名证书。
|
||||
|
||||
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 +266,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,15 +310,18 @@ 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` | 容器和日志时区 |
|
||||
|
||||
前端构建还支持 `VITE_AMAP_JS_KEY`,用于覆盖发布页高德 JS API 的公开 Key;未设置时使用内置的公开 Key。修改后需重新执行 `make frontend` 才会写入嵌入式前端资源。
|
||||
|
||||
Docker Compose 还支持:
|
||||
|
||||
| 变量 | 默认值 | 说明 |
|
||||
@@ -251,10 +333,13 @@ 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-<提交号>` 标签。
|
||||
默认 `compose.yml` 直接拉取 GHCR 的 `:latest` 多架构镜像;如需固定版本,请把
|
||||
`XIANYU_IMAGE` 设置为完整镜像地址,例如
|
||||
`ghcr.io/christ9038/ydisks-xianyu-helper:v1.2.3`、
|
||||
`ghcr.io/christ9038/ydisks-xianyu-helper:main` 或
|
||||
`ghcr.io/christ9038/ydisks-xianyu-helper:sha-<完整提交号>`。
|
||||
|
||||
`XIANYU_DATA_KEY` 用于加密 Cookie、账号密码、设备令牌、访问令牌、AI/SMTP 密钥和
|
||||
通知凭证。启用后,服务会自动升级历史明文数据。密钥丢失或更换后,已有加密数据将
|
||||
@@ -266,7 +351,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 指纹读取和滑块处理 |
|
||||
@@ -332,12 +417,14 @@ ARM64 Linux 拉取 arm64,不需要手动设置 `platform`。
|
||||
|
||||
| Git 引用 | 镜像标签 |
|
||||
| --- | --- |
|
||||
| `main` 分支 | `main`、`latest`、`sha-<完整提交号>` |
|
||||
| `v1.2.3` 标签 | `1.2.3`、`1.2`、`sha-<完整提交号>` |
|
||||
| `dev` 分支 | `dev`、`sha-<完整提交号>` |
|
||||
| `main` 分支 | `main`、`sha-<完整提交号>` |
|
||||
| `v1.2.3` 标签 | `v1.2.3`、`1.2.3`、`1.2`、`latest`、`sha-<完整提交号>` |
|
||||
|
||||
当前 Docker 发布工作流只在 `main` 分支推送和发布镜像;`dev` 分支不会自动生成
|
||||
GHCR 标签。开发分支如需验证镜像,请在本地使用源码构建 Compose 文件,或手动运行
|
||||
对应的构建流程。
|
||||
`dev` 是日常调试通道,`main` 是稳定候选通道,两者都不会更新 `latest` 或创建 Release。推送
|
||||
`v1.2.3` 格式的 Git 标签会触发统一正式发布流程。所有 Docker 发布都必须先通过 Go/前端测试,
|
||||
再对每个原生架构镜像实际启动 Chromium 和服务并通过 `/health` 检查;正式版还必须等全部桌面
|
||||
安装包构建成功并通过人工审批,之后才生成版本 manifest、更新 `latest` 并创建 GitHub Release。
|
||||
|
||||
生产环境建议使用明确的版本标签或 SHA 标签,避免上游更新导致未经验证的自动升级。
|
||||
|
||||
@@ -390,16 +477,19 @@ 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
|
||||
```
|
||||
|
||||
健康接口正常时返回:
|
||||
健康接口正常时返回(构建信息会随运行方式变化):
|
||||
|
||||
```json
|
||||
{"database":"ok","status":"ok"}
|
||||
{"status":"ok","database":"ok","version":"dev","commit":"unknown","build_time":"unknown"}
|
||||
```
|
||||
|
||||
正式安装包和 Docker 镜像会注入对应版本、提交号和构建时间;源码运行默认显示
|
||||
`dev`/`unknown`。管理后台侧边栏底部也会显示当前运行版本和短提交号。
|
||||
|
||||
### 更新镜像
|
||||
|
||||
```bash
|
||||
@@ -454,7 +544,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 +555,8 @@ services:
|
||||
.
|
||||
├── cmd/
|
||||
│ ├── server/ # 主服务与管理员初始化入口
|
||||
│ ├── browser-install/ # Playwright Chromium 安装辅助程序
|
||||
│ ├── tray/ # Windows 托盘/macOS 菜单栏控制器
|
||||
│ ├── init-admin/ # 交互式管理员初始化工具
|
||||
│ ├── dbverify/ # 多数据库迁移和 CRUD 验证
|
||||
│ └── dbseed/ # Docker 功能测试数据种子
|
||||
@@ -481,6 +573,7 @@ services:
|
||||
│ └── xianyu/ # MTOP、WebSocket、登录和协议实现
|
||||
├── frontend/ # React、TypeScript、Vite 前端
|
||||
├── docs/ # 专题文档和行为规范
|
||||
├── packaging/ # Linux systemd、Windows Inno Setup、macOS pkg
|
||||
├── scripts/ # Docker 与回归测试脚本
|
||||
└── Dockerfile.debian13 # 多阶段生产镜像
|
||||
```
|
||||
@@ -490,7 +583,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 +593,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 +634,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 +663,12 @@ 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` 包。最终镜像基于
|
||||
固定的 Node.js 24 slim 镜像,只通过 Playwright 安装 Chromium 所需动态库,并在同一镜像层清理
|
||||
apt 索引和临时缓存;发布前会实际启动 Chromium 和服务进行门禁验证。
|
||||
- 独立安装包在 CI 构建阶段下载对应架构的 Playwright driver 和 Chromium;Linux 安装时只
|
||||
安装系统库,不需要再次下载浏览器。
|
||||
- 源码运行时确认系统允许下载 Playwright 驱动和 Chromium。
|
||||
- 自带 Chromium 时设置 `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH`,并按需设置
|
||||
`PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1`。
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
+270
-80
@@ -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"
|
||||
|
||||
@@ -34,125 +29,240 @@ import (
|
||||
"xianyu-go/internal/notify"
|
||||
"xianyu-go/internal/renewal"
|
||||
"xianyu-go/internal/server"
|
||||
appversion "xianyu-go/internal/version"
|
||||
)
|
||||
|
||||
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
|
||||
showVersion 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.showVersion {
|
||||
fmt.Printf("Ydisks Xianyu Helper %s (commit %s, built %s)\n", appversion.Version, appversion.ShortCommit(), appversion.BuildTime)
|
||||
return
|
||||
}
|
||||
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.BoolVar(&opts.showVersion, "version", false, "显示版本和构建信息后退出")
|
||||
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
|
||||
}
|
||||
packagedPlaywrightRuntime := strings.TrimSpace(opts.playwrightRuntimeRoot) != ""
|
||||
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)
|
||||
}
|
||||
// 只有安装包显式提供 runtime root 时,才把 Playwright runtime
|
||||
// 放进应用数据目录。普通本地开发应沿用 Playwright 的用户缓存;
|
||||
// 空的应用目录会让 playwright-go 误以为 driver 已配置,随后尝试
|
||||
// 执行不存在的 <dataDir>/playwright-driver/node。
|
||||
if packagedPlaywrightRuntime && opts.playwrightDriverDir == "" {
|
||||
opts.playwrightDriverDir = filepath.Join(dataDir, "playwright-driver")
|
||||
}
|
||||
if packagedPlaywrightRuntime && 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 +278,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 +294,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 +401,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) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
//go:build !windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func runPlatformService(_ string, _ func(context.Context) error) error {
|
||||
return fmt.Errorf("当前平台不支持 -service;请使用系统服务管理器启动普通进程")
|
||||
}
|
||||
@@ -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 |
@@ -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
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 171 KiB |
@@ -0,0 +1,43 @@
|
||||
//go:build !windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
func acquireTrayInstance() (release func(), acquired bool, err error) {
|
||||
cacheDirectory, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("获取用户缓存目录失败: %w", err)
|
||||
}
|
||||
lockDirectory := filepath.Join(cacheDirectory, "YdisksXianyuHelper")
|
||||
if err := os.MkdirAll(lockDirectory, 0o755); err != nil {
|
||||
return nil, false, fmt.Errorf("创建托盘锁目录失败: %w", err)
|
||||
}
|
||||
|
||||
return acquireTrayFileLock(filepath.Join(lockDirectory, "tray.lock"))
|
||||
}
|
||||
|
||||
func acquireTrayFileLock(lockPath string) (release func(), acquired bool, err error) {
|
||||
lockFile, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0o600)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("打开托盘锁文件失败: %w", err)
|
||||
}
|
||||
if err := unix.Flock(int(lockFile.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil {
|
||||
_ = lockFile.Close()
|
||||
if err == unix.EWOULDBLOCK || err == unix.EAGAIN {
|
||||
return func() {}, false, nil
|
||||
}
|
||||
return nil, false, fmt.Errorf("锁定托盘实例失败: %w", err)
|
||||
}
|
||||
|
||||
return func() {
|
||||
_ = unix.Flock(int(lockFile.Fd()), unix.LOCK_UN)
|
||||
_ = lockFile.Close()
|
||||
}, true, nil
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//go:build !windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAcquireTrayInstanceRejectsSecondInstance(t *testing.T) {
|
||||
lockPath := filepath.Join(t.TempDir(), "tray.lock")
|
||||
releaseFirst, acquired, err := acquireTrayFileLock(lockPath)
|
||||
if err != nil {
|
||||
t.Fatalf("acquire first tray instance: %v", err)
|
||||
}
|
||||
if !acquired {
|
||||
t.Fatal("first tray instance should acquire lock")
|
||||
}
|
||||
defer releaseFirst()
|
||||
|
||||
releaseSecond, acquired, err := acquireTrayFileLock(lockPath)
|
||||
if err != nil {
|
||||
t.Fatalf("acquire second tray instance: %v", err)
|
||||
}
|
||||
defer releaseSecond()
|
||||
if acquired {
|
||||
t.Fatal("second tray instance must be rejected")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
//go:build windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
func acquireTrayInstance() (release func(), acquired bool, err error) {
|
||||
mutexName, err := windows.UTF16PtrFromString(`Local\YdisksXianyuHelperTray`)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("生成托盘互斥锁名称失败: %w", err)
|
||||
}
|
||||
handle, err := windows.CreateMutex(nil, false, mutexName)
|
||||
if err == windows.ERROR_ALREADY_EXISTS {
|
||||
if handle != 0 {
|
||||
_ = windows.CloseHandle(handle)
|
||||
}
|
||||
return func() {}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("创建托盘互斥锁失败: %w", err)
|
||||
}
|
||||
return func() { _ = windows.CloseHandle(handle) }, true, nil
|
||||
}
|
||||
@@ -0,0 +1,367 @@
|
||||
// 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"`
|
||||
Version string `json:"version"`
|
||||
Commit string `json:"commit"`
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
//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_SERVICE_DOES_NOT_EXIST) {
|
||||
return fmt.Errorf("Windows 服务 %s 尚未安装,请重新运行安装器", name)
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//go:build windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
type fakeWindowsServiceController struct {
|
||||
states []uint32
|
||||
actions []string
|
||||
}
|
||||
|
||||
func (controller *fakeWindowsServiceController) state() (uint32, error) {
|
||||
if len(controller.states) == 0 {
|
||||
return 0, fmt.Errorf("测试状态序列为空")
|
||||
}
|
||||
state := controller.states[0]
|
||||
if len(controller.states) > 1 {
|
||||
controller.states = controller.states[1:]
|
||||
}
|
||||
return state, nil
|
||||
}
|
||||
|
||||
func (controller *fakeWindowsServiceController) start() error {
|
||||
controller.actions = append(controller.actions, "start")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (controller *fakeWindowsServiceController) stop() error {
|
||||
controller.actions = append(controller.actions, "stop")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (controller *fakeWindowsServiceController) close() {}
|
||||
|
||||
func TestWindowsRestartWaitsForStoppedBeforeStarting(t *testing.T) {
|
||||
controller := &fakeWindowsServiceController{
|
||||
states: []uint32{
|
||||
windows.SERVICE_RUNNING,
|
||||
windows.SERVICE_STOP_PENDING,
|
||||
windows.SERVICE_STOPPED,
|
||||
windows.SERVICE_STOPPED,
|
||||
windows.SERVICE_START_PENDING,
|
||||
windows.SERVICE_RUNNING,
|
||||
},
|
||||
}
|
||||
if err := controlWindowsService(controller, "restart", time.Second, time.Millisecond); err != nil {
|
||||
t.Fatalf("restart Windows service: %v", err)
|
||||
}
|
||||
if want := []string{"stop", "start"}; !reflect.DeepEqual(controller.actions, want) {
|
||||
t.Fatalf("actions = %v, want %v", controller.actions, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWindowsStartWaitsForPreviousStop(t *testing.T) {
|
||||
controller := &fakeWindowsServiceController{
|
||||
states: []uint32{
|
||||
windows.SERVICE_STOP_PENDING,
|
||||
windows.SERVICE_STOPPED,
|
||||
windows.SERVICE_START_PENDING,
|
||||
windows.SERVICE_RUNNING,
|
||||
},
|
||||
}
|
||||
if err := controlWindowsService(controller, "start", time.Second, time.Millisecond); err != nil {
|
||||
t.Fatalf("start Windows service: %v", err)
|
||||
}
|
||||
if want := []string{"start"}; !reflect.DeepEqual(controller.actions, want) {
|
||||
t.Fatalf("actions = %v, want %v", controller.actions, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWindowsServiceAccessIsLimitedToStatusStartStop(t *testing.T) {
|
||||
want := uint32(windows.SERVICE_QUERY_STATUS | windows.SERVICE_START | windows.SERVICE_STOP)
|
||||
if windowsServiceAccess != want {
|
||||
t.Fatalf("service access = %#x, want %#x", windowsServiceAccess, want)
|
||||
}
|
||||
}
|
||||
+3
-7
@@ -8,10 +8,6 @@ x-app-env: &app-env
|
||||
LOG_LEVEL: ${LOG_LEVEL:-info}
|
||||
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_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 +41,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
|
||||
|
||||
@@ -6,10 +6,6 @@ x-app-env: &app-env
|
||||
LOG_LEVEL: ${LOG_LEVEL:-info}
|
||||
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_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 +41,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
|
||||
|
||||
@@ -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
|
||||
|
||||
+63
-22
@@ -914,7 +914,7 @@
|
||||
<div style="width: 50px;"></div>
|
||||
</div>
|
||||
<div class="preview-img-container">
|
||||
<img src="img/preview.png" alt="Ydisks 闲鱼助手 Dashboard Preview" loading="lazy">
|
||||
<img src="img/preview_account.png" alt="Ydisks 闲鱼助手 Dashboard Preview" loading="lazy">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -96,6 +96,9 @@ distance = track.width - button.width
|
||||
- 页面加载后随机等待 `0.3–0.8s`,移动鼠标到 `(640, 360)`,滚动 `200–500px`,并保留现有短暂停顿。
|
||||
- 页面包含“抱歉,页面访问出现了问题”时,判定验证链接过期。
|
||||
- 页面包含 `STATUS_BREAKPOINT` 或“崩溃”时,判定验证页崩溃。
|
||||
- 页面准备完成后、首次滑动前必须先判定页面类型:只有同一 frame 内存在可见的滑块按钮和轨道时才进入滑动逻辑。
|
||||
- 如果没有可见滑块,并且任一 frame 的可见正文直接显示“验证失败”“安全验证未通过”“请求/加载失败”“系统繁忙”“服务/网络/页面异常”“请稍后重试”或对应英文错误提示,则判定为无可验证滑块的直接错误页,立即停止自动验证。
|
||||
- 直接错误页不得通过点击错误框、reload 或备用引擎强行转成滑块尝试;只有已经实际拖动过滑块后出现的 `.errloading` 才继续按第 5 节恢复。
|
||||
- 拖动前必须保存所有域上的旧 `x5sec` 值,供严格成功判定使用。
|
||||
|
||||
### 3.2 距离计算
|
||||
@@ -199,6 +202,7 @@ Playwright 主引擎
|
||||
|
||||
- 获取新验证链接的 provider 不得在主引擎持有同账号持久化 profile 锁时调用,避免同账号锁死。
|
||||
- 过期链接最多触发现有的 2 次链接刷新;最终仍过期时直接失败,不把过期 URL 交给备用引擎重放。
|
||||
- 主引擎判定为“没有可见滑块的直接错误页”时立即失败,不刷新链接,也不进入直接 Chromium/CDP 备用引擎。
|
||||
- 进入备用引擎前可再获取一次新链接和更新后的 Cookie。
|
||||
- `CAPTCHA_REAL_MOUSE=true` 在当前 Go/Docker 实现中只记录物理鼠标不可用,并继续备用逻辑;不得假装已启用物理鼠标。
|
||||
- `CAPTCHA_DRISSIONPAGE_FALLBACK_ENABLED` 默认为启用。
|
||||
@@ -242,6 +246,7 @@ Playwright 主引擎
|
||||
- 最终 `left`、最终 class 或最终 X 偏移。
|
||||
- 失败时的按钮 style/class、轨道 class、可见重试选择器和重试文本。
|
||||
- 恢复方式是 `click` 还是 `reload`、所用选择器以及是否重新归位。
|
||||
- 自动滑块最终失败时,错误文本和 `token 风控滑块处理失败` 日志的 `verification_url` 字段必须包含最后实际使用的完整验证地址(包括 query),供用户复制到本机浏览器手动验证。此字段是仅在最终失败时提供的人工接管信息;常规页面/frame 诊断日志仍必须去掉 query 与 fragment。
|
||||
|
||||
页面可能被浏览器扩展注入大量无关 DOM。当前仅把下列注入作为诊断信息记录,不允许它们改变滑块定位、距离或成功判定:
|
||||
|
||||
@@ -268,6 +273,7 @@ go vet ./internal/browser ./internal/engine ./internal/account ./internal/server
|
||||
- 主引擎首次滑动成功。
|
||||
- 主引擎首次失败并隐藏滑块,点击 `.errloading` 恢复后第二次成功。
|
||||
- 直接 Chromium/CDP 备用引擎使用同一恢复流程后成功。
|
||||
- 没有可见滑块、只显示直接错误提示的真实 Chromium 页面必须被识别,并且不得进入滑动或备用引擎。
|
||||
- 标准 `300px` 轨道与 `42px` 按钮得到精确 `258px`。
|
||||
- 旧 `x5sec` 不得判成功,新 `x5sec` 才能判成功。
|
||||
|
||||
@@ -275,6 +281,10 @@ go vet ./internal/browser ./internal/engine ./internal/account ./internal/server
|
||||
|
||||
## 10. 唯一变更流程
|
||||
|
||||
### 2026-08-13 当前授权变更
|
||||
|
||||
用户明确要求改变“未找到滑块时仍执行失败恢复/备用引擎”和“最终失败日志只保留脱敏页面地址”的既有契约。原因是风控页有时只显示平台错误信息而没有可操作滑块,继续 reload、拖动或切换引擎没有验证意义且会增加风控;而真实滑块自动处理失败时,用户需要完整地址在本机浏览器中接管验证。本规范第 3.1、6、8、9 节已同步纳入新的页面分类、编排、日志和集成验证要求。
|
||||
|
||||
只有用户在当前任务中明确点名要求修改滑块认证时,才允许触碰冻结范围。获得授权后也必须在同一个变更中:
|
||||
|
||||
1. 说明要改变本文哪一条冻结契约及原因。
|
||||
|
||||
+32
-11
@@ -5,16 +5,31 @@
|
||||
|
||||
## 推荐上线路径
|
||||
|
||||
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,
|
||||
安装脚本只补齐系统依赖。桌面托盘退出前会先停止后台服务。
|
||||
|
||||
管理后台侧边栏底部会显示当前运行版本和短提交号。源码运行默认显示 `dev`/`unknown`;正式安装包和
|
||||
Docker 镜像会显示构建时注入的正式版本与提交信息。
|
||||
|
||||
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 仓库版本。
|
||||
|
||||
## 先读这些页面
|
||||
|
||||
@@ -34,4 +49,10 @@
|
||||
|
||||
## GitHub Wiki 同步
|
||||
|
||||
这些 Markdown 文件位于仓库 `docs/wiki/`,可直接复制到 GitHub Wiki 对应页面;文件名即页面名。`_Sidebar.md` 是 Wiki 导航。仓库内保留副本便于在 Pull Request 中审阅和版本化维护。
|
||||
这些 Markdown 文件位于仓库 `docs/wiki/`,是 Wiki 的唯一维护来源;文件名即页面名,`_Sidebar.md` 是
|
||||
Wiki 导航。`main` 分支发生变更后,`.github/workflows/sync-wiki.yml` 会自动把这些文件镜像到 GitHub
|
||||
Wiki;也可以通过 GitHub Actions 手动运行该工作流。仓库内保留副本,便于在 Pull Request 中审阅和版本化维护,
|
||||
不建议直接在 GitHub Wiki 仓库中维护内容。
|
||||
|
||||
项目 Pages 站点使用 `main` 分支的 `/docs` 目录发布,域名由 `docs/CNAME` 中的配置决定;修改首页或图片资源
|
||||
后,合并到 `main` 即可由 GitHub Pages 发布。Pages 发布与 GitHub Wiki 同步是两个独立流程。
|
||||
+74
-5
@@ -18,18 +18,79 @@
|
||||
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 而跳过静默续期。续期结果仍以闲鱼响应和账号登录态为准。
|
||||
|
||||
## 版本、镜像与正式发布
|
||||
|
||||
项目以 Git 标签作为正式版本来源,正式标签必须符合 `v1.2.3` 格式,并指向 `main` 已包含的提交。
|
||||
推送正式标签后,统一的 `.github/workflows/release.yml` 会重新从该标签提交构建桌面安装包和 Docker 镜像;
|
||||
不会复用之前 `main` 分支构建的产物。
|
||||
构建、Chromium 启动和 `/health` 检查全部通过后,还需要 `production-release` Environment 人工审批,
|
||||
审批通过才会创建 GitHub Release、上传安装包与 `SHA256SUMS`,并更新正式镜像标签。
|
||||
|
||||
Docker 标签规则如下:
|
||||
|
||||
| Git 引用 | 镜像标签 | 是否正式发布 |
|
||||
| --- | --- | --- |
|
||||
| `dev` 分支 | `dev`、`sha-<完整提交号>` | 否,用于日常调试 |
|
||||
| `main` 分支 | `main`、`sha-<完整提交号>` | 否,稳定候选构建 |
|
||||
| `v1.2.3` 标签 | `v1.2.3`、`1.2.3`、`1.2`、`latest`、`sha-<完整提交号>` | 是 |
|
||||
|
||||
`latest` 只在正式版本审批发布阶段更新,不会随 `main` 或 `dev` 分支提交变化。生产环境建议使用
|
||||
`v1.2.3`、`1.2.3` 或 SHA 标签固定版本;Compose 默认使用 `latest`。
|
||||
|
||||
当前 Windows 和 macOS 正式安装包的 CI 签名步骤仍需要对应的签名证书 Secrets;未配置时这些平台的
|
||||
正式发布会在签名步骤失败。Linux 安装包不依赖桌面端签名证书。
|
||||
|
||||
## 独立安装包
|
||||
|
||||
独立安装包与 Docker 使用同一套 Playwright Chromium 版本来源:Chromium、headless shell 和
|
||||
Playwright driver 都在构建阶段下载并放入包内,不使用 Debian 仓库的 Chromium。Docker CI 会优先
|
||||
复用架构专属的 GitHub Actions runtime 缓存,Dockerfile 最终使用固定的 Node.js 24 slim 运行时,
|
||||
只通过 Playwright 安装 Chromium 所需系统动态库,随后清理 apt 索引和临时缓存,不安装 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 +107,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 +116,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
@@ -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>
|
||||
|
||||
+13
-5
@@ -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 开发服务器地址,不是应用服务端口。
|
||||
|
||||
## 构建产物
|
||||
|
||||
@@ -36,6 +38,9 @@ npm run build
|
||||
生产部署无需单独分发前端。若 Go 服务已经运行,构建完成后必须重启 Go 服务,
|
||||
因为嵌入资源在 Go 编译时写入服务二进制;仅刷新浏览器不会更新已运行进程中的前端版本。
|
||||
|
||||
侧边栏底部的运行版本和短提交号来自后端 `/health` 接口。源码运行通常显示 `dev`/`unknown`;CI
|
||||
构建的安装包和 Docker 镜像由构建参数注入对应版本信息。
|
||||
|
||||
## Dashboard 图表约定
|
||||
|
||||
Dashboard 的营收趋势柱状图使用统一的品牌蓝 `#0094f7` 表示同一指标序列,日期之间
|
||||
@@ -48,7 +53,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`,支持深链刷新。
|
||||
|
||||
## 测试
|
||||
|
||||
|
||||
@@ -50,6 +50,7 @@ const AccountList: React.FC = () => {
|
||||
const [showQRModal, setShowQRModal] = useState(false);
|
||||
const [qrCodeUrl, setQrCodeUrl] = useState<string>('');
|
||||
const [qrStatus, setQrStatus] = useState<string>('pending');
|
||||
const [qrErrorMessage, setQrErrorMessage] = useState<string>('');
|
||||
const [verificationScreenshot, setVerificationScreenshot] = useState<string>('');
|
||||
const [faceQrUrl, setFaceQrUrl] = useState<string>('');
|
||||
const [qrReauthTarget, setQrReauthTarget] = useState<AccountDetail | null>(null);
|
||||
@@ -624,12 +625,16 @@ const AccountList: React.FC = () => {
|
||||
setQrReauthTarget(targetAccount);
|
||||
setShowQRModal(true);
|
||||
setQrStatus('loading');
|
||||
setQrErrorMessage('');
|
||||
setQrCodeUrl('');
|
||||
setVerificationScreenshot('');
|
||||
setFaceQrUrl('');
|
||||
try {
|
||||
const res = await generateQRLogin({ signal: controller.signal });
|
||||
if (!qrRequestGateRef.current?.isCurrent(requestGeneration)) return;
|
||||
if (!res.success || !res.qr_code_url || !res.session_id) {
|
||||
throw new Error(res.message || '闲鱼未返回可用的登录二维码');
|
||||
}
|
||||
if (res.success && res.qr_code_url && res.session_id) {
|
||||
const generatedSessionID = res.session_id;
|
||||
setQrCodeUrl(res.qr_code_url);
|
||||
@@ -674,7 +679,10 @@ const AccountList: React.FC = () => {
|
||||
}
|
||||
} catch (e) {
|
||||
if (!qrRequestGateRef.current?.isCurrent(requestGeneration)) return;
|
||||
setQrErrorMessage(e instanceof Error ? e.message : '二维码获取失败,请稍后重试');
|
||||
setQrStatus('error');
|
||||
} finally {
|
||||
if (qrGenerateAbortRef.current === controller) qrGenerateAbortRef.current = null;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1029,7 +1037,7 @@ const AccountList: React.FC = () => {
|
||||
{qrStatus === 'error' && (
|
||||
<div className="px-5 text-center">
|
||||
<span className="block text-red-600 font-bold">二维码获取失败</span>
|
||||
<span className="mt-2 block text-xs leading-5 text-gray-500">请关闭窗口后重新发起扫码登录。</span>
|
||||
<span className="mt-2 block text-xs leading-5 text-gray-500">{qrErrorMessage || '请关闭窗口后重新发起扫码登录。'}</span>
|
||||
</div>
|
||||
)}
|
||||
{qrStatus === 'verification' && (
|
||||
|
||||
@@ -20,7 +20,9 @@ import {
|
||||
deleteItem,
|
||||
getShippingRules
|
||||
} from '../services/api';
|
||||
import { ArrowRight, Box, CheckCircle2, CircleDashed, Edit, Filter, Link2, PackagePlus, Plus, RefreshCw, Save, Search, ShoppingBag, Trash2, UploadCloud, User, X } from 'lucide-react';
|
||||
import type { PublishLocation } from '../services/api';
|
||||
import { getPublishLocations } from '../services/amapLocation';
|
||||
import { ArrowRight, Box, CheckCircle2, CircleDashed, Edit, Filter, Link2, LocateFixed, PackagePlus, Plus, RefreshCw, Save, Search, ShoppingBag, Trash2, UploadCloud, User, X } from 'lucide-react';
|
||||
|
||||
interface ItemListProps {
|
||||
onConfigureDelivery: (item: Item) => void;
|
||||
@@ -100,6 +102,11 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
const [batchImagesZip, setBatchImagesZip] = useState<File | null>(null);
|
||||
const [batchCategoryKeyword, setBatchCategoryKeyword] = useState('');
|
||||
const [batchCategoryLoading, setBatchCategoryLoading] = useState(false);
|
||||
const [locationLoading, setLocationLoading] = useState(false);
|
||||
const [publishLocations, setPublishLocations] = useState<PublishLocation[]>([]);
|
||||
const [publishLocation, setPublishLocation] = useState<PublishLocation | null>(null);
|
||||
const [batchLocations, setBatchLocations] = useState<PublishLocation[]>([]);
|
||||
const [batchLocation, setBatchLocation] = useState<PublishLocation | null>(null);
|
||||
const [batchFallbackCategory, setBatchFallbackCategory] = useState({
|
||||
catId: '',
|
||||
catName: '',
|
||||
@@ -133,8 +140,8 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
original_price: '',
|
||||
quantity: '1',
|
||||
postage_mode: 'free',
|
||||
postage: '',
|
||||
images: [] as File[]
|
||||
postage: '',
|
||||
images: [] as File[],
|
||||
});
|
||||
const [publishImagePreviews, setPublishImagePreviews] = useState<{ key: string; url: string }[]>([]);
|
||||
|
||||
@@ -285,12 +292,12 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
if (!publishForm.title.trim()) return alert('请填写商品标题');
|
||||
if (!publishForm.price.trim()) return alert('请填写商品价格');
|
||||
if (!publishForm.quantity || Number(publishForm.quantity) <= 0) return alert('库存数量必须大于 0');
|
||||
if (publishForm.images.length === 0) return alert('至少上传 1 张商品图片');
|
||||
if (publishForm.postage_mode === 'fixed' && !publishForm.postage.trim()) return alert('请填写一口价邮费');
|
||||
if (publishForm.images.length === 0) return alert('至少上传 1 张商品图片');
|
||||
if (publishForm.postage_mode === 'fixed' && !publishForm.postage.trim()) return alert('请填写一口价邮费');
|
||||
|
||||
setPublishing(true);
|
||||
try {
|
||||
const result = await publishItem(publishForm);
|
||||
const result = await publishItem({ ...publishForm, location: publishLocation || undefined });
|
||||
await loadItems();
|
||||
setShowPublishModal(false);
|
||||
setPublishForm({
|
||||
@@ -302,8 +309,10 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
quantity: '1',
|
||||
postage_mode: 'free',
|
||||
postage: '',
|
||||
images: []
|
||||
images: [],
|
||||
});
|
||||
setPublishLocations([]);
|
||||
setPublishLocation(null);
|
||||
if (result?.item_id) {
|
||||
const publishedItem: Item = {
|
||||
id: result.item_id,
|
||||
@@ -339,6 +348,8 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
setBatchImagesZip(null);
|
||||
setBatchCategoryKeyword('');
|
||||
setBatchFallbackCategory({ catId: '', catName: '', channelCatId: '', tbCatId: '' });
|
||||
setBatchLocations([]);
|
||||
setBatchLocation(null);
|
||||
setShowBatchModal(true);
|
||||
setBatchLoading(true);
|
||||
try {
|
||||
@@ -404,6 +415,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
imagesZip: batchImagesZip,
|
||||
defaultCookieId: selectedAccount,
|
||||
fallbackCategory: batchFallbackCategory,
|
||||
location: batchLocation || undefined,
|
||||
});
|
||||
setBatchPreview(result);
|
||||
setBatchDetail(null);
|
||||
@@ -517,6 +529,26 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
setShowPublishModal(true);
|
||||
};
|
||||
|
||||
const locateForPublish = async (batch: boolean) => {
|
||||
const cookieId = batch ? selectedAccount : publishForm.cookie_id;
|
||||
if (!cookieId) return alert('请先选择发布账号');
|
||||
if (!navigator.geolocation) return alert('当前浏览器不支持定位');
|
||||
setLocationLoading(true);
|
||||
navigator.geolocation.getCurrentPosition(async position => {
|
||||
try {
|
||||
const locations = await getPublishLocations(position.coords.longitude, position.coords.latitude);
|
||||
if (!locations.length) throw new Error('当前位置附近没有可用的高德发货地,请稍后重试');
|
||||
if (batch) { setBatchLocations(locations); setBatchLocation(locations[0]); }
|
||||
else { setPublishLocations(locations); setPublishLocation(locations[0]); }
|
||||
} catch (error: any) {
|
||||
alert(error?.message || '获取发货地失败');
|
||||
} finally { setLocationLoading(false); }
|
||||
}, error => {
|
||||
setLocationLoading(false);
|
||||
alert(error.code === error.PERMISSION_DENIED ? '定位权限被拒绝,请在浏览器设置中允许定位' : '无法获取当前位置,请稍后重试');
|
||||
}, { enableHighAccuracy: true, timeout: 15000, maximumAge: 60000 });
|
||||
};
|
||||
|
||||
const rulesForItem = (item: Item) => shippingRules.filter(rule =>
|
||||
rule.cookie_id === item.cookie_id && rule.item_id === item.item_id
|
||||
).length > 0
|
||||
@@ -822,7 +854,11 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700">发布账号</label>
|
||||
<select className="w-full ios-input px-4 py-3 rounded-xl" value={publishForm.cookie_id} onChange={e => setPublishForm({...publishForm, cookie_id: e.target.value})}>
|
||||
<select className="w-full ios-input px-4 py-3 rounded-xl" value={publishForm.cookie_id} onChange={e => {
|
||||
setPublishForm({...publishForm, cookie_id: e.target.value});
|
||||
setPublishLocations([]);
|
||||
setPublishLocation(null);
|
||||
}}>
|
||||
<option value="">选择账号</option>
|
||||
{accounts.map(acc => <option key={acc.id} value={acc.id}>{accountName(acc.id)}</option>)}
|
||||
</select>
|
||||
@@ -866,6 +902,17 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="例如 8.00" value={publishForm.postage} onChange={e => setPublishForm({...publishForm, postage: e.target.value})} />
|
||||
</div>
|
||||
)}
|
||||
<div className="rounded-2xl border border-sky-200 bg-sky-50 p-4 space-y-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div><div className="text-sm font-extrabold text-gray-900">发货地(可选)</div><p className="mt-1 text-xs text-sky-800">虚拟商品无需发货地;发布失败时可再定位并作为补充信息提交。</p></div>
|
||||
<button type="button" disabled={locationLoading || !publishForm.cookie_id} onClick={() => void locateForPublish(false)} className="ios-btn-primary flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-bold disabled:opacity-50">
|
||||
<LocateFixed className="h-4 w-4" />{locationLoading ? '定位中...' : '获取当前位置'}
|
||||
</button>
|
||||
</div>
|
||||
{publishLocations.length > 0 && <select className="w-full ios-input rounded-xl bg-white px-4 py-3" value={String(Math.max(0, publishLocations.indexOf(publishLocation!)))} onChange={e => setPublishLocation(publishLocations[Number(e.target.value)] || null)}>
|
||||
{publishLocations.map((item, index) => <option key={`${item.division_id}-${item.poi_id}-${index}`} value={String(index)}>{[item.province, item.city, item.area, item.poi_name].filter(Boolean).join(' ')}</option>)}
|
||||
</select>}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700">商品图片(1-9 张)</label>
|
||||
<label className="flex min-h-[120px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-emerald-300 hover:bg-emerald-50/50 transition-colors">
|
||||
@@ -951,7 +998,11 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
<select
|
||||
className="w-full ios-input px-4 py-3 rounded-xl"
|
||||
value={selectedAccount}
|
||||
onChange={e => setSelectedAccount(e.target.value)}
|
||||
onChange={e => {
|
||||
setSelectedAccount(e.target.value);
|
||||
setBatchLocations([]);
|
||||
setBatchLocation(null);
|
||||
}}
|
||||
>
|
||||
<option value="">选择账号</option>
|
||||
{accounts.map(acc => <option key={acc.id} value={acc.id}>{accountName(acc.id)}</option>)}
|
||||
@@ -1012,6 +1063,18 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="rounded-xl border border-sky-200 bg-sky-50 p-4 space-y-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div><div className="text-sm font-extrabold text-gray-900">批次发货地(可选)</div><p className="mt-1 text-xs text-sky-800">虚拟商品可留空;填写后整个批次使用同一个发货地,并随任务保存用于恢复和重试。</p></div>
|
||||
<button type="button" disabled={locationLoading || !selectedAccount} onClick={() => void locateForPublish(true)} className="ios-btn-primary flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-bold disabled:opacity-50">
|
||||
<LocateFixed className="h-4 w-4" />{locationLoading ? '定位中...' : '获取当前位置'}
|
||||
</button>
|
||||
</div>
|
||||
{batchLocations.length > 0 && <select className="w-full ios-input rounded-xl bg-white px-4 py-3" value={String(Math.max(0, batchLocations.indexOf(batchLocation!)))} onChange={e => setBatchLocation(batchLocations[Number(e.target.value)] || null)}>
|
||||
{batchLocations.map((item, index) => <option key={`${item.division_id}-${item.poi_id}-${index}`} value={String(index)}>{[item.province, item.city, item.area, item.poi_name].filter(Boolean).join(' ')}</option>)}
|
||||
</select>}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<label className="flex min-h-[150px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-blue-300 hover:bg-blue-50 transition-colors">
|
||||
<UploadCloud className="w-9 h-9 text-blue-600 mb-3" />
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React from 'react';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import {
|
||||
Bell, Box, ChevronLeft, ChevronRight, CreditCard, LayoutDashboard,
|
||||
LogOut, MessageCircleMore, Settings, ShoppingBag, Users, Zap,
|
||||
GitCommitHorizontal, LogOut, MessageCircleMore, Settings, ShoppingBag, Users, Zap,
|
||||
} from 'lucide-react';
|
||||
import { YdisksBrandIcon } from './YdisksLogo';
|
||||
|
||||
@@ -14,9 +14,30 @@ interface SidebarProps {
|
||||
onLogout: () => void;
|
||||
}
|
||||
|
||||
interface BuildInfo {
|
||||
version: string;
|
||||
commit: string;
|
||||
}
|
||||
|
||||
const Sidebar: React.FC<SidebarProps> = ({
|
||||
activeTab, isAdmin = false, collapsed, onToggleCollapsed, onNavigate, onLogout,
|
||||
}) => {
|
||||
const [buildInfo, setBuildInfo] = useState<BuildInfo>({ version: 'dev', commit: 'unknown' });
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
fetch('/health', { signal: controller.signal })
|
||||
.then(response => response.ok ? response.json() : Promise.reject(new Error('health request failed')))
|
||||
.then(data => setBuildInfo({
|
||||
version: String(data.version || 'dev'),
|
||||
commit: String(data.commit || 'unknown'),
|
||||
}))
|
||||
.catch(error => {
|
||||
if (error instanceof DOMException && error.name === 'AbortError') return;
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, []);
|
||||
|
||||
const menuItems = [
|
||||
{ id: 'dashboard', icon: LayoutDashboard, label: '仪表盘' },
|
||||
{ id: 'accounts', icon: Users, label: '账号管理' },
|
||||
@@ -28,6 +49,9 @@ const Sidebar: React.FC<SidebarProps> = ({
|
||||
{ id: 'notifications', icon: Bell, label: '通知设置' },
|
||||
...(isAdmin ? [{ id: 'settings', icon: Settings, label: '系统与AI' }] : []),
|
||||
];
|
||||
const displayVersion = /^\d+\.\d+\.\d+$/.test(buildInfo.version)
|
||||
? `v${buildInfo.version}`
|
||||
: buildInfo.version;
|
||||
|
||||
return (
|
||||
<aside className={`fixed inset-y-0 left-0 z-20 flex flex-col border-r border-slate-200/80 bg-white/95 shadow-sidebar backdrop-blur-xl transition-[width] duration-300 ${collapsed ? 'w-16' : 'w-64'}`}>
|
||||
@@ -41,13 +65,13 @@ const Sidebar: React.FC<SidebarProps> = ({
|
||||
)}
|
||||
</div>
|
||||
|
||||
<nav className={`flex-1 space-y-1.5 overflow-y-auto py-5 ${collapsed ? 'px-2' : 'px-3'}`} aria-label="主导航">
|
||||
<nav className={`flex-1 space-y-1.5 overflow-y-auto pt-5 ${collapsed ? 'px-2' : 'px-3'}`} aria-label="主导航">
|
||||
{menuItems.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const active = activeTab === item.id;
|
||||
return (
|
||||
<button
|
||||
key={item.id}
|
||||
<React.Fragment key={item.id}>
|
||||
<button
|
||||
type="button"
|
||||
title={collapsed ? item.label : undefined}
|
||||
aria-label={item.label}
|
||||
@@ -62,32 +86,54 @@ const Sidebar: React.FC<SidebarProps> = ({
|
||||
<Icon className={`h-[19px] w-[19px] shrink-0 ${active ? 'text-white' : 'text-slate-400 group-hover:text-slate-700'}`} />
|
||||
{!collapsed && <span className="truncate text-sm font-bold">{item.label}</span>}
|
||||
{active && !collapsed && <span className="ml-auto h-1.5 w-1.5 rounded-full bg-white/90" />}
|
||||
</button>
|
||||
</button>
|
||||
</React.Fragment>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
|
||||
<div className={`space-y-2 border-t border-slate-100 p-2 ${collapsed ? '' : 'p-3'}`}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToggleCollapsed}
|
||||
title={collapsed ? '展开侧边栏' : '收起侧边栏'}
|
||||
aria-label={collapsed ? '展开侧边栏' : '收起侧边栏'}
|
||||
className={`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-slate-100 hover:text-slate-900 ${collapsed ? 'justify-center' : 'gap-3 px-3'}`}
|
||||
<div>
|
||||
<div
|
||||
title={collapsed ? `版本 ${buildInfo.version} · ${buildInfo.commit}` : undefined}
|
||||
className={`border-y border-slate-100 bg-slate-50/70 py-2.5 ${collapsed ? 'flex justify-center px-1' : 'px-6'}`}
|
||||
>
|
||||
{collapsed ? <ChevronRight className="h-5 w-5" /> : <ChevronLeft className="h-5 w-5" />}
|
||||
{!collapsed && <span className="text-sm font-bold">收起侧边栏</span>}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onLogout}
|
||||
title={collapsed ? '退出登录' : undefined}
|
||||
aria-label="退出登录"
|
||||
className={`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-red-50 hover:text-red-600 ${collapsed ? 'justify-center' : 'gap-3 px-3'}`}
|
||||
>
|
||||
<LogOut className="h-5 w-5" />
|
||||
{!collapsed && <span className="text-sm font-bold">退出登录</span>}
|
||||
</button>
|
||||
{collapsed ? (
|
||||
<GitCommitHorizontal className="h-[18px] w-[18px] text-slate-400" aria-label={`版本 ${buildInfo.version}`} />
|
||||
) : (
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2 text-[10px] font-extrabold uppercase tracking-[0.18em] text-slate-400">
|
||||
<GitCommitHorizontal className="h-3.5 w-3.5" />
|
||||
运行版本
|
||||
</div>
|
||||
<div className="mt-1 flex items-baseline gap-2">
|
||||
<span className="truncate font-mono text-xs font-bold text-slate-700">{displayVersion}</span>
|
||||
<span className="truncate font-mono text-[10px] text-slate-400">{buildInfo.commit}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className={`space-y-2 p-2 ${collapsed ? '' : 'p-3'}`}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToggleCollapsed}
|
||||
title={collapsed ? '展开侧边栏' : '收起侧边栏'}
|
||||
aria-label={collapsed ? '展开侧边栏' : '收起侧边栏'}
|
||||
className={`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-slate-100 hover:text-slate-900 ${collapsed ? 'justify-center' : 'gap-3 px-3'}`}
|
||||
>
|
||||
{collapsed ? <ChevronRight className="h-5 w-5" /> : <ChevronLeft className="h-5 w-5" />}
|
||||
{!collapsed && <span className="text-sm font-bold">收起侧边栏</span>}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onLogout}
|
||||
title={collapsed ? '退出登录' : undefined}
|
||||
aria-label="退出登录"
|
||||
className={`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-red-50 hover:text-red-600 ${collapsed ? 'justify-center' : 'gap-3 px-3'}`}
|
||||
>
|
||||
<LogOut className="h-5 w-5" />
|
||||
{!collapsed && <span className="text-sm font-bold">退出登录</span>}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
|
||||
@@ -36,7 +36,7 @@ describe('frontend navigation routing', () => {
|
||||
test('logout button invalidates the backend session before clearing UI state', () => {
|
||||
const app = readFrontendFile('App.tsx');
|
||||
|
||||
expect(app).toContain('import { login, logout, verifySession }');
|
||||
expect(app).toContain('import { initializeAdmin, login, logout, verifySession }');
|
||||
expect(app).toContain('await logout();');
|
||||
expect(app).toContain('onLogout={handleLogout}');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import { amapPOIToPublishLocation } from './amapLocation';
|
||||
|
||||
test('maps AMap POI fields to the publish location shape', () => {
|
||||
expect(amapPOIToPublishLocation({
|
||||
id: 'B000A74398',
|
||||
name: '人民广场',
|
||||
address: '人民大道',
|
||||
adname: '黄浦区',
|
||||
cityname: '上海市',
|
||||
adcode: '310101',
|
||||
pname: '上海市',
|
||||
location: { lng: 121.4737, lat: 31.2304 },
|
||||
})).toEqual({
|
||||
area: '黄浦区',
|
||||
city: '上海市',
|
||||
division_id: '310101',
|
||||
longitude: 121.4737,
|
||||
latitude: 31.2304,
|
||||
poi_id: 'B000A74398',
|
||||
poi_name: '人民广场',
|
||||
province: '上海市',
|
||||
});
|
||||
});
|
||||
|
||||
test('drops incomplete or invalid AMap POIs', () => {
|
||||
expect(amapPOIToPublishLocation({
|
||||
id: 'poi',
|
||||
name: '无坐标',
|
||||
adcode: '310101',
|
||||
pname: '上海市',
|
||||
cityname: '上海市',
|
||||
location: { lng: 0, lat: 31.2 },
|
||||
})).toBeNull();
|
||||
});
|
||||
@@ -0,0 +1,153 @@
|
||||
import type { PublishLocation } from './api';
|
||||
|
||||
const AMAP_SCRIPT_ID = 'ydisks-amap-js-api';
|
||||
// 高德 JS API 的 Key 是前端公开 Key;部署时可通过 VITE_AMAP_JS_KEY 覆盖。
|
||||
const DEFAULT_AMAP_JS_KEY = 'c9b68d4ce9a2a97f22a4a439404488ca';
|
||||
|
||||
export interface AMapLocationValue {
|
||||
lng: number;
|
||||
lat: number;
|
||||
}
|
||||
|
||||
export interface AMapPOI {
|
||||
id?: string;
|
||||
name?: string;
|
||||
address?: string;
|
||||
adname?: string;
|
||||
cityname?: string;
|
||||
adcode?: string | number;
|
||||
pname?: string;
|
||||
location?: AMapLocationValue;
|
||||
}
|
||||
|
||||
interface AMapPlaceSearchResult {
|
||||
poiList?: {
|
||||
pois?: AMapPOI[];
|
||||
};
|
||||
}
|
||||
|
||||
interface AMapPlaceSearch {
|
||||
searchNearBy(
|
||||
keyword: string,
|
||||
center: [number, number],
|
||||
radius: number,
|
||||
callback: (status: string, result: AMapPlaceSearchResult) => void,
|
||||
): void;
|
||||
}
|
||||
|
||||
interface AMapAPI {
|
||||
PlaceSearch: new (options: { extensions: 'all'; pageSize: number }) => AMapPlaceSearch;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
AMap?: AMapAPI;
|
||||
__ydisksAmapLoaded?: () => void;
|
||||
}
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_AMAP_JS_KEY?: string;
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
readonly env: ImportMetaEnv;
|
||||
}
|
||||
}
|
||||
|
||||
let amapLoadPromise: Promise<AMapAPI> | null = null;
|
||||
|
||||
const configuredAmapKey = (): string => {
|
||||
const key = import.meta.env.VITE_AMAP_JS_KEY?.trim();
|
||||
return key || DEFAULT_AMAP_JS_KEY;
|
||||
};
|
||||
|
||||
const loadAMap = (): Promise<AMapAPI> => {
|
||||
if (window.AMap) return Promise.resolve(window.AMap);
|
||||
if (amapLoadPromise) return amapLoadPromise;
|
||||
|
||||
amapLoadPromise = new Promise<AMapAPI>((resolve, reject) => {
|
||||
const existing = document.getElementById(AMAP_SCRIPT_ID) as HTMLScriptElement | null;
|
||||
const script = existing || document.createElement('script');
|
||||
const cleanup = () => {
|
||||
window.__ydisksAmapLoaded = undefined;
|
||||
window.clearTimeout(timeout);
|
||||
};
|
||||
const finish = () => {
|
||||
if (window.AMap) {
|
||||
cleanup();
|
||||
resolve(window.AMap);
|
||||
} else {
|
||||
cleanup();
|
||||
reject(new Error('高德地图 API 加载完成但未找到 AMap 对象'));
|
||||
}
|
||||
};
|
||||
const timeout = window.setTimeout(() => {
|
||||
cleanup();
|
||||
reject(new Error('高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置'));
|
||||
}, 15_000);
|
||||
|
||||
window.__ydisksAmapLoaded = finish;
|
||||
script.id = AMAP_SCRIPT_ID;
|
||||
script.async = true;
|
||||
script.src = `https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(configuredAmapKey())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`;
|
||||
script.onerror = () => {
|
||||
cleanup();
|
||||
reject(new Error('高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置'));
|
||||
};
|
||||
if (!existing) document.head.appendChild(script);
|
||||
}).catch(error => {
|
||||
amapLoadPromise = null;
|
||||
throw error;
|
||||
});
|
||||
|
||||
return amapLoadPromise;
|
||||
};
|
||||
|
||||
const validCoordinate = (value: number): boolean => Number.isFinite(value) && value !== 0;
|
||||
|
||||
// 字段映射与闲鱼网页版发布页一致:adcode → divisionId,name → poi,pname/cityname/adname → 行政区。
|
||||
export const amapPOIToPublishLocation = (poi: AMapPOI): PublishLocation | null => {
|
||||
const longitude = Number(poi.location?.lng);
|
||||
const latitude = Number(poi.location?.lat);
|
||||
const location: PublishLocation = {
|
||||
area: String(poi.adname || '').trim(),
|
||||
city: String(poi.cityname || '').trim(),
|
||||
division_id: String(poi.adcode || '').trim(),
|
||||
longitude,
|
||||
latitude,
|
||||
poi_id: String(poi.id || '').trim(),
|
||||
poi_name: String(poi.name || '').trim(),
|
||||
province: String(poi.pname || '').trim(),
|
||||
};
|
||||
if (!location.division_id || !location.province || !location.city || !location.poi_id || !location.poi_name) {
|
||||
return null;
|
||||
}
|
||||
if (!validCoordinate(longitude) || !validCoordinate(latitude) || longitude < -180 || longitude > 180 || latitude < -90 || latitude > 90) {
|
||||
return null;
|
||||
}
|
||||
return location;
|
||||
};
|
||||
|
||||
export const getPublishLocations = async (longitude: number, latitude: number): Promise<PublishLocation[]> => {
|
||||
if (!validCoordinate(longitude) || !validCoordinate(latitude) || longitude < -180 || longitude > 180 || latitude < -90 || latitude > 90) {
|
||||
throw new Error('经纬度无效');
|
||||
}
|
||||
const amap = await loadAMap();
|
||||
return new Promise<PublishLocation[]>((resolve, reject) => {
|
||||
const placeSearch = new amap.PlaceSearch({ extensions: 'all', pageSize: 10 });
|
||||
placeSearch.searchNearBy('', [longitude, latitude], 1_000, (status, result) => {
|
||||
if (status !== 'complete') {
|
||||
if (status === 'no_data') {
|
||||
resolve([]);
|
||||
return;
|
||||
}
|
||||
reject(new Error('高德地图附近地址查询失败,请稍后重试'));
|
||||
return;
|
||||
}
|
||||
const locations = (result?.poiList?.pois || [])
|
||||
.map(amapPOIToPublishLocation)
|
||||
.filter((location): location is PublishLocation => location !== null);
|
||||
resolve(locations);
|
||||
});
|
||||
});
|
||||
};
|
||||
@@ -17,8 +17,9 @@ import {
|
||||
getShippingRules,
|
||||
getShippingRulesPage,
|
||||
getSystemSettings,
|
||||
getValidOrders,
|
||||
logout,
|
||||
getValidOrders,
|
||||
publishItem,
|
||||
logout,
|
||||
importOrders,
|
||||
passwordLogin,
|
||||
resolveAutomationRun,
|
||||
@@ -228,6 +229,22 @@ test('deleteItemPublishBatch removes an abandoned preview', async () => {
|
||||
}));
|
||||
});
|
||||
|
||||
test('publishItem allows virtual publishing without an optional location', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await publishItem({
|
||||
cookie_id: 'acc1',
|
||||
title: '虚拟商品',
|
||||
description: '',
|
||||
price: '12.50',
|
||||
quantity: 1,
|
||||
postage_mode: 'none',
|
||||
images: [],
|
||||
});
|
||||
const body = fetchMock.mock.calls[0][1].body as FormData;
|
||||
expect(body.get('location')).toBeNull();
|
||||
});
|
||||
|
||||
test('getItems normalizes multi-spec flags from backend values', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse([{
|
||||
cookie_id: 'cookie-1',
|
||||
|
||||
@@ -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');
|
||||
};
|
||||
@@ -159,8 +163,9 @@ export const getAccountRuntimeStatuses = async (options?: RequestControlOptions)
|
||||
return get('/cookies/runtime-status', undefined, options);
|
||||
};
|
||||
|
||||
export const generateQRLogin = async (options?: RequestControlOptions): Promise<{ success: boolean; session_id?: string; qr_code_url?: string }> => {
|
||||
return post('/qr-login/generate', undefined, options);
|
||||
export const generateQRLogin = async (options?: RequestControlOptions): Promise<{ success: boolean; session_id?: string; qr_code_url?: string; message?: string }> => {
|
||||
// 风控后匿名 token 接口可能超过通用的 30 秒请求窗口;后端总生成窗口为 2 分钟。
|
||||
return post('/qr-login/generate', undefined, { ...options, timeoutMs: options?.timeoutMs ?? 130_000 });
|
||||
};
|
||||
|
||||
export const checkQRLoginStatus = async (sessionId: string, signal?: AbortSignal): Promise<any> => {
|
||||
@@ -522,6 +527,7 @@ export const publishItem = async (form: {
|
||||
postage_mode: string;
|
||||
postage?: string;
|
||||
images: File[];
|
||||
location?: PublishLocation;
|
||||
}): Promise<any> => {
|
||||
const body = new FormData();
|
||||
body.set('cookie_id', form.cookie_id);
|
||||
@@ -532,12 +538,24 @@ export const publishItem = async (form: {
|
||||
body.set('quantity', String(form.quantity));
|
||||
body.set('postage_mode', form.postage_mode);
|
||||
body.set('postage', form.postage || '');
|
||||
if (form.location) body.set('location', JSON.stringify(form.location));
|
||||
for (const file of form.images) {
|
||||
body.append('images', file);
|
||||
}
|
||||
return postForm('/items/publish', body);
|
||||
}
|
||||
|
||||
export interface PublishLocation {
|
||||
area: string;
|
||||
city: string;
|
||||
division_id: string;
|
||||
longitude: number;
|
||||
latitude: number;
|
||||
poi_id: string;
|
||||
poi_name: string;
|
||||
province: string;
|
||||
}
|
||||
|
||||
export const recommendPublishCategory = async (cookieId: string, keyword: string): Promise<{
|
||||
success: boolean;
|
||||
category: {
|
||||
@@ -560,6 +578,7 @@ export const previewItemPublishBatch = async (form: {
|
||||
channelCatId?: string;
|
||||
tbCatId?: string;
|
||||
};
|
||||
location?: PublishLocation;
|
||||
}): Promise<any> => {
|
||||
const body = new FormData();
|
||||
body.set('file', form.file);
|
||||
@@ -569,6 +588,7 @@ export const previewItemPublishBatch = async (form: {
|
||||
body.set('fallback_category_name', form.fallbackCategory.catName);
|
||||
body.set('fallback_channel_category_id', form.fallbackCategory.channelCatId || '');
|
||||
body.set('fallback_tb_category_id', form.fallbackCategory.tbCatId || '');
|
||||
if (form.location) body.set('location', JSON.stringify(form.location));
|
||||
return postForm('/items/publish-batches/preview', body);
|
||||
}
|
||||
|
||||
|
||||
+27
-27
@@ -10,113 +10,113 @@ export default defineConfig({
|
||||
proxy: {
|
||||
// 代理API请求到后端
|
||||
'/api': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
ws: true,
|
||||
},
|
||||
// 代理其他后端请求
|
||||
'/cookies': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/account': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/qr-login': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/password-login': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/keywords': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/keywords-with-item-id': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/default-reply': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/items': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/cards': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/automation-rules': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/automation-issues': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/automation-runs': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/automation-pending-tasks': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/notification-channels': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/message-notifications': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/ai-reply-settings': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/ai-models': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/system-settings': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/user-settings': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/admin': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/analytics': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/login': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/verify': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/logout': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/change-password': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/health': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 |
@@ -159,6 +159,15 @@ func (m *Manager) Sender(cookieID string) (automation.MessageSender, bool) {
|
||||
return m.GetInstance(cookieID)
|
||||
}
|
||||
|
||||
// RecoverExpiredCredential 把任意上层 MTOP API 检测到的 Session 失效统一
|
||||
// 转交给账号 Handler 的协议续期流程。调用方必须先释放账号凭证锁。
|
||||
func (m *Manager) RecoverExpiredCredential(ctx context.Context, cookieID string) bool {
|
||||
if m == nil || m.handler == nil {
|
||||
return false
|
||||
}
|
||||
return m.handler.OnPasswordLoginRefresh(ctx, cookieID)
|
||||
}
|
||||
|
||||
// RuntimeStatuses 返回所有已启动账号的实时状态快照。
|
||||
func (m *Manager) RuntimeStatuses() map[string]engine.RuntimeStatus {
|
||||
m.mu.Lock()
|
||||
|
||||
@@ -276,7 +276,11 @@ func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cook
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
a.logger.Warn("token 风控滑块处理失败", "account", cookieID, "err", err)
|
||||
manualURL := browser.TokenCaptchaManualVerificationURL(err)
|
||||
if strings.TrimSpace(manualURL) == "" {
|
||||
manualURL = verificationURL
|
||||
}
|
||||
a.logger.Warn("token 风控滑块处理失败", "account", cookieID, "err", err, "verification_url", manualURL)
|
||||
if a.store != nil && a.store.RiskLogs != nil {
|
||||
_ = a.store.RiskLogs.Update(ctx, logID, db.RiskControlLog{
|
||||
ProcessingStatus: "failed",
|
||||
|
||||
@@ -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(首次登录静默升级)
|
||||
//
|
||||
|
||||
@@ -2,6 +2,7 @@ package automation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -45,14 +46,32 @@ func (c *Center) RunAccountTask(ctx context.Context, accountID, taskType string)
|
||||
if err != nil {
|
||||
return AccountTaskSummary{TaskType: taskType}, err
|
||||
}
|
||||
return c.runConfiguredAccountTask(ctx, settings, taskType)
|
||||
}
|
||||
|
||||
func (c *Center) runConfiguredAccountTask(ctx context.Context, settings db.AccountTaskSettings, taskType string) (AccountTaskSummary, error) {
|
||||
if blocked, err := c.accountTaskSessionBlocked(ctx, settings.CookieID); err != nil {
|
||||
return AccountTaskSummary{TaskType: taskType}, err
|
||||
} else if blocked {
|
||||
return AccountTaskSummary{TaskType: taskType, Skipped: 1, Message: "Session 已失效,等待续期或重新登录"},
|
||||
fmt.Errorf("账号 Session 已失效,已停止自动化 API 请求,等待续期或重新登录")
|
||||
}
|
||||
var (
|
||||
summary AccountTaskSummary
|
||||
err error
|
||||
)
|
||||
switch taskType {
|
||||
case TaskAutoRate:
|
||||
return c.runAutoRate(ctx, settings)
|
||||
summary, err = c.runAutoRate(ctx, settings)
|
||||
case TaskAutoPolish:
|
||||
return c.runAutoPolish(ctx, settings, beijingNow(), true)
|
||||
summary, err = c.runAutoPolish(ctx, settings, beijingNow(), true)
|
||||
default:
|
||||
return AccountTaskSummary{TaskType: taskType}, fmt.Errorf("不支持的账号任务: %s", taskType)
|
||||
}
|
||||
if err != nil && mtop.IsSessionExpiredErr(err) {
|
||||
err = c.recoverAccountTaskSession(ctx, settings.CookieID, err)
|
||||
}
|
||||
return summary, err
|
||||
}
|
||||
|
||||
func (c *Center) scanAccountTasks(ctx context.Context) {
|
||||
@@ -70,19 +89,70 @@ func (c *Center) scanAccountTasks(ctx context.Context) {
|
||||
if err != nil || !allowed {
|
||||
continue
|
||||
}
|
||||
if blocked, blockErr := c.accountTaskSessionBlocked(ctx, setting.CookieID); blockErr != nil || blocked {
|
||||
continue
|
||||
}
|
||||
if setting.AutoRateEnabled {
|
||||
if _, err := c.runAutoRate(ctx, setting); err != nil {
|
||||
if _, err := c.runConfiguredAccountTask(ctx, setting, TaskAutoRate); err != nil {
|
||||
c.logger.Warn("自动评价扫描失败", "account", setting.CookieID, "err", err)
|
||||
}
|
||||
}
|
||||
if setting.AutoPolishEnabled && polishDue(setting, now) {
|
||||
if _, err := c.runAutoPolish(ctx, setting, now, false); err != nil {
|
||||
c.logger.Warn("每日擦亮失败", "account", setting.CookieID, "err", err)
|
||||
if blocked, _ := c.accountTaskSessionBlocked(ctx, setting.CookieID); blocked {
|
||||
continue
|
||||
}
|
||||
_, taskErr := c.runAutoPolish(ctx, setting, now, false)
|
||||
if taskErr != nil && mtop.IsSessionExpiredErr(taskErr) {
|
||||
taskErr = c.recoverAccountTaskSession(ctx, setting.CookieID, taskErr)
|
||||
}
|
||||
if taskErr != nil {
|
||||
c.logger.Warn("每日擦亮失败", "account", setting.CookieID, "err", taskErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Center) recoverAccountTaskSession(ctx context.Context, accountID string, sessionErr error) error {
|
||||
fingerprint, fingerprintErr := c.accountCredentialFingerprint(ctx, accountID)
|
||||
if fingerprintErr == nil {
|
||||
c.sessionExpired.Store(accountID, fingerprint)
|
||||
}
|
||||
c.logger.Warn("自动化 API 检测到 Session 过期,停止后续请求并开始即时续期", "account", accountID, "err", sessionErr)
|
||||
if c.recoverer != nil && c.recoverer.RecoverExpiredCredential(ctx, accountID) {
|
||||
c.sessionExpired.Delete(accountID)
|
||||
return fmt.Errorf("%w;Session 续期成功,本次自动化已停止,下一轮将使用新凭证", sessionErr)
|
||||
}
|
||||
return fmt.Errorf("%w;已停止该账号自动化 API 请求,等待续期或重新登录", sessionErr)
|
||||
}
|
||||
|
||||
func (c *Center) accountTaskSessionBlocked(ctx context.Context, accountID string) (bool, error) {
|
||||
blockedFingerprint, ok := c.sessionExpired.Load(accountID)
|
||||
if !ok {
|
||||
return false, nil
|
||||
}
|
||||
current, err := c.accountCredentialFingerprint(ctx, accountID)
|
||||
if err != nil {
|
||||
return true, err
|
||||
}
|
||||
if current != blockedFingerprint.(string) {
|
||||
c.sessionExpired.Delete(accountID)
|
||||
return false, nil
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (c *Center) accountCredentialFingerprint(ctx context.Context, accountID string) (string, error) {
|
||||
detail, err := c.store.Cookies.GetDetails(ctx, accountID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if detail == nil {
|
||||
return "", db.ErrNotFound
|
||||
}
|
||||
sum := sha256.Sum256([]byte(detail.Value + "\x00" + detail.MetadataJSON))
|
||||
return fmt.Sprintf("%x", sum[:]), nil
|
||||
}
|
||||
|
||||
func (c *Center) runAutoRate(ctx context.Context, settings db.AccountTaskSettings) (AccountTaskSummary, error) {
|
||||
summary := AccountTaskSummary{TaskType: TaskAutoRate}
|
||||
if c.accountTasks == nil {
|
||||
@@ -125,6 +195,9 @@ func (c *Center) runAutoRate(ctx context.Context, settings db.AccountTaskSetting
|
||||
}
|
||||
_ = c.store.AccountTasks.FinishRun(ctx, runKey, "failed", 0, 1, message, time.Now().UTC().Add(10*time.Minute).Unix())
|
||||
summary.Failed++
|
||||
if mtop.IsSessionExpiredErr(rateErr) {
|
||||
return summary, rateErr
|
||||
}
|
||||
continue
|
||||
}
|
||||
current = c.persistTaskCookies(ctx, settings.CookieID, current, result.UpdatedCookies)
|
||||
@@ -178,6 +251,10 @@ func (c *Center) runAutoPolish(ctx context.Context, settings db.AccountTaskSetti
|
||||
if result != nil && result.Message != "" {
|
||||
lastError = result.Message
|
||||
}
|
||||
if mtop.IsSessionExpiredErr(polishErr) {
|
||||
_ = c.store.AccountTasks.FinishRun(ctx, runKey, "failed", summary.Success, summary.Failed, lastError, 0)
|
||||
return summary, polishErr
|
||||
}
|
||||
continue
|
||||
}
|
||||
current = c.persistTaskCookies(ctx, settings.CookieID, current, result.UpdatedCookies)
|
||||
|
||||
@@ -3,6 +3,7 @@ package automation
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -15,6 +16,8 @@ type fakeAccountTaskClient struct {
|
||||
rateCalls int
|
||||
polishCalls int
|
||||
pending []mtop.PendingRateOrder
|
||||
pendingErr error
|
||||
rateErr error
|
||||
items []mtop.ItemListItem
|
||||
fetchItemsErr error
|
||||
fetchPageSize int
|
||||
@@ -24,11 +27,17 @@ type fakeAccountTaskClient struct {
|
||||
|
||||
func (f *fakeAccountTaskClient) FetchPendingRateOrders(context.Context, string, int, int) (*mtop.PendingRateResult, error) {
|
||||
f.pendingCalls++
|
||||
if f.pendingErr != nil {
|
||||
return nil, f.pendingErr
|
||||
}
|
||||
return &mtop.PendingRateResult{Orders: f.pending}, nil
|
||||
}
|
||||
|
||||
func (f *fakeAccountTaskClient) RateBuyer(context.Context, string, string, string) (*mtop.AccountTaskResult, error) {
|
||||
f.rateCalls++
|
||||
if f.rateErr != nil {
|
||||
return nil, f.rateErr
|
||||
}
|
||||
return &mtop.AccountTaskResult{Success: true, Message: "ok"}, nil
|
||||
}
|
||||
|
||||
@@ -69,6 +78,72 @@ func TestAccountTaskRateIsOrderIdempotent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountTaskSessionExpiredRecoversOnceAndBlocksFurtherAPIRequests(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
sessionErr := &mtop.SessionExpiredError{API: "自动评价接口", Ret: []string{"FAIL_SYS_SESSION_EXPIRED::Session过期"}}
|
||||
client := &fakeAccountTaskClient{pendingErr: sessionErr}
|
||||
recoverer := &fakeCredentialRecoverer{store: store, fail: true}
|
||||
center := New(store, testSenderProvider{sender: &testSender{}}, nil)
|
||||
center.SetAccountTaskClient(client)
|
||||
center.SetOrderDetailFetcher(recoverer)
|
||||
if err := store.AccountTasks.Upsert(ctx, db.AccountTaskSettings{CookieID: "cid", AutoRateEnabled: true,
|
||||
RateContent: "交易愉快", PolishTime: "03:00"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := center.RunAccountTask(ctx, "cid", TaskAutoRate); err == nil || !mtop.IsSessionExpiredErr(err) {
|
||||
t.Fatalf("首次 session 失效应触发续期并返回原始分类错误: %v", err)
|
||||
}
|
||||
if client.pendingCalls != 1 || recoverer.calls != 1 {
|
||||
t.Fatalf("first calls: api=%d recover=%d want 1/1", client.pendingCalls, recoverer.calls)
|
||||
}
|
||||
if _, err := center.RunAccountTask(ctx, "cid", TaskAutoRate); err == nil || !strings.Contains(err.Error(), "已停止自动化 API 请求") {
|
||||
t.Fatalf("未更新凭证时应保持阻断: %v", err)
|
||||
}
|
||||
if client.pendingCalls != 1 || recoverer.calls != 1 {
|
||||
t.Fatalf("blocked run must not call API/recovery again: api=%d recover=%d", client.pendingCalls, recoverer.calls)
|
||||
}
|
||||
|
||||
if err := store.Cookies.UpdateValueExisting(ctx, "cid", "unb=1; _m_h5_tk=fresh_1; renewed=1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client.pendingErr = nil
|
||||
if _, err := center.RunAccountTask(ctx, "cid", TaskAutoRate); err != nil {
|
||||
t.Fatalf("凭证变化后应自动解除阻断: %v", err)
|
||||
}
|
||||
if client.pendingCalls != 2 {
|
||||
t.Fatalf("api calls after credential update=%d want 2", client.pendingCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountTaskStopsRemainingOrdersOnSessionExpired(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
sessionErr := &mtop.SessionExpiredError{API: "评价接口", Ret: []string{"FAIL_SYS_SESSION_EXPIRED::Session过期"}}
|
||||
client := &fakeAccountTaskClient{
|
||||
pending: []mtop.PendingRateOrder{{TradeID: "order-1"}, {TradeID: "order-2"}},
|
||||
rateErr: sessionErr,
|
||||
}
|
||||
recoverer := &fakeCredentialRecoverer{store: store, fail: true}
|
||||
center := New(store, testSenderProvider{sender: &testSender{}}, nil)
|
||||
center.SetAccountTaskClient(client)
|
||||
center.SetOrderDetailFetcher(recoverer)
|
||||
if err := store.AccountTasks.Upsert(ctx, db.AccountTaskSettings{CookieID: "cid", AutoRateEnabled: true,
|
||||
RateContent: "交易愉快", PolishTime: "03:00"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := center.RunAccountTask(ctx, "cid", TaskAutoRate); err == nil {
|
||||
t.Fatal("session expiry must be returned")
|
||||
}
|
||||
if client.rateCalls != 1 || recoverer.calls != 1 {
|
||||
t.Fatalf("remaining orders must stop immediately: rate=%d recover=%d", client.rateCalls, recoverer.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountTaskPolishRunsOncePerBeijingDay(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
|
||||
@@ -96,6 +96,9 @@ type Center struct {
|
||||
logger *slog.Logger
|
||||
cookieSrc func(context.Context, string) (string, error)
|
||||
cardLocks sync.Map
|
||||
// sessionExpired 保存检测到 Session 失效时的凭证指纹。在凭证续期或
|
||||
// 重新登录真正改变之前,账号任务不得再次调用任何 MTOP 业务接口。
|
||||
sessionExpired sync.Map
|
||||
}
|
||||
|
||||
// New 构造自动化中心。
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
"github.com/mxschmitt/playwright-go"
|
||||
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
)
|
||||
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
"github.com/mxschmitt/playwright-go"
|
||||
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
)
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
"github.com/mxschmitt/playwright-go"
|
||||
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
)
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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{
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
"github.com/mxschmitt/playwright-go"
|
||||
)
|
||||
|
||||
// loginFormSelectors 登录表单选择器,主页面和 iframe 中都要找。
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
"github.com/mxschmitt/playwright-go"
|
||||
|
||||
"xianyu-go/internal/logsafe"
|
||||
)
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
"github.com/mxschmitt/playwright-go"
|
||||
)
|
||||
|
||||
// sliderSelectors 按优先级排列的滑块相关选择器(移植自 xianyu_slider_stealth.py)。
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
"github.com/mxschmitt/playwright-go"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -30,6 +30,53 @@ type TokenCaptchaURLProvider func(ctx context.Context, currentCookies string) (u
|
||||
type tokenCaptchaEngineFunc func(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, provider TokenCaptchaURLProvider) (string, error)
|
||||
|
||||
var errTokenCaptchaURLExpired = errors.New("token 风控验证链接已过期")
|
||||
var errTokenCaptchaDirectPageError = errors.New("token 风控页面直接显示错误且没有可验证滑块")
|
||||
|
||||
// TokenCaptchaFailureError 保留自动验证失败时最后实际使用的完整验证地址,
|
||||
// 便于用户复制到本机浏览器中手动完成验证。
|
||||
type TokenCaptchaFailureError struct {
|
||||
VerificationURL string
|
||||
Cause error
|
||||
}
|
||||
|
||||
func (e *TokenCaptchaFailureError) Error() string {
|
||||
if e == nil {
|
||||
return ""
|
||||
}
|
||||
if e.Cause == nil {
|
||||
if strings.TrimSpace(e.VerificationURL) == "" {
|
||||
return "token 风控自动验证失败"
|
||||
}
|
||||
return fmt.Sprintf("token 风控自动验证失败;手动验证地址: %s", e.VerificationURL)
|
||||
}
|
||||
if strings.TrimSpace(e.VerificationURL) == "" {
|
||||
return e.Cause.Error()
|
||||
}
|
||||
return fmt.Sprintf("%v;手动验证地址: %s", e.Cause, e.VerificationURL)
|
||||
}
|
||||
|
||||
func (e *TokenCaptchaFailureError) Unwrap() error {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return e.Cause
|
||||
}
|
||||
|
||||
// TokenCaptchaManualVerificationURL 从自动验证失败中提取可供用户手动打开的完整地址。
|
||||
func TokenCaptchaManualVerificationURL(err error) string {
|
||||
var failure *TokenCaptchaFailureError
|
||||
if errors.As(err, &failure) {
|
||||
return failure.VerificationURL
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func tokenCaptchaFailure(err error, verificationURL string) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
return &TokenCaptchaFailureError{VerificationURL: strings.TrimSpace(verificationURL), Cause: err}
|
||||
}
|
||||
|
||||
// TokenCaptchaRecover solves a token-refresh captcha and returns cookies with x5sec merged in.
|
||||
func (m *Manager) TokenCaptchaRecover(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, provider TokenCaptchaURLProvider) (string, error) {
|
||||
@@ -77,8 +124,8 @@ func (m *Manager) TokenCaptchaRecoverWithEngine(ctx context.Context, cookieID, c
|
||||
primaryURL = freshURL
|
||||
}
|
||||
// An expired URL cannot be repaired by replaying it through the fallback.
|
||||
if errors.Is(primaryErr, errTokenCaptchaURLExpired) {
|
||||
return "", "", primaryErr
|
||||
if errors.Is(primaryErr, errTokenCaptchaURLExpired) || errors.Is(primaryErr, errTokenCaptchaDirectPageError) {
|
||||
return "", "", tokenCaptchaFailure(primaryErr, primaryURL)
|
||||
}
|
||||
|
||||
if realMouseRequested() {
|
||||
@@ -87,7 +134,7 @@ func (m *Manager) TokenCaptchaRecoverWithEngine(ctx context.Context, cookieID, c
|
||||
m.logger.Error("CAPTCHA_REAL_MOUSE 已开启但物理鼠标引擎不可用,回退备用滑块逻辑", "goos", runtime.GOOS)
|
||||
}
|
||||
if !drissionFallbackEnabled() {
|
||||
return "", "playwright", primaryErr
|
||||
return "", "playwright", tokenCaptchaFailure(primaryErr, primaryURL)
|
||||
}
|
||||
|
||||
fallbackURL := verificationURL
|
||||
@@ -121,7 +168,10 @@ func (m *Manager) TokenCaptchaRecoverWithEngine(ctx context.Context, cookieID, c
|
||||
if fallbackErr == nil {
|
||||
fallbackErr = fmt.Errorf("备用滑块引擎未获取到新的 x5sec Cookie")
|
||||
}
|
||||
return "", "", fmt.Errorf("Playwright 主引擎失败: %v;备用滑块引擎失败: %w", primaryErr, fallbackErr)
|
||||
return "", "", tokenCaptchaFailure(
|
||||
fmt.Errorf("Playwright 主引擎失败: %v;备用滑块引擎失败: %w", primaryErr, fallbackErr),
|
||||
fallbackURL,
|
||||
)
|
||||
}
|
||||
|
||||
func (m *Manager) tokenCaptchaPlaywrightRecover(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, _ TokenCaptchaURLProvider) (string, error) {
|
||||
@@ -176,6 +226,10 @@ func (m *Manager) tokenCaptchaPlaywrightRecover(ctx context.Context, cookieID, c
|
||||
if strings.Contains(content, "STATUS_BREAKPOINT") || strings.Contains(content, "崩溃") {
|
||||
return "", fmt.Errorf("token 风控验证页面崩溃")
|
||||
}
|
||||
if pageErr := tokenCaptchaDirectPageError(page); pageErr != nil {
|
||||
m.logger.Warn("token 风控页面没有可验证滑块,停止自动验证", "cookieID", cookieID, "err", pageErr)
|
||||
return "", pageErr
|
||||
}
|
||||
|
||||
scratch := isScratchCaptcha(content)
|
||||
if err := solveSliderStrict(page, scratch, m.logger, previousX5SecValues, browserDeadline); err != nil {
|
||||
@@ -255,6 +309,47 @@ func captchaURLExpired(content string) bool {
|
||||
return strings.Contains(content, "抱歉,页面访问出现了问题")
|
||||
}
|
||||
|
||||
func tokenCaptchaDirectPageError(page playwright.Page) error {
|
||||
if page == nil {
|
||||
return nil
|
||||
}
|
||||
if _, _, _, err := findSliderElements(page); err == nil {
|
||||
return nil
|
||||
}
|
||||
frames := append([]playwright.Frame{page.MainFrame()}, page.Frames()...)
|
||||
for _, frame := range frames {
|
||||
body, err := frame.QuerySelector("body")
|
||||
if err != nil || body == nil {
|
||||
continue
|
||||
}
|
||||
text, err := body.InnerText()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if tokenCaptchaDirectErrorText(text) {
|
||||
return fmt.Errorf("%w: %s", errTokenCaptchaDirectPageError, truncateSliderText(text))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func tokenCaptchaDirectErrorText(text string) bool {
|
||||
normalized := strings.ToLower(strings.Join(strings.Fields(text), " "))
|
||||
if normalized == "" {
|
||||
return false
|
||||
}
|
||||
for _, marker := range []string{
|
||||
"验证失败", "安全验证未通过", "请求失败", "加载失败", "系统繁忙", "服务异常", "网络异常",
|
||||
"页面异常", "页面出错", "发生错误", "请稍后重试", "something's wrong", "something went wrong",
|
||||
"please refresh and try again", "try again later",
|
||||
} {
|
||||
if strings.Contains(normalized, marker) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func waitForFreshX5SecCookie(ctx context.Context, reader browserCookieReader, previousValues map[string]struct{}, timeout, pollInterval time.Duration) (map[string]string, error) {
|
||||
if timeout <= 0 || pollInterval <= 0 {
|
||||
return nil, fmt.Errorf("等待 x5sec Cookie 的超时和轮询间隔必须大于 0")
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
"github.com/mxschmitt/playwright-go"
|
||||
)
|
||||
|
||||
var fallbackTrackSelectors = []string{
|
||||
@@ -112,6 +112,10 @@ func (m *Manager) tokenCaptchaCDPFallback(ctx context.Context, cookieID, cookieS
|
||||
if err := sleepUntil(ctx, deadline, secondsDuration(randomFloat(1, 3))); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if pageErr := tokenCaptchaDirectPageError(page); pageErr != nil {
|
||||
m.logger.Warn("备用滑块引擎页面没有可验证滑块,停止自动验证", "cookieID", cookieID, "err", pageErr)
|
||||
return "", pageErr
|
||||
}
|
||||
|
||||
for attempt := 0; attempt < 3; attempt++ {
|
||||
if err := contextDeadlineError(ctx, deadline); err != nil {
|
||||
|
||||
@@ -2,6 +2,7 @@ package browser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -11,7 +12,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
"github.com/mxschmitt/playwright-go"
|
||||
)
|
||||
|
||||
func TestReferencePlaywrightSliderBrowserIntegration(t *testing.T) {
|
||||
@@ -169,6 +170,43 @@ document.addEventListener('click', event => {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenCaptchaDirectErrorPageBrowserIntegration(t *testing.T) {
|
||||
if os.Getenv("RUN_BROWSER_INTEGRATION") != "1" {
|
||||
t.Skip("set RUN_BROWSER_INTEGRATION=1 to exercise direct-error page classification")
|
||||
}
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
_, _ = io.WriteString(w, `<!doctype html><html><head><title>验证码拦截</title></head><body>
|
||||
<div class="errloading">Oops... something's wrong. Please refresh and try again.(error:6T0DWd)</div>
|
||||
</body></html>`)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
m := NewManager(nil)
|
||||
defer m.Close()
|
||||
if err := m.init(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
browser, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{
|
||||
Headless: playwright.Bool(true),
|
||||
Args: chromiumLaunchArgs(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = browser.Close() }()
|
||||
page, err := browser.NewPage()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := page.Goto(server.URL+"/punish", playwright.PageGotoOptions{WaitUntil: playwright.WaitUntilStateDomcontentloaded}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := tokenCaptchaDirectPageError(page); !errors.Is(err, errTokenCaptchaDirectPageError) {
|
||||
t.Fatalf("无滑块错误页应停止自动验证: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenCaptchaCDPFallbackBrowserIntegration(t *testing.T) {
|
||||
if os.Getenv("RUN_BROWSER_INTEGRATION") != "1" {
|
||||
t.Skip("set RUN_BROWSER_INTEGRATION=1 to exercise the direct-CDP Chromium fallback")
|
||||
|
||||
@@ -3,6 +3,7 @@ package browser
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -77,6 +78,49 @@ func TestTokenCaptchaExpiredURLSkipsFallback(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenCaptchaDirectErrorPageSkipsFallbackAndKeepsManualURL(t *testing.T) {
|
||||
fallbackCalls := 0
|
||||
verificationURL := "https://h5api.m.goofish.com/punish?x5secdata=full-sensitive-value&action=captcha"
|
||||
m := &Manager{
|
||||
logger: slog.Default(),
|
||||
tokenCaptchaPrimaryFn: func(context.Context, string, string, string, bool, TokenCaptchaURLProvider) (string, error) {
|
||||
return "", fmt.Errorf("%w: Oops... something's wrong", errTokenCaptchaDirectPageError)
|
||||
},
|
||||
tokenCaptchaFallbackFn: func(context.Context, string, string, string, bool, TokenCaptchaURLProvider) (string, error) {
|
||||
fallbackCalls++
|
||||
return "", errors.New("must not run")
|
||||
},
|
||||
}
|
||||
_, engine, err := m.TokenCaptchaRecoverWithEngine(context.Background(), "cid", "unb=1", verificationURL, true, nil)
|
||||
if !errors.Is(err, errTokenCaptchaDirectPageError) || engine != "" || fallbackCalls != 0 {
|
||||
t.Fatalf("engine=%q fallback=%d err=%v", engine, fallbackCalls, err)
|
||||
}
|
||||
if got := TokenCaptchaManualVerificationURL(err); got != verificationURL || !strings.Contains(err.Error(), verificationURL) {
|
||||
t.Fatalf("manual URL=%q err=%v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenCaptchaSliderFailureReportsLatestFallbackURL(t *testing.T) {
|
||||
t.Setenv("CAPTCHA_DRISSIONPAGE_FALLBACK_ENABLED", "true")
|
||||
freshURL := "https://h5api.m.goofish.com/punish?x5secdata=latest-full-value&action=captcha"
|
||||
m := &Manager{
|
||||
logger: slog.Default(),
|
||||
tokenCaptchaPrimaryFn: func(context.Context, string, string, string, bool, TokenCaptchaURLProvider) (string, error) {
|
||||
return "", errors.New("slider failed three times")
|
||||
},
|
||||
tokenCaptchaFallbackFn: func(context.Context, string, string, string, bool, TokenCaptchaURLProvider) (string, error) {
|
||||
return "", errors.New("fallback slider failed three times")
|
||||
},
|
||||
}
|
||||
provider := func(context.Context, string) (string, bool, string, error) {
|
||||
return freshURL, false, "unb=1; _m_h5_tk=fresh", nil
|
||||
}
|
||||
_, _, err := m.TokenCaptchaRecoverWithEngine(context.Background(), "cid", "unb=1", "https://old.example/punish", true, provider)
|
||||
if err == nil || TokenCaptchaManualVerificationURL(err) != freshURL || !strings.Contains(err.Error(), freshURL) {
|
||||
t.Fatalf("err=%v manual=%q", err, TokenCaptchaManualVerificationURL(err))
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenCaptchaExpiredURLRefreshesAfterPrimaryCloses(t *testing.T) {
|
||||
primaryCalls := 0
|
||||
providerCalls := 0
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
"github.com/mxschmitt/playwright-go"
|
||||
)
|
||||
|
||||
type cookieReadResult struct {
|
||||
@@ -140,3 +140,20 @@ func TestX5SecValuesCollectsAllDomains(t *testing.T) {
|
||||
t.Fatal("缺少 two")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenCaptchaDirectErrorTextRequiresAnErrorPrompt(t *testing.T) {
|
||||
for _, text := range []string{
|
||||
"验证失败,点击框体重试(error:YzRQd)",
|
||||
"Oops... something's wrong. Please refresh and try again.(error:6T0DWd)",
|
||||
"系统繁忙,请稍后重试",
|
||||
} {
|
||||
if !tokenCaptchaDirectErrorText(text) {
|
||||
t.Fatalf("应识别无滑块错误提示 %q", text)
|
||||
}
|
||||
}
|
||||
for _, text := range []string{"请按住滑块,拖动到最右边", "验证码加载中,请稍候", "验证码拦截"} {
|
||||
if tokenCaptchaDirectErrorText(text) {
|
||||
t.Fatalf("正常滑块提示不应识别为错误页 %q", text)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@ type ItemPublishBatch struct {
|
||||
DefaultCookieID string // 默认发布账号(明细行未指定账号时回退到此)
|
||||
Filename string // 原始上传文件名
|
||||
UploadDir string // 图片资源目录(发布时读取商品图片的根目录)
|
||||
LocationJSON string // 批次统一使用的发货地 JSON
|
||||
Status string // 批次状态:pending/running/completed/partially_failed/failed
|
||||
TotalCount int // 明细行总数(Recount 维护)
|
||||
SuccessCount int // 成功数(Recount 维护)
|
||||
@@ -66,6 +67,9 @@ type ItemPublishBatchRow struct {
|
||||
// 明细行的 quantity/postage_mode/status/images_json/raw_json/automation_json 缺省值在此补齐。
|
||||
// total_count 取 len(rows),success/failed 初始为 0。
|
||||
func (b *ItemPublishBatches) Create(ctx context.Context, batch *ItemPublishBatch, rows []ItemPublishBatchRow) error {
|
||||
if strings.TrimSpace(batch.LocationJSON) == "" {
|
||||
batch.LocationJSON = "{}"
|
||||
}
|
||||
tx, err := b.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -73,10 +77,10 @@ func (b *ItemPublishBatches) Create(ctx context.Context, batch *ItemPublishBatch
|
||||
defer tx.Rollback()
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO item_publish_batches
|
||||
(id,user_id,default_cookie_id,filename,upload_dir,status,total_count,success_count,failed_count)
|
||||
VALUES (?,?,?,?,?,?,?,?,?)`,
|
||||
(id,user_id,default_cookie_id,filename,upload_dir,location_json,status,total_count,success_count,failed_count)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?)`,
|
||||
batch.ID, batch.UserID, batch.DefaultCookieID, batch.Filename, batch.UploadDir,
|
||||
batch.Status, len(rows), 0, 0); err != nil {
|
||||
batch.LocationJSON, batch.Status, len(rows), 0, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, row := range rows {
|
||||
@@ -119,11 +123,11 @@ func (b *ItemPublishBatches) Create(ctx context.Context, batch *ItemPublishBatch
|
||||
func (b *ItemPublishBatches) Get(ctx context.Context, userID int64, id string) (*ItemPublishBatch, error) {
|
||||
var out ItemPublishBatch
|
||||
err := b.DB.QueryRowContext(ctx,
|
||||
`SELECT id,user_id,default_cookie_id,filename,upload_dir,status,total_count,success_count,failed_count,
|
||||
`SELECT id,user_id,default_cookie_id,filename,upload_dir,COALESCE(location_json,'{}'),status,total_count,success_count,failed_count,
|
||||
COALESCE(worker_token,''),COALESCE(lease_expires_at,0),
|
||||
created_at,updated_at
|
||||
FROM item_publish_batches WHERE id=? AND user_id=?`, id, userID).Scan(
|
||||
&out.ID, &out.UserID, &out.DefaultCookieID, &out.Filename, &out.UploadDir, &out.Status,
|
||||
&out.ID, &out.UserID, &out.DefaultCookieID, &out.Filename, &out.UploadDir, &out.LocationJSON, &out.Status,
|
||||
&out.TotalCount, &out.SuccessCount, &out.FailedCount, &out.WorkerToken, &out.LeaseExpiresAt,
|
||||
&out.CreatedAt, &out.UpdatedAt)
|
||||
if err != nil {
|
||||
@@ -140,7 +144,7 @@ func (b *ItemPublishBatches) ListForUser(ctx context.Context, userID int64, limi
|
||||
if limit <= 0 || limit > 100 {
|
||||
limit = 20
|
||||
}
|
||||
rows, err := b.DB.QueryContext(ctx, `SELECT id,user_id,default_cookie_id,filename,upload_dir,status,
|
||||
rows, err := b.DB.QueryContext(ctx, `SELECT id,user_id,default_cookie_id,filename,upload_dir,COALESCE(location_json,'{}'),status,
|
||||
total_count,success_count,failed_count,COALESCE(worker_token,''),COALESCE(lease_expires_at,0),created_at,updated_at
|
||||
FROM item_publish_batches WHERE user_id=? ORDER BY created_at DESC,id DESC LIMIT ?`, userID, limit)
|
||||
if err != nil {
|
||||
@@ -150,7 +154,7 @@ func (b *ItemPublishBatches) ListForUser(ctx context.Context, userID int64, limi
|
||||
var out []ItemPublishBatch
|
||||
for rows.Next() {
|
||||
var batch ItemPublishBatch
|
||||
if err := rows.Scan(&batch.ID, &batch.UserID, &batch.DefaultCookieID, &batch.Filename, &batch.UploadDir,
|
||||
if err := rows.Scan(&batch.ID, &batch.UserID, &batch.DefaultCookieID, &batch.Filename, &batch.UploadDir, &batch.LocationJSON,
|
||||
&batch.Status, &batch.TotalCount, &batch.SuccessCount, &batch.FailedCount, &batch.WorkerToken,
|
||||
&batch.LeaseExpiresAt, &batch.CreatedAt, &batch.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
@@ -165,7 +169,7 @@ func (b *ItemPublishBatches) Recoverable(ctx context.Context, now int64, limit i
|
||||
if limit <= 0 {
|
||||
limit = 20
|
||||
}
|
||||
rows, err := b.DB.QueryContext(ctx, `SELECT id,user_id,default_cookie_id,filename,upload_dir,status,
|
||||
rows, err := b.DB.QueryContext(ctx, `SELECT id,user_id,default_cookie_id,filename,upload_dir,COALESCE(location_json,'{}'),status,
|
||||
total_count,success_count,failed_count,COALESCE(worker_token,''),COALESCE(lease_expires_at,0),created_at,updated_at
|
||||
FROM item_publish_batches b
|
||||
WHERE (b.status IN ('running','canceling') AND (b.lease_expires_at=0 OR b.lease_expires_at<?))
|
||||
@@ -179,7 +183,7 @@ func (b *ItemPublishBatches) Recoverable(ctx context.Context, now int64, limit i
|
||||
var out []ItemPublishBatch
|
||||
for rows.Next() {
|
||||
var batch ItemPublishBatch
|
||||
if err := rows.Scan(&batch.ID, &batch.UserID, &batch.DefaultCookieID, &batch.Filename, &batch.UploadDir,
|
||||
if err := rows.Scan(&batch.ID, &batch.UserID, &batch.DefaultCookieID, &batch.Filename, &batch.UploadDir, &batch.LocationJSON,
|
||||
&batch.Status, &batch.TotalCount, &batch.SuccessCount, &batch.FailedCount, &batch.WorkerToken,
|
||||
&batch.LeaseExpiresAt, &batch.CreatedAt, &batch.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -129,7 +129,7 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
|
||||
}
|
||||
goose.SetBaseFS(migrationsFS)
|
||||
// 依次回滚最新版本到 13,再整体升级。
|
||||
for i := 0; i < 14; i++ {
|
||||
for i := 0; i < 15; i++ {
|
||||
if err := goose.Down(d, "migrations/sqlite"); err != nil {
|
||||
t.Fatalf("down migration #%d: %v", i+1, err)
|
||||
}
|
||||
@@ -155,6 +155,9 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
|
||||
if columnExists(t, d, "orders", "deleted_at") {
|
||||
t.Fatal("orders.deleted_at should be removed after migration 27 down")
|
||||
}
|
||||
if columnExists(t, d, "item_publish_batches", "location_json") {
|
||||
t.Fatal("item_publish_batches.location_json should be removed after migration 28 down")
|
||||
}
|
||||
for _, table := range []string{"account_task_settings", "account_task_runs", "chat_sessions", "chat_messages"} {
|
||||
if tableExists(t, d, table) {
|
||||
t.Fatalf("table should be removed after migration 24 down: %s", table)
|
||||
@@ -178,6 +181,7 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
|
||||
{"default_reply_records", "text_sent"},
|
||||
{"account_tokens", "cookie_fingerprint"},
|
||||
{"item_publish_batch_rows", "category_json"},
|
||||
{"item_publish_batches", "location_json"},
|
||||
{"account_task_settings", "auto_rate_enabled"},
|
||||
{"account_task_runs", "run_key"},
|
||||
{"chat_sessions", "unread_count"},
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE item_publish_batches ADD COLUMN location_json LONGTEXT NULL;
|
||||
UPDATE item_publish_batches SET location_json='{}' WHERE location_json IS NULL;
|
||||
ALTER TABLE item_publish_batches MODIFY COLUMN location_json LONGTEXT NOT NULL;
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE item_publish_batches DROP COLUMN location_json;
|
||||
@@ -0,0 +1,5 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE item_publish_batches ADD COLUMN location_json TEXT NOT NULL DEFAULT '{}';
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE item_publish_batches DROP COLUMN location_json;
|
||||
@@ -0,0 +1,5 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE item_publish_batches ADD COLUMN location_json TEXT NOT NULL DEFAULT '{}';
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE item_publish_batches DROP COLUMN location_json;
|
||||
@@ -771,7 +771,7 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) {
|
||||
t.Fatalf("set goose dialect: %v", err)
|
||||
}
|
||||
goose.SetBaseFS(migrationsFS)
|
||||
for i := 0; i < 14; i++ {
|
||||
for i := 0; i < 15; i++ {
|
||||
if err := goose.Down(tg.store.DB, "migrations/"+subdir); err != nil {
|
||||
t.Fatalf("migration down #%d: %v", i+1, err)
|
||||
}
|
||||
@@ -791,6 +791,9 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) {
|
||||
if columnExistsForDialect(t, tg.store.DB, tg.dialect, "item_publish_batch_rows", "category_json") {
|
||||
t.Fatal("item_publish_batch_rows.category_json should be removed after down")
|
||||
}
|
||||
if columnExistsForDialect(t, tg.store.DB, tg.dialect, "item_publish_batches", "location_json") {
|
||||
t.Fatal("item_publish_batches.location_json should be removed after down")
|
||||
}
|
||||
for _, table := range []string{"account_task_settings", "account_task_runs", "chat_sessions", "chat_messages"} {
|
||||
if tableExistsForDialect(t, tg.store.DB, tg.dialect, table) {
|
||||
t.Fatalf("table should be removed after migration 24 down: %s", table)
|
||||
@@ -816,6 +819,7 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) {
|
||||
{"automation_runs", "action_started"},
|
||||
{"account_tokens", "cookie_fingerprint"},
|
||||
{"item_publish_batch_rows", "category_json"},
|
||||
{"item_publish_batches", "location_json"},
|
||||
{"item_info", "deleted_at"},
|
||||
{"automation_rules", "deleted_at"},
|
||||
{"orders", "deleted_at"},
|
||||
|
||||
@@ -443,9 +443,19 @@ func (a *Account) Run(parent context.Context) error {
|
||||
return err
|
||||
}
|
||||
if mtop.IsSessionExpiredErr(err) {
|
||||
reason := "登录凭证已失效,请重新登录"
|
||||
a.logger.Warn("session 已失效,停止消息登录", "err", err)
|
||||
reason := "登录凭证已失效,正在立即续期"
|
||||
a.logger.Warn("token API 检测到 Session 过期,停止重试并开始即时续期", "err", err)
|
||||
a.clearTokenCache(ctx)
|
||||
a.setRuntimeState(RuntimeReconnecting, reason)
|
||||
a.notifyOffline(ctx, reason+":"+errString(err))
|
||||
if a.handler != nil && a.handler.OnPasswordLoginRefresh(ctx, a.CookieID) {
|
||||
a.reloadCookieFromDB(ctx)
|
||||
a.clearCurrentToken()
|
||||
a.resetFailures()
|
||||
a.setRuntimeState(RuntimeConnecting, "Session 续期成功,正在重新连接")
|
||||
continue
|
||||
}
|
||||
reason = "登录凭证已失效,自动续期失败,请重新扫码登录"
|
||||
a.setRuntimeState(RuntimeAuthExpired, reason)
|
||||
a.notifyOffline(ctx, reason+":"+errString(err))
|
||||
return err
|
||||
|
||||
@@ -188,8 +188,17 @@ func (s *Scheduler) executeLoginRenew(ctx context.Context) {
|
||||
func (s *Scheduler) loginRenewOne(ctx context.Context, batchID string, account db.RenewalAccount) {
|
||||
credentialUnlock := s.store.LockAccountCredentials(account.ID)
|
||||
credentialUpdated := false
|
||||
sessionExpired := false
|
||||
defer func() {
|
||||
credentialUnlock()
|
||||
if sessionExpired {
|
||||
s.logger.Warn("loginuser.get 检测到 Session 过期,开始即时续期", "account", account.ID)
|
||||
if s.refresher != nil && s.refresher.OnPasswordLoginRefresh(ctx, account.ID) {
|
||||
s.wakeCredentialBlockedAutomation(ctx, account.ID)
|
||||
s.restartAfterCredentialUpdate(ctx, account.ID, account.Enabled, "Session 即时续期")
|
||||
}
|
||||
return
|
||||
}
|
||||
if credentialUpdated {
|
||||
s.wakeCredentialBlockedAutomation(ctx, account.ID)
|
||||
s.restartAfterCredentialUpdate(ctx, account.ID, account.Enabled, "登录态续期")
|
||||
@@ -267,6 +276,9 @@ func (s *Scheduler) loginRenewOne(ctx context.Context, batchID string, account d
|
||||
if res.Status == mtop.LoginStatusSessionExpired || res.Status == mtop.LoginStatusTokenEmpty {
|
||||
s.markSessionExpired(account.ID)
|
||||
}
|
||||
if res.Status == mtop.LoginStatusSessionExpired {
|
||||
sessionExpired = true
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Scheduler) executeAPICookieRenew(ctx context.Context) {
|
||||
|
||||
@@ -400,6 +400,26 @@ func TestLoginRenewPreservesValidTokenCache(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginRenewSessionExpiredStartsImmediateRecovery(t *testing.T) {
|
||||
store, cleanup := newSchedulerTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
account := createSchedulerAccount(t, store, "cid-login-session-expired", "unb=1; _m_h5_tk=old_1")
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte(`{"ret":["FAIL_SYS_SESSION_EXPIRED::Session过期"],"data":{}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
refresher := &schedulerFakePasswordRefresher{}
|
||||
s := NewScheduler(store, nil, refresher, nil)
|
||||
s.mtop = &mtop.ClientImpl{HTTPClient: srv.Client(), LoginUserURL: srv.URL}
|
||||
|
||||
s.loginRenewOne(ctx, "batch-login-session-expired", account)
|
||||
|
||||
if got := refresher.calls.Load(); got != 1 {
|
||||
t.Fatalf("session 过期应在登录态检查返回后立即触发一次续期,calls=%d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginRenewPersistsAuthoritativeSessionBeforeParseError(t *testing.T) {
|
||||
store, cleanup := newSchedulerTestStore(t)
|
||||
defer cleanup()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -58,6 +58,8 @@ func (s *Server) listChatSessions(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
hasMore, nextCursor = page.HasMore, page.NextCursor
|
||||
} else {
|
||||
s.recoverExpiredMTOPSession(r.Context(), accountID, fetchErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -80,6 +82,8 @@ func (s *Server) listChatSessions(w http.ResponseWriter, r *http.Request) {
|
||||
defer resolveCancel()
|
||||
jobs := make(chan int)
|
||||
var workers sync.WaitGroup
|
||||
var sessionOnce sync.Once
|
||||
var sessionErr error
|
||||
for worker := 0; worker < 8; worker++ {
|
||||
workers.Add(1)
|
||||
go func() {
|
||||
@@ -88,6 +92,13 @@ func (s *Server) listChatSessions(w http.ResponseWriter, r *http.Request) {
|
||||
infoCtx, cancel := context.WithTimeout(resolveCtx, 3*time.Second)
|
||||
info, infoErr := client.FetchChatUserInfo(infoCtx, cookieValue, rows[index].ChatID)
|
||||
cancel()
|
||||
if mtop.IsSessionExpiredErr(infoErr) {
|
||||
sessionOnce.Do(func() {
|
||||
sessionErr = infoErr
|
||||
resolveCancel()
|
||||
})
|
||||
continue
|
||||
}
|
||||
if infoErr != nil || info == nil {
|
||||
continue
|
||||
}
|
||||
@@ -115,6 +126,9 @@ func (s *Server) listChatSessions(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
close(jobs)
|
||||
workers.Wait()
|
||||
if sessionErr != nil {
|
||||
s.recoverExpiredMTOPSession(r.Context(), accountID, sessionErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"sessions": rows, "has_more": hasMore, "next_cursor": nextCursor})
|
||||
@@ -283,6 +297,8 @@ func (s *Server) resolveSelectedChatIdentity(ctx context.Context, accountID stri
|
||||
if info.AvatarURL != "" {
|
||||
session.BuyerAvatar = info.AvatarURL
|
||||
}
|
||||
} else if err != nil {
|
||||
s.recoverExpiredMTOPSession(ctx, accountID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -839,6 +839,7 @@ func (s *Server) refreshAccountProfile(ctx context.Context, d *db.CookieDetail)
|
||||
s.updateRunningCookie(ctx, d.ID, runtimeCookie)
|
||||
}
|
||||
if callErr != nil {
|
||||
s.recoverExpiredMTOPSession(ctx, d.ID, callErr)
|
||||
if s.Logger != nil {
|
||||
s.Logger.Warn("刷新账号资料失败", "account", d.ID, "err", callErr)
|
||||
}
|
||||
|
||||
@@ -89,6 +89,15 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
var location mtop.PublishLocation
|
||||
var selectedLocation *mtop.PublishLocation
|
||||
if rawLocation := strings.TrimSpace(r.FormValue("location")); rawLocation != "" {
|
||||
if err := json.Unmarshal([]byte(rawLocation), &location); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "发货地格式错误,请重新定位")
|
||||
return
|
||||
}
|
||||
selectedLocation = &location
|
||||
}
|
||||
credentialUnlock := s.Store.LockAccountCredentials(cookieID)
|
||||
latest, err := s.Store.Cookies.GetDetails(r.Context(), cookieID)
|
||||
if err != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) {
|
||||
@@ -110,6 +119,7 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
|
||||
PostageMode: postageMode,
|
||||
PostageCents: postageCents,
|
||||
Virtual: true,
|
||||
Location: selectedLocation,
|
||||
Images: images,
|
||||
})
|
||||
runtimeCookie := ""
|
||||
@@ -141,6 +151,7 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
|
||||
if responseCookieErr != nil {
|
||||
callErr = errors.Join(callErr, fmt.Errorf("保存发布响应 Cookie: %w", responseCookieErr))
|
||||
}
|
||||
s.recoverExpiredMTOPSession(r.Context(), cookieID, callErr)
|
||||
var perr *mtop.PublishError
|
||||
if errors.As(callErr, &perr) {
|
||||
status := http.StatusBadGateway
|
||||
@@ -372,6 +383,7 @@ func (s *Server) syncItemsFromAccount(w http.ResponseWriter, r *http.Request) {
|
||||
} else if valueChanged {
|
||||
s.updateRunningCookie(r.Context(), req.CookieID, value)
|
||||
}
|
||||
s.recoverExpiredMTOPSession(r.Context(), req.CookieID, callErr)
|
||||
writeErr(w, http.StatusBadGateway, callErr.Error())
|
||||
return
|
||||
}
|
||||
@@ -379,7 +391,7 @@ func (s *Server) syncItemsFromAccount(w http.ResponseWriter, r *http.Request) {
|
||||
if res.UpdatedCookies != "" {
|
||||
detailCookies = res.UpdatedCookies
|
||||
}
|
||||
s.enrichSyncedItemMultiSpec(mtopCtx, client, detailCookies, req.CookieID, res.Items)
|
||||
detailErr := s.enrichSyncedItemMultiSpec(mtopCtx, client, detailCookies, req.CookieID, res.Items)
|
||||
runtimeCookie := ""
|
||||
runtimeCookieChanged := false
|
||||
value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
|
||||
@@ -408,6 +420,11 @@ func (s *Server) syncItemsFromAccount(w http.ResponseWriter, r *http.Request) {
|
||||
if runtimeCookieChanged {
|
||||
s.updateRunningCookie(r.Context(), req.CookieID, runtimeCookie)
|
||||
}
|
||||
if detailErr != nil {
|
||||
s.recoverExpiredMTOPSession(r.Context(), req.CookieID, detailErr)
|
||||
writeErr(w, http.StatusBadGateway, detailErr.Error())
|
||||
return
|
||||
}
|
||||
syncResult, syncErr := s.syncSyncedItems(r.Context(), req.CookieID, res.Items)
|
||||
if syncErr != nil {
|
||||
if s.Logger != nil {
|
||||
@@ -466,6 +483,7 @@ func (s *Server) syncItemsPageFromAccount(w http.ResponseWriter, r *http.Request
|
||||
} else if valueChanged {
|
||||
s.updateRunningCookie(r.Context(), req.CookieID, value)
|
||||
}
|
||||
s.recoverExpiredMTOPSession(r.Context(), req.CookieID, callErr)
|
||||
writeErr(w, http.StatusBadGateway, callErr.Error())
|
||||
return
|
||||
}
|
||||
@@ -473,7 +491,7 @@ func (s *Server) syncItemsPageFromAccount(w http.ResponseWriter, r *http.Request
|
||||
if res.UpdatedCookies != "" {
|
||||
detailCookies = res.UpdatedCookies
|
||||
}
|
||||
s.enrichSyncedItemMultiSpec(mtopCtx, client, detailCookies, req.CookieID, res.Items)
|
||||
detailErr := s.enrichSyncedItemMultiSpec(mtopCtx, client, detailCookies, req.CookieID, res.Items)
|
||||
runtimeCookie := ""
|
||||
runtimeCookieChanged := false
|
||||
value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
|
||||
@@ -502,6 +520,11 @@ func (s *Server) syncItemsPageFromAccount(w http.ResponseWriter, r *http.Request
|
||||
if runtimeCookieChanged {
|
||||
s.updateRunningCookie(r.Context(), req.CookieID, runtimeCookie)
|
||||
}
|
||||
if detailErr != nil {
|
||||
s.recoverExpiredMTOPSession(r.Context(), req.CookieID, detailErr)
|
||||
writeErr(w, http.StatusBadGateway, detailErr.Error())
|
||||
return
|
||||
}
|
||||
saved := s.saveSyncedItems(r.Context(), req.CookieID, res.Items)
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": true,
|
||||
@@ -582,10 +605,10 @@ func (s *Server) syncSyncedItems(ctx context.Context, cookieID string, items []m
|
||||
return s.Store.Items.SyncFromRemote(ctx, cookieID, rows)
|
||||
}
|
||||
|
||||
func (s *Server) enrichSyncedItemMultiSpec(ctx context.Context, client mtop.Client, cookies, cookieID string, items []mtop.ItemListItem) {
|
||||
func (s *Server) enrichSyncedItemMultiSpec(ctx context.Context, client mtop.Client, cookies, cookieID string, items []mtop.ItemListItem) error {
|
||||
fetcher, ok := client.(mtop.ItemDetailFetcher)
|
||||
if !ok {
|
||||
return
|
||||
return nil
|
||||
}
|
||||
for index := range items {
|
||||
if items[index].IsMultiSpec || s.Store.Items.IsMultiSpec(ctx, cookieID, items[index].ID) {
|
||||
@@ -594,6 +617,9 @@ func (s *Server) enrichSyncedItemMultiSpec(ctx context.Context, client mtop.Clie
|
||||
}
|
||||
isMultiSpec, err := fetcher.DetectItemMultiSpec(ctx, cookies, items[index].ID)
|
||||
if err != nil {
|
||||
if mtop.IsSessionExpiredErr(err) {
|
||||
return err
|
||||
}
|
||||
if s.Logger != nil {
|
||||
s.Logger.Warn("识别商品多规格状态失败", "cookie_id", cookieID, "item_id", items[index].ID, "err", err)
|
||||
}
|
||||
@@ -601,6 +627,7 @@ func (s *Server) enrichSyncedItemMultiSpec(ctx context.Context, client mtop.Clie
|
||||
}
|
||||
items[index].IsMultiSpec = isMultiSpec
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) listItemsByCookie(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -241,8 +241,6 @@ func TestPublishItemSuccess(t *testing.T) {
|
||||
switch {
|
||||
case strings.Contains(u, "stream-upload.goofish.com"):
|
||||
respBody = `{"object":{"url":"https://img.alicdn.com/published.png","pix":"800_800"}}`
|
||||
case strings.Contains(u, "mtop.taobao.idle.local.poi.get"):
|
||||
respBody = `{"ret":["SUCCESS::调用成功"],"data":{"commonAddresses":[{"address":"北京"}]}}`
|
||||
case strings.Contains(u, "mtop.taobao.idle.kgraph.property.recommend"):
|
||||
respBody = `{"ret":["SUCCESS::调用成功"],"data":{"categoryPredictResult":{"catId":"99","catName":"数码"}}}`
|
||||
case strings.Contains(u, "mtop.idle.pc.idleitem.publish"):
|
||||
@@ -330,8 +328,6 @@ func TestPublishItemStockPermissionMissing(t *testing.T) {
|
||||
switch {
|
||||
case strings.Contains(u, "stream-upload.goofish.com"):
|
||||
respBody = `{"object":{"url":"https://img.alicdn.com/published.png","pix":"800_800"}}`
|
||||
case strings.Contains(u, "mtop.taobao.idle.local.poi.get"):
|
||||
respBody = `{"ret":["SUCCESS::调用成功"],"data":{"commonAddresses":[{"address":"北京"}]}}`
|
||||
case strings.Contains(u, "mtop.taobao.idle.kgraph.property.recommend"):
|
||||
respBody = `{"ret":["SUCCESS::调用成功"],"data":{"categoryPredictResult":{"catId":"99","catName":"数码"}}}`
|
||||
case strings.Contains(u, "mtop.idle.pc.idleitem.publish"):
|
||||
|
||||
@@ -194,6 +194,15 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
|
||||
ChannelCatID: strings.TrimSpace(r.FormValue("fallback_channel_category_id")),
|
||||
TBCatID: strings.TrimSpace(r.FormValue("fallback_tb_category_id")),
|
||||
}
|
||||
var batchLocation mtop.PublishLocation
|
||||
locationJSON := strings.TrimSpace(r.FormValue("location"))
|
||||
if locationJSON != "" {
|
||||
if json.Unmarshal([]byte(locationJSON), &batchLocation) != nil {
|
||||
writeErr(w, http.StatusBadRequest, "发货地格式错误,请重新定位")
|
||||
return
|
||||
}
|
||||
}
|
||||
locationBytes, _ := json.Marshal(batchLocation)
|
||||
hasDefaultCategory := fallbackCategory.CatID != "" || fallbackCategory.CatName != "" || fallbackCategory.ChannelCatID != "" || fallbackCategory.TBCatID != ""
|
||||
if hasDefaultCategory && (fallbackCategory.CatID == "" || fallbackCategory.CatName == "" || fallbackCategory.ChannelCatID == "") {
|
||||
writeErr(w, http.StatusBadRequest, "默认类目信息不完整,请重新通过关键词获取")
|
||||
@@ -331,6 +340,7 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
|
||||
DefaultCookieID: defaultCookieID,
|
||||
Filename: sourceName,
|
||||
UploadDir: uploadDir,
|
||||
LocationJSON: string(locationBytes),
|
||||
Status: "preview",
|
||||
}, rows); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存预检结果失败")
|
||||
@@ -695,11 +705,12 @@ func (s *Server) runItemPublishBatch(ctx context.Context, userID int64, batchID,
|
||||
if !claimed {
|
||||
continue
|
||||
}
|
||||
if err := s.publishBatchRow(ctx, userID, client, row, workerToken); err != nil {
|
||||
if rowErr := s.publishBatchRow(ctx, userID, client, row, workerToken); rowErr != nil {
|
||||
sessionExpired := mtop.IsSessionExpiredErr(rowErr)
|
||||
statusCtx, statusCancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
status, _ := s.Store.PublishBatches.BatchStatus(statusCtx, batchID)
|
||||
statusCancel()
|
||||
message, failureKind := publishBatchFailure(err, status)
|
||||
message, failureKind := publishBatchFailure(rowErr, status)
|
||||
wctx, cancel := publishStatusContext(ctx)
|
||||
marked, markErr := s.Store.PublishBatches.MarkClaimedRowFailed(wctx, row.ID, workerToken, message, failureKind)
|
||||
cancel()
|
||||
@@ -709,6 +720,10 @@ func (s *Server) runItemPublishBatch(ctx context.Context, userID int64, batchID,
|
||||
}
|
||||
return
|
||||
}
|
||||
if sessionExpired {
|
||||
s.finishInterruptedPublishBatch(ctx, userID, batchID, workerToken)
|
||||
return
|
||||
}
|
||||
}
|
||||
wctx, cancel = publishStatusContext(ctx)
|
||||
if err := s.Store.PublishBatches.Recount(wctx, batchID); err != nil && s.Logger != nil {
|
||||
@@ -854,6 +869,18 @@ func (s *Server) publishBatchRow(ctx context.Context, userID int64, client mtop.
|
||||
if err != nil {
|
||||
return errors.New("批量任务不存在")
|
||||
}
|
||||
var location mtop.PublishLocation
|
||||
locationJSON := strings.TrimSpace(batch.LocationJSON)
|
||||
if locationJSON == "" {
|
||||
locationJSON = "{}"
|
||||
}
|
||||
if err := json.Unmarshal([]byte(locationJSON), &location); err != nil {
|
||||
return errors.New("批量任务发货地配置损坏,请重新创建任务")
|
||||
}
|
||||
var selectedLocation *mtop.PublishLocation
|
||||
if strings.TrimSpace(location.DivisionID) != "" {
|
||||
selectedLocation = &location
|
||||
}
|
||||
cookieValue, err := s.cookieValueForUser(ctx, userID, row.CookieID)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -919,6 +946,7 @@ func (s *Server) publishBatchRow(ctx context.Context, userID int64, client mtop.
|
||||
PostageMode: row.PostageMode,
|
||||
PostageCents: postageCents,
|
||||
Virtual: true,
|
||||
Location: selectedLocation,
|
||||
PreferredCategory: preferredCategory,
|
||||
Images: images,
|
||||
})
|
||||
@@ -954,6 +982,7 @@ func (s *Server) publishBatchRow(ctx context.Context, userID int64, client mtop.
|
||||
s.updateRunningCookie(ctx, row.CookieID, runtimeCookie)
|
||||
}
|
||||
if err != nil {
|
||||
s.recoverExpiredMTOPSession(ctx, row.CookieID, err)
|
||||
if ctx.Err() != nil {
|
||||
return &uncertainRemotePublishError{err: fmt.Errorf("取消时远端发布结果未知: %w", err)}
|
||||
}
|
||||
@@ -1308,6 +1337,10 @@ func (s *Server) validatePublishAutomation(ctx context.Context, userID int64, cf
|
||||
}
|
||||
|
||||
func publishBatchToMap(batch *db.ItemPublishBatch, rows []db.ItemPublishBatchRow) map[string]any {
|
||||
locationJSON := strings.TrimSpace(batch.LocationJSON)
|
||||
if locationJSON == "" {
|
||||
locationJSON = "{}"
|
||||
}
|
||||
outRows := make([]map[string]any, 0, len(rows))
|
||||
pending := 0
|
||||
running := 0
|
||||
@@ -1343,6 +1376,7 @@ func publishBatchToMap(batch *db.ItemPublishBatch, rows []db.ItemPublishBatchRow
|
||||
"id": batch.ID, "status": batch.Status, "filename": batch.Filename,
|
||||
"total": batch.TotalCount, "success": batch.SuccessCount, "failed": batch.FailedCount,
|
||||
"pending": pending, "running": running, "retryable": retryable, "rows": outRows,
|
||||
"location": json.RawMessage(locationJSON),
|
||||
"created_at": batch.CreatedAt, "updated_at": batch.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,6 +190,7 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
|
||||
discovered, listUpdated, softDeleted, failed := 0, 0, 0, 0
|
||||
results := []map[string]any{}
|
||||
newOrderIDs := make(map[string]struct{})
|
||||
sessionExpiredAccounts := make(map[string]struct{})
|
||||
if fetcher, ok := s.mtopClient().(mtop.SoldOrderFetcher); ok {
|
||||
for cid := range all {
|
||||
credentialUnlock := s.Store.LockAccountCredentials(cid)
|
||||
@@ -218,6 +219,10 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
|
||||
if persistErr == nil && valueChanged {
|
||||
s.updateRunningCookie(r.Context(), cid, value)
|
||||
}
|
||||
if mtop.IsSessionExpiredErr(discoveryErr) {
|
||||
sessionExpiredAccounts[cid] = struct{}{}
|
||||
s.recoverExpiredMTOPSession(r.Context(), cid, discoveryErr)
|
||||
}
|
||||
discovered += accountDiscovered
|
||||
listUpdated += accountUpdated
|
||||
for orderID := range accountNewIDs {
|
||||
@@ -250,6 +255,9 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
ordersByCookie := map[string][]refreshTarget{}
|
||||
for cid := range all {
|
||||
if _, blocked := sessionExpiredAccounts[cid]; blocked {
|
||||
continue
|
||||
}
|
||||
for offset := 0; ; offset += 500 {
|
||||
rows, err := s.Store.Orders.ByCookiePage(r.Context(), cid, 500, offset)
|
||||
if err != nil {
|
||||
@@ -312,6 +320,7 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
updated, noChange := 0, 0
|
||||
for cid, targets := range ordersByCookie {
|
||||
accountSessionExpired := false
|
||||
for _, chunk := range chunkRefreshTargets(targets, refreshOrderChunkSize) {
|
||||
credentialUnlock := s.Store.LockAccountCredentials(cid)
|
||||
latest, latestErr := s.Store.Cookies.GetDetails(r.Context(), cid)
|
||||
@@ -323,6 +332,7 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Minute)
|
||||
mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
|
||||
var sessionErr error
|
||||
for _, target := range chunk {
|
||||
detail, fetchErr := detailFetcher.FetchOrderDetail(mtopCtx, latest.Value, target.OrderID)
|
||||
if fetchErr != nil || detail == nil {
|
||||
@@ -336,6 +346,10 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
|
||||
"success": false,
|
||||
"error": message,
|
||||
})
|
||||
if mtop.IsSessionExpiredErr(fetchErr) {
|
||||
sessionErr = fetchErr
|
||||
break
|
||||
}
|
||||
continue
|
||||
}
|
||||
newStatus := db.NormalizeOrderStatus(detail.OrderStatus)
|
||||
@@ -377,6 +391,14 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
|
||||
} else if valueChanged {
|
||||
s.updateRunningCookie(r.Context(), cid, value)
|
||||
}
|
||||
if sessionErr != nil {
|
||||
s.recoverExpiredMTOPSession(r.Context(), cid, sessionErr)
|
||||
accountSessionExpired = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if accountSessionExpired {
|
||||
continue
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
@@ -544,6 +566,7 @@ func (s *Server) refreshSingleOrder(w http.ResponseWriter, r *http.Request) {
|
||||
s.updateRunningCookie(r.Context(), cookieID, runtimeCookie)
|
||||
}
|
||||
if callErr != nil {
|
||||
s.recoverExpiredMTOPSession(r.Context(), cookieID, callErr)
|
||||
writeErr(w, http.StatusBadGateway, callErr.Error())
|
||||
return
|
||||
}
|
||||
|
||||
@@ -311,8 +311,6 @@ func TestRunItemPublishBatch_Success(t *testing.T) {
|
||||
switch {
|
||||
case strings.Contains(u, "stream-upload.goofish.com"):
|
||||
body = `{"object":{"url":"https://img.alicdn.com/published.png","pix":"800_800"}}`
|
||||
case strings.Contains(u, "mtop.taobao.idle.local.poi.get"):
|
||||
body = `{"ret":["SUCCESS::调用成功"],"data":{"commonAddresses":[{"address":"北京"}]}}`
|
||||
case strings.Contains(u, "mtop.taobao.idle.kgraph.property.recommend"):
|
||||
body = `{"ret":["SUCCESS::调用成功"],"data":{}}`
|
||||
case strings.Contains(u, "mtop.idle.pc.idleitem.publish"):
|
||||
|
||||
@@ -16,6 +16,8 @@ import (
|
||||
"xianyu-go/internal/xianyu/protocol"
|
||||
)
|
||||
|
||||
const qrLoginGenerateTimeout = 2 * time.Minute
|
||||
|
||||
// mountQRLoginReal 扫码登录端点(纯 HTTP,不需要浏览器)。
|
||||
func (s *Server) mountQRLoginReal(r chi.Router) {
|
||||
r.Post("/qr-login/generate", s.generateQRLogin)
|
||||
@@ -32,12 +34,26 @@ func (s *Server) generateQRLogin(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
s.cleanupQRLoginSessions()
|
||||
sessionID, qrCodeURL, err := s.QRLogin.GenerateQRCode(r.Context())
|
||||
// 风控后的闲鱼匿名 token 接口偶尔会明显变慢。二维码生成需要连续完成
|
||||
// token、登录参数和二维码请求,不能沿用前端通用接口的短超时。
|
||||
generateCtx, cancel := context.WithTimeout(r.Context(), qrLoginGenerateTimeout)
|
||||
defer cancel()
|
||||
sessionID, qrCodeURL, err := s.QRLogin.GenerateQRCode(generateCtx)
|
||||
if err != nil {
|
||||
s.Logger.Error("生成二维码失败", "err", err)
|
||||
message := "生成二维码失败: " + err.Error()
|
||||
switch {
|
||||
case errors.Is(err, context.Canceled):
|
||||
s.Logger.Info("二维码生成请求已取消")
|
||||
message = "二维码生成请求已取消,请重新获取"
|
||||
case errors.Is(err, context.DeadlineExceeded):
|
||||
s.Logger.Error("生成二维码超时", "err", err)
|
||||
message = "闲鱼二维码接口响应超时,请稍后重新获取"
|
||||
default:
|
||||
s.Logger.Error("生成二维码失败", "err", err)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": false,
|
||||
"message": "生成二维码失败: " + err.Error(),
|
||||
"message": message,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -15,14 +15,16 @@ import (
|
||||
)
|
||||
|
||||
type fakeQRLoginService struct {
|
||||
status map[string]any
|
||||
generateErr error
|
||||
completeCookies string
|
||||
completeUNB string
|
||||
completeErr error
|
||||
status map[string]any
|
||||
generateErr error
|
||||
generateDeadline time.Time
|
||||
completeCookies string
|
||||
completeUNB string
|
||||
completeErr error
|
||||
}
|
||||
|
||||
func (f *fakeQRLoginService) GenerateQRCode(context.Context) (string, string, error) {
|
||||
func (f *fakeQRLoginService) GenerateQRCode(ctx context.Context) (string, string, error) {
|
||||
f.generateDeadline, _ = ctx.Deadline()
|
||||
if f.generateErr != nil {
|
||||
return "", "", f.generateErr
|
||||
}
|
||||
@@ -54,7 +56,8 @@ func (f *fakeQRLoginService) CompleteVerification(context.Context, string) (stri
|
||||
func TestGenerateQRLogin(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
srv.QRLogin = &fakeQRLoginService{}
|
||||
qr := &fakeQRLoginService{}
|
||||
srv.QRLogin = qr
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
@@ -70,6 +73,10 @@ func TestGenerateQRLogin(t *testing.T) {
|
||||
if res["success"] != true || res["session_id"] == nil || res["session_id"] == "" {
|
||||
t.Fatalf("生成二维码响应异常: %+v", res)
|
||||
}
|
||||
remaining := time.Until(qr.generateDeadline)
|
||||
if remaining < qrLoginGenerateTimeout-time.Second || remaining > qrLoginGenerateTimeout {
|
||||
t.Fatalf("二维码生成超时窗口=%v want≈%v", remaining, qrLoginGenerateTimeout)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQRLoginSessionCannotBeReadByAnotherUser(t *testing.T) {
|
||||
|
||||
@@ -24,6 +24,7 @@ import (
|
||||
"xianyu-go/internal/chat"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/notify"
|
||||
appversion "xianyu-go/internal/version"
|
||||
"xianyu-go/internal/webui"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
"xianyu-go/internal/xianyu/qrlogin"
|
||||
@@ -83,8 +84,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.
|
||||
@@ -127,6 +129,21 @@ func (s *Server) mtopClient() mtop.Client {
|
||||
return mtop.NewClient()
|
||||
}
|
||||
|
||||
// recoverExpiredMTOPSession 是 HTTP/API 入口的统一 Session 失效出口。
|
||||
// 各调用点必须先保存响应 Cookie 并释放账号凭证锁,再进入续期,避免锁反转。
|
||||
func (s *Server) recoverExpiredMTOPSession(ctx context.Context, cookieID string, err error) bool {
|
||||
if !mtop.IsSessionExpiredErr(err) {
|
||||
return false
|
||||
}
|
||||
if s.Logger != nil {
|
||||
s.Logger.Warn("MTOP API 检测到 Session 过期,停止业务请求并开始即时续期", "account", cookieID, "err", err)
|
||||
}
|
||||
if s.Manager == nil {
|
||||
return false
|
||||
}
|
||||
return s.Manager.RecoverExpiredCredential(ctx, cookieID)
|
||||
}
|
||||
|
||||
// Router 构建完整路由树。
|
||||
func (s *Server) Router() http.Handler {
|
||||
r := chi.NewRouter()
|
||||
@@ -142,6 +159,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 +338,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",
|
||||
@@ -347,7 +365,13 @@ func (s *Server) health(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"status": "degraded", "database": "unavailable"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"status": "ok", "database": "ok"})
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"status": "ok",
|
||||
"database": "ok",
|
||||
"version": appversion.Version,
|
||||
"commit": appversion.ShortCommit(),
|
||||
"build_time": appversion.BuildTime,
|
||||
})
|
||||
}
|
||||
|
||||
// 各分组 mount*Real 方法在 handlers 文件中实现;为避免单文件过大,按业务域分文件。
|
||||
|
||||
@@ -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()
|
||||
@@ -316,6 +390,9 @@ func TestHealth(t *testing.T) {
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("health status=%d", rec.Code)
|
||||
}
|
||||
if !strings.Contains(rec.Body.String(), `"version":"dev"`) {
|
||||
t.Fatalf("health response missing build version: %s", rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHealthReportsUnavailableDatabase(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
// Package version exposes build metadata injected by release builds.
|
||||
package version
|
||||
|
||||
import "strings"
|
||||
|
||||
var (
|
||||
Version = "dev"
|
||||
Commit = "unknown"
|
||||
BuildTime = "unknown"
|
||||
)
|
||||
|
||||
// ShortCommit returns a compact commit identifier suitable for UI display.
|
||||
func ShortCommit() string {
|
||||
commit := strings.TrimSpace(Commit)
|
||||
if len(commit) > 12 {
|
||||
return commit[:12]
|
||||
}
|
||||
if commit == "" {
|
||||
return "unknown"
|
||||
}
|
||||
return commit
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package version
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestShortCommit(t *testing.T) {
|
||||
original := Commit
|
||||
t.Cleanup(func() { Commit = original })
|
||||
|
||||
Commit = "0123456789abcdef"
|
||||
if got := ShortCommit(); got != "0123456789ab" {
|
||||
t.Fatalf("ShortCommit() = %q", got)
|
||||
}
|
||||
}
|
||||
+90
-80
@@ -1,4 +1,4 @@
|
||||
import{r as s}from"./react-vendor-C_od1ZSF.js";/**
|
||||
import{r as h}from"./react-vendor-C_od1ZSF.js";/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
@@ -13,394 +13,404 @@ import{r as s}from"./react-vendor-C_od1ZSF.js";/**
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const m=s.forwardRef(({color:t="currentColor",size:a=24,strokeWidth:c=2,absoluteStrokeWidth:o,className:y="",children:h,iconNode:p,...d},i)=>s.createElement("svg",{ref:i,...v,width:a,height:a,stroke:t,strokeWidth:o?Number(c)*24/Number(a):c,className:k("lucide",y),...!h&&!x(d)&&{"aria-hidden":"true"},...d},[...p.map(([r,l])=>s.createElement(r,l)),...Array.isArray(h)?h:[h]]));/**
|
||||
*/const m=h.forwardRef(({color:t="currentColor",size:a=24,strokeWidth:c=2,absoluteStrokeWidth:o,className:s="",children:y,iconNode:i,...d},p)=>h.createElement("svg",{ref:p,...v,width:a,height:a,stroke:t,strokeWidth:o?Number(c)*24/Number(a):c,className:k("lucide",s),...!y&&!x(d)&&{"aria-hidden":"true"},...d},[...i.map(([r,l])=>h.createElement(r,l)),...Array.isArray(y)?y:[y]]));/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const e=(t,a)=>{const c=s.forwardRef(({className:o,...y},h)=>s.createElement(m,{ref:h,iconNode:a,className:k(`lucide-${M(n(t))}`,`lucide-${t}`,o),...y}));return c.displayName=n(t),c};/**
|
||||
*/const e=(t,a)=>{const c=h.forwardRef(({className:o,...s},y)=>h.createElement(m,{ref:y,iconNode:a,className:k(`lucide-${M(n(t))}`,`lucide-${t}`,o),...s}));return c.displayName=n(t),c};/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const g=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],I1=e("activity",g);/**
|
||||
*/const g=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],O1=e("activity",g);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const u=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],O1=e("arrow-right",u);/**
|
||||
*/const u=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],Z1=e("arrow-right",u);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const $=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]],Z1=e("bell",$);/**
|
||||
*/const $=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]],K1=e("bell",$);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const N=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],F1=e("bot",N);/**
|
||||
*/const N=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],G1=e("bot",N);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const f=[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]],K1=e("box",f);/**
|
||||
*/const f=[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]],Q1=e("box",f);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const w=[["path",{d:"M16 14v2.2l1.6 1",key:"fo4ql5"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5",key:"1osxxc"}],["path",{d:"M3 10h5",key:"r794hk"}],["path",{d:"M8 2v4",key:"1cmpym"}],["circle",{cx:"16",cy:"16",r:"6",key:"qoo3c4"}]],Q1=e("calendar-clock",w);/**
|
||||
*/const w=[["path",{d:"M16 14v2.2l1.6 1",key:"fo4ql5"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5",key:"1osxxc"}],["path",{d:"M3 10h5",key:"r794hk"}],["path",{d:"M8 2v4",key:"1cmpym"}],["circle",{cx:"16",cy:"16",r:"6",key:"qoo3c4"}]],J1=e("calendar-clock",w);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const b=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],G1=e("check-check",b);/**
|
||||
*/const z=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],X1=e("check-check",z);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const z=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],J1=e("check",z);/**
|
||||
*/const b=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Y1=e("check",b);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const q=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],X1=e("chevron-down",q);/**
|
||||
*/const q=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],e2=e("chevron-down",q);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const C=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],Y1=e("chevron-left",C);/**
|
||||
*/const C=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],a2=e("chevron-left",C);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const A=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],e2=e("chevron-right",A);/**
|
||||
*/const j=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],t2=e("chevron-right",j);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const j=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],a2=e("circle-alert",j);/**
|
||||
*/const A=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],c2=e("circle-alert",A);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const H=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],t2=e("circle-check",H);/**
|
||||
*/const H=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],o2=e("circle-check",H);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const V=[["path",{d:"M10.1 2.182a10 10 0 0 1 3.8 0",key:"5ilxe3"}],["path",{d:"M13.9 21.818a10 10 0 0 1-3.8 0",key:"11zvb9"}],["path",{d:"M17.609 3.721a10 10 0 0 1 2.69 2.7",key:"1iw5b2"}],["path",{d:"M2.182 13.9a10 10 0 0 1 0-3.8",key:"c0bmvh"}],["path",{d:"M20.279 17.609a10 10 0 0 1-2.7 2.69",key:"1ruxm7"}],["path",{d:"M21.818 10.1a10 10 0 0 1 0 3.8",key:"qkgqxc"}],["path",{d:"M3.721 6.391a10 10 0 0 1 2.7-2.69",key:"1mcia2"}],["path",{d:"M6.391 20.279a10 10 0 0 1-2.69-2.7",key:"1fvljs"}]],c2=e("circle-dashed",V);/**
|
||||
*/const V=[["path",{d:"M10.1 2.182a10 10 0 0 1 3.8 0",key:"5ilxe3"}],["path",{d:"M13.9 21.818a10 10 0 0 1-3.8 0",key:"11zvb9"}],["path",{d:"M17.609 3.721a10 10 0 0 1 2.69 2.7",key:"1iw5b2"}],["path",{d:"M2.182 13.9a10 10 0 0 1 0-3.8",key:"c0bmvh"}],["path",{d:"M20.279 17.609a10 10 0 0 1-2.7 2.69",key:"1ruxm7"}],["path",{d:"M21.818 10.1a10 10 0 0 1 0 3.8",key:"qkgqxc"}],["path",{d:"M3.721 6.391a10 10 0 0 1 2.7-2.69",key:"1mcia2"}],["path",{d:"M6.391 20.279a10 10 0 0 1-2.69-2.7",key:"1fvljs"}]],y2=e("circle-dashed",V);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const L=[["path",{d:"M12 6v6h4",key:"135r8i"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],o2=e("clock-3",L);/**
|
||||
*/const L=[["path",{d:"M12 6v6h4",key:"135r8i"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],h2=e("clock-3",L);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const P=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],h2=e("clock",P);/**
|
||||
*/const P=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],s2=e("clock",P);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const S=[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"m8 17 4-4 4 4",key:"1quai1"}]],s2=e("cloud-upload",S);/**
|
||||
*/const S=[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"m8 17 4-4 4 4",key:"1quai1"}]],d2=e("cloud-upload",S);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const U=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],y2=e("code",U);/**
|
||||
*/const U=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],n2=e("code",U);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const E=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],d2=e("copy",E);/**
|
||||
*/const E=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],k2=e("copy",E);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const B=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],n2=e("credit-card",B);/**
|
||||
*/const B=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],i2=e("credit-card",B);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const D=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],k2=e("database",D);/**
|
||||
*/const D=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],p2=e("database",D);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const R=[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]],p2=e("dollar-sign",R);/**
|
||||
*/const R=[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]],r2=e("dollar-sign",R);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const T=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],i2=e("external-link",T);/**
|
||||
*/const T=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],l2=e("external-link",T);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const W=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],r2=e("eye-off",W);/**
|
||||
*/const W=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],M2=e("eye-off",W);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const I=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],l2=e("eye",I);/**
|
||||
*/const F=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],_2=e("eye",F);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const O=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]],M2=e("file-down",O);/**
|
||||
*/const I=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]],x2=e("file-down",I);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const Z=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],_2=e("file-text",Z);/**
|
||||
*/const O=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],v2=e("file-text",O);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const F=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]],x2=e("funnel",F);/**
|
||||
*/const Z=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]],m2=e("funnel",Z);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const K=[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1",key:"bkv52"}],["path",{d:"M12 8v13",key:"1c76mn"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7",key:"6wjy6b"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5",key:"1ihvrl"}]],v2=e("gift",K);/**
|
||||
*/const K=[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1",key:"bkv52"}],["path",{d:"M12 8v13",key:"1c76mn"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7",key:"6wjy6b"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5",key:"1ihvrl"}]],g2=e("gift",K);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const Q=[["path",{d:"M16 5h6",key:"1vod17"}],["path",{d:"M19 2v6",key:"4bpg5p"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5",key:"1ue2ih"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}]],m2=e("image-plus",Q);/**
|
||||
*/const G=[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["line",{x1:"3",x2:"9",y1:"12",y2:"12",key:"1dyftd"}],["line",{x1:"15",x2:"21",y1:"12",y2:"12",key:"oup4p8"}]],u2=e("git-commit-horizontal",G);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const G=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],g2=e("image",G);/**
|
||||
*/const Q=[["path",{d:"M16 5h6",key:"1vod17"}],["path",{d:"M19 2v6",key:"4bpg5p"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5",key:"1ue2ih"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}]],$2=e("image-plus",Q);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const J=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]],u2=e("key",J);/**
|
||||
*/const J=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],N2=e("image",J);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const X=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],$2=e("layers",X);/**
|
||||
*/const X=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]],f2=e("key",X);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const Y=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],N2=e("layout-dashboard",Y);/**
|
||||
*/const Y=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],w2=e("layers",Y);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const e1=[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]],f2=e("link-2",e1);/**
|
||||
*/const e1=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],z2=e("layout-dashboard",e1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const a1=[["path",{d:"M16 5H3",key:"m91uny"}],["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 19H3",key:"zzsher"}],["path",{d:"M18 9v6",key:"1twb98"}],["path",{d:"M21 12h-6",key:"bt1uis"}]],w2=e("list-plus",a1);/**
|
||||
*/const a1=[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]],b2=e("link-2",a1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const t1=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],b2=e("loader-circle",t1);/**
|
||||
*/const t1=[["path",{d:"M16 5H3",key:"m91uny"}],["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 19H3",key:"zzsher"}],["path",{d:"M18 9v6",key:"1twb98"}],["path",{d:"M21 12h-6",key:"bt1uis"}]],q2=e("list-plus",t1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const c1=[["circle",{cx:"12",cy:"16",r:"1",key:"1au0dj"}],["rect",{x:"3",y:"10",width:"18",height:"12",rx:"2",key:"6s8ecr"}],["path",{d:"M7 10V7a5 5 0 0 1 10 0v3",key:"1pqi11"}]],z2=e("lock-keyhole",c1);/**
|
||||
*/const c1=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],C2=e("loader-circle",c1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const o1=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],q2=e("lock",o1);/**
|
||||
*/const o1=[["line",{x1:"2",x2:"5",y1:"12",y2:"12",key:"bvdh0s"}],["line",{x1:"19",x2:"22",y1:"12",y2:"12",key:"1tbv5k"}],["line",{x1:"12",x2:"12",y1:"2",y2:"5",key:"11lu5j"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}],["circle",{cx:"12",cy:"12",r:"7",key:"fim9np"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],j2=e("locate-fixed",o1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const h1=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],C2=e("log-out",h1);/**
|
||||
*/const y1=[["circle",{cx:"12",cy:"16",r:"1",key:"1au0dj"}],["rect",{x:"3",y:"10",width:"18",height:"12",rx:"2",key:"6s8ecr"}],["path",{d:"M7 10V7a5 5 0 0 1 10 0v3",key:"1pqi11"}]],A2=e("lock-keyhole",y1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const s1=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7",key:"132q7q"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}]],A2=e("mail",s1);/**
|
||||
*/const h1=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],H2=e("lock",h1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const y1=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}],["path",{d:"M8 12h.01",key:"czm47f"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M16 12h.01",key:"1l6xoz"}]],j2=e("message-circle-more",y1);/**
|
||||
*/const s1=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],V2=e("log-out",s1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const d1=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],H2=e("message-circle",d1);/**
|
||||
*/const d1=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7",key:"132q7q"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}]],L2=e("mail",d1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const n1=[["path",{d:"M14 14a2 2 0 0 0 2-2V8h-2",key:"1r06pg"}],["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}],["path",{d:"M8 14a2 2 0 0 0 2-2V8H8",key:"1jzu5j"}]],V2=e("message-square-quote",n1);/**
|
||||
*/const n1=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}],["path",{d:"M8 12h.01",key:"czm47f"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M16 12h.01",key:"1l6xoz"}]],P2=e("message-circle-more",n1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const k1=[["path",{d:"m16 16 2 2 4-4",key:"gfu2re"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]],L2=e("package-check",k1);/**
|
||||
*/const k1=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],S2=e("message-circle",k1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const p1=[["path",{d:"M16 16h6",key:"100bgy"}],["path",{d:"M19 13v6",key:"85cyf1"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]],P2=e("package-plus",p1);/**
|
||||
*/const i1=[["path",{d:"M14 14a2 2 0 0 0 2-2V8h-2",key:"1r06pg"}],["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}],["path",{d:"M8 14a2 2 0 0 0 2-2V8H8",key:"1jzu5j"}]],U2=e("message-square-quote",i1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const i1=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],S2=e("package",i1);/**
|
||||
*/const p1=[["path",{d:"m16 16 2 2 4-4",key:"gfu2re"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]],E2=e("package-check",p1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const r1=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],U2=e("pen",r1);/**
|
||||
*/const r1=[["path",{d:"M16 16h6",key:"100bgy"}],["path",{d:"M19 13v6",key:"85cyf1"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]],B2=e("package-plus",r1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const l1=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],E2=e("play",l1);/**
|
||||
*/const l1=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],D2=e("package",l1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const M1=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],B2=e("plus",M1);/**
|
||||
*/const M1=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],R2=e("pen",M1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const _1=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],D2=e("power",_1);/**
|
||||
*/const _1=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],T2=e("play",_1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const x1=[["rect",{width:"5",height:"5",x:"3",y:"3",rx:"1",key:"1tu5fj"}],["rect",{width:"5",height:"5",x:"16",y:"3",rx:"1",key:"1v8r4q"}],["rect",{width:"5",height:"5",x:"3",y:"16",rx:"1",key:"1x03jg"}],["path",{d:"M21 16h-3a2 2 0 0 0-2 2v3",key:"177gqh"}],["path",{d:"M21 21v.01",key:"ents32"}],["path",{d:"M12 7v3a2 2 0 0 1-2 2H7",key:"8crl2c"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M12 3h.01",key:"n36tog"}],["path",{d:"M12 16v.01",key:"133mhm"}],["path",{d:"M16 12h1",key:"1slzba"}],["path",{d:"M21 12v.01",key:"1lwtk9"}],["path",{d:"M12 21v-1",key:"1880an"}]],R2=e("qr-code",x1);/**
|
||||
*/const x1=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],W2=e("plus",x1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const v1=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],T2=e("refresh-cw",v1);/**
|
||||
*/const v1=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],F2=e("power",v1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const m1=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],W2=e("save",m1);/**
|
||||
*/const m1=[["rect",{width:"5",height:"5",x:"3",y:"3",rx:"1",key:"1tu5fj"}],["rect",{width:"5",height:"5",x:"16",y:"3",rx:"1",key:"1v8r4q"}],["rect",{width:"5",height:"5",x:"3",y:"16",rx:"1",key:"1x03jg"}],["path",{d:"M21 16h-3a2 2 0 0 0-2 2v3",key:"177gqh"}],["path",{d:"M21 21v.01",key:"ents32"}],["path",{d:"M12 7v3a2 2 0 0 1-2 2H7",key:"8crl2c"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M12 3h.01",key:"n36tog"}],["path",{d:"M12 16v.01",key:"133mhm"}],["path",{d:"M16 12h1",key:"1slzba"}],["path",{d:"M21 12v.01",key:"1lwtk9"}],["path",{d:"M12 21v-1",key:"1880an"}]],I2=e("qr-code",m1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const g1=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],I2=e("search",g1);/**
|
||||
*/const g1=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],O2=e("refresh-cw",g1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const u1=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],O2=e("send",u1);/**
|
||||
*/const u1=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],Z2=e("save",u1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const $1=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Z2=e("settings",$1);/**
|
||||
*/const $1=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],K2=e("search",$1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const N1=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],F2=e("shield-check",N1);/**
|
||||
*/const N1=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],G2=e("send",N1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const f1=[["path",{d:"M16 10a4 4 0 0 1-8 0",key:"1ltviw"}],["path",{d:"M3.103 6.034h17.794",key:"awc11p"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z",key:"o988cm"}]],K2=e("shopping-bag",f1);/**
|
||||
*/const f1=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Q2=e("settings",f1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const w1=[["circle",{cx:"8",cy:"21",r:"1",key:"jimo8o"}],["circle",{cx:"19",cy:"21",r:"1",key:"13723u"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12",key:"9zh506"}]],Q2=e("shopping-cart",w1);/**
|
||||
*/const w1=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],J2=e("shield-check",w1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const b1=[["path",{d:"M10 5H3",key:"1qgfaw"}],["path",{d:"M12 19H3",key:"yhmn1j"}],["path",{d:"M14 3v4",key:"1sua03"}],["path",{d:"M16 17v4",key:"1q0r14"}],["path",{d:"M21 12h-9",key:"1o4lsq"}],["path",{d:"M21 19h-5",key:"1rlt1p"}],["path",{d:"M21 5h-7",key:"1oszz2"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M8 12H3",key:"a7s4jb"}]],G2=e("sliders-horizontal",b1);/**
|
||||
*/const z1=[["path",{d:"M16 10a4 4 0 0 1-8 0",key:"1ltviw"}],["path",{d:"M3.103 6.034h17.794",key:"awc11p"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z",key:"o988cm"}]],X2=e("shopping-bag",z1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const z1=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]],J2=e("smile",z1);/**
|
||||
*/const b1=[["circle",{cx:"8",cy:"21",r:"1",key:"jimo8o"}],["circle",{cx:"19",cy:"21",r:"1",key:"13723u"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12",key:"9zh506"}]],Y2=e("shopping-cart",b1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const q1=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],X2=e("sparkles",q1);/**
|
||||
*/const q1=[["path",{d:"M10 5H3",key:"1qgfaw"}],["path",{d:"M12 19H3",key:"yhmn1j"}],["path",{d:"M14 3v4",key:"1sua03"}],["path",{d:"M16 17v4",key:"1q0r14"}],["path",{d:"M21 12h-9",key:"1o4lsq"}],["path",{d:"M21 19h-5",key:"1rlt1p"}],["path",{d:"M21 5h-7",key:"1oszz2"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M8 12H3",key:"a7s4jb"}]],e0=e("sliders-horizontal",q1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const C1=[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]],Y2=e("square-pen",C1);/**
|
||||
*/const C1=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]],a0=e("smile",C1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const A1=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],e0=e("trash-2",A1);/**
|
||||
*/const j1=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],t0=e("sparkles",j1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const j1=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],a0=e("trending-up",j1);/**
|
||||
*/const A1=[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]],c0=e("square-pen",A1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const H1=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],t0=e("triangle-alert",H1);/**
|
||||
*/const H1=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],o0=e("trash-2",H1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const V1=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2",key:"wrbu53"}],["path",{d:"M15 18H9",key:"1lyqi6"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14",key:"lysw3i"}],["circle",{cx:"17",cy:"18",r:"2",key:"332jqn"}],["circle",{cx:"7",cy:"18",r:"2",key:"19iecd"}]],c0=e("truck",V1);/**
|
||||
*/const V1=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],y0=e("trending-up",V1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const L1=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],o0=e("upload",L1);/**
|
||||
*/const L1=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],h0=e("triangle-alert",L1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const P1=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],h0=e("user-round",P1);/**
|
||||
*/const P1=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2",key:"wrbu53"}],["path",{d:"M15 18H9",key:"1lyqi6"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14",key:"lysw3i"}],["circle",{cx:"17",cy:"18",r:"2",key:"332jqn"}],["circle",{cx:"7",cy:"18",r:"2",key:"19iecd"}]],s0=e("truck",P1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const S1=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]],s0=e("user",S1);/**
|
||||
*/const S1=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],d0=e("upload",S1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const U1=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],y0=e("users",U1);/**
|
||||
*/const U1=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],n0=e("user-round",U1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const E1=[["path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2",key:"q3hayz"}],["path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06",key:"1go1hn"}],["path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8",key:"qlwsc0"}]],d0=e("webhook",E1);/**
|
||||
*/const E1=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]],k0=e("user",E1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const B1=[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}],["path",{d:"M5 12.859a10 10 0 0 1 5.17-2.69",key:"1dl1wf"}],["path",{d:"M19 12.859a10 10 0 0 0-2.007-1.523",key:"4k23kn"}],["path",{d:"M2 8.82a15 15 0 0 1 4.177-2.643",key:"1grhjp"}],["path",{d:"M22 8.82a15 15 0 0 0-11.288-3.764",key:"z3jwby"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],n0=e("wifi-off",B1);/**
|
||||
*/const B1=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],i0=e("users",B1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const D1=[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M2 8.82a15 15 0 0 1 20 0",key:"dnpr2z"}],["path",{d:"M5 12.859a10 10 0 0 1 14 0",key:"1x1e6c"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}]],k0=e("wifi",D1);/**
|
||||
*/const D1=[["path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2",key:"q3hayz"}],["path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06",key:"1go1hn"}],["path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8",key:"qlwsc0"}]],p0=e("webhook",D1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const R1=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],p0=e("x",R1);/**
|
||||
*/const R1=[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}],["path",{d:"M5 12.859a10 10 0 0 1 5.17-2.69",key:"1dl1wf"}],["path",{d:"M19 12.859a10 10 0 0 0-2.007-1.523",key:"4k23kn"}],["path",{d:"M2 8.82a15 15 0 0 1 4.177-2.643",key:"1grhjp"}],["path",{d:"M22 8.82a15 15 0 0 0-11.288-3.764",key:"z3jwby"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],r0=e("wifi-off",R1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const T1=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],i0=e("zap",T1);export{x2 as $,I1 as A,K1 as B,n2 as C,p2 as D,i2 as E,c0 as F,I2 as G,Y2 as H,o0 as I,G2 as J,u2 as K,N2 as L,j2 as M,d2 as N,_2 as O,S2 as P,R2 as Q,T2 as R,K2 as S,a0 as T,y0 as U,g2 as V,w2 as W,p0 as X,M2 as Y,i0 as Z,y2 as _,Z1 as a,P2 as a0,s2 as a1,t2 as a2,c2 as a3,f2 as a4,O1 as a5,k2 as a6,X1 as a7,F2 as a8,z2 as a9,h0 as aa,o2 as ab,v2 as ac,$2 as ad,O2 as ae,A2 as af,d0 as ag,k0 as ah,n0 as ai,G1 as aj,J2 as ak,m2 as al,q2 as am,Z2 as b,e2 as c,Y1 as d,C2 as e,a2 as f,Q2 as g,L2 as h,t0 as i,b2 as j,V2 as k,E2 as l,X2 as m,Q1 as n,W2 as o,s0 as p,J1 as q,F1 as r,H2 as s,h2 as t,U2 as u,D2 as v,e0 as w,r2 as x,l2 as y,B2 as z};
|
||||
*/const T1=[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M2 8.82a15 15 0 0 1 20 0",key:"dnpr2z"}],["path",{d:"M5 12.859a10 10 0 0 1 14 0",key:"1x1e6c"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}]],l0=e("wifi",T1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const W1=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],M0=e("x",W1);/**
|
||||
* @license lucide-react v0.562.0 - ISC
|
||||
*
|
||||
* This source code is licensed under the ISC license.
|
||||
* See the LICENSE file in the root directory of this source tree.
|
||||
*/const F1=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],_0=e("zap",F1);export{n2 as $,O1 as A,Q1 as B,i2 as C,r2 as D,l2 as E,s0 as F,u2 as G,K2 as H,c0 as I,d0 as J,f2 as K,z2 as L,P2 as M,e0 as N,k2 as O,D2 as P,I2 as Q,O2 as R,X2 as S,y0 as T,i0 as U,v2 as V,N2 as W,M0 as X,q2 as Y,_0 as Z,x2 as _,K1 as a,m2 as a0,B2 as a1,d2 as a2,o2 as a3,y2 as a4,b2 as a5,Z1 as a6,j2 as a7,p2 as a8,e2 as a9,J2 as aa,A2 as ab,n0 as ac,h2 as ad,g2 as ae,w2 as af,G2 as ag,L2 as ah,p0 as ai,l0 as aj,r0 as ak,X1 as al,a0 as am,$2 as an,H2 as ao,Q2 as b,t2 as c,a2 as d,V2 as e,c2 as f,Y2 as g,E2 as h,h0 as i,C2 as j,U2 as k,T2 as l,t0 as m,J1 as n,Z2 as o,k0 as p,Y1 as q,G1 as r,S2 as s,s2 as t,R2 as u,F2 as v,o0 as w,M2 as x,_2 as y,W2 as z};
|
||||
@@ -1 +0,0 @@
|
||||
*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(147 197 253 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(147 197 253 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:rgb(var(--color-neutral-200) / 1)}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:rgb(var(--color-neutral-400) / 1)}input::placeholder,textarea::placeholder{opacity:1;color:rgb(var(--color-neutral-400) / 1)}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.\!container{width:100%!important}.container{width:100%}@media(min-width:640px){.\!container{max-width:640px!important}.container{max-width:6Line truncated
|
||||
Loaded 100 of 141 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user