Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ae73eca2c4 | ||
|
|
3480cbaa5f |
No files matched your search
@@ -1,397 +0,0 @@
|
||||
# GC-UI 夜间 alpha 构建(Gitea Actions)
|
||||
#
|
||||
# 触发:每天 21:00(Asia/Shanghai)自动跑一次,产出 Windows 与 macOS 的 Flutter 前端产物,
|
||||
# 发布为一个「预览版(prerelease)」Release —— 不占用 latest。
|
||||
# 手动:Actions 页面点 Run workflow(Gitea 的 workflow_dispatch),用于验证 runner 是否就绪;
|
||||
# 也可以从命令行调 POST /api/v1/repos/{owner}/{repo}/actions/workflows/{file}/dispatches。
|
||||
#
|
||||
# 为什么是 .gitea/workflows/:本仓库是自建 Gitea,不是 GitHub。Gitea Actions 语法与
|
||||
# GitHub Actions 基本一致,但工作流目录是 .gitea/workflows/,API 前缀是 /api/v1,
|
||||
# runner 标签必须与 act_runner 上注册的 label 一致(见 GC-UI/CI.md)。
|
||||
#
|
||||
# 为什么 alpha 不会变成 latest:Gitea 的 /releases/latest 按定义只返回「最近一个既非草稿
|
||||
# 也非 prerelease」的发布,所以 prerelease=true 的版本永远不会被当成 latest。
|
||||
# publish 任务最后还会主动断言一次,确认 latest 没有指向本次 tag。
|
||||
|
||||
name: GC-UI Alpha
|
||||
|
||||
on:
|
||||
schedule:
|
||||
# 每天晚上 21:00,北京时间。
|
||||
# Gitea 1.23 起 Actions 的 cron 默认按 UTC 解释,这里显式带 TZ= 前缀(robfig/cron 支持的
|
||||
# 时区前缀语法),这样不依赖服务器自身时区设置。
|
||||
# 如果所在实例不认 TZ= 前缀,改用等效的 UTC 写法 '0 13 * * *'。
|
||||
- cron: 'TZ=Asia/Shanghai 0 21 * * *'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
note:
|
||||
description: '额外写进 Release 说明的备注(可留空)'
|
||||
required: false
|
||||
default: ''
|
||||
|
||||
# 用 github.token 往本仓库建 Release / 传附件,需要 contents 写权限
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
env:
|
||||
GITEA_API: ${{ github.server_url }}/api/v1
|
||||
REPO: ${{ github.repository }}
|
||||
FRONTEND_DIR: GC-UI/frontend
|
||||
# runner 上没预装 Flutter 时,按这个版本自举(需 >= 3.5.4,与 pubspec.yaml 的 sdk 约束对齐)
|
||||
FLUTTER_VERSION: 3.24.5
|
||||
|
||||
jobs:
|
||||
# ---------------------------------------------------------------- 1. 版本与草稿
|
||||
prepare:
|
||||
name: 计算 alpha 版本并创建预览版草稿
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
version: ${{ steps.meta.outputs.version }}
|
||||
base_version: ${{ steps.meta.outputs.base_version }}
|
||||
tag: ${{ steps.meta.outputs.tag }}
|
||||
build_number: ${{ steps.meta.outputs.build_number }}
|
||||
release_id: ${{ steps.release.outputs.release_id }}
|
||||
steps:
|
||||
- name: 检出代码
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: 计算版本号
|
||||
id: meta
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# 基础版本取自 version.json 的 launcher.version(例如 1.0.7),与启动器保持一致;
|
||||
# alpha 后缀只表示构建通道,写在 tag / Release 标题里。
|
||||
BASE=$(python3 -c "import json;print(json.load(open('version.json'))['launcher']['version'])")
|
||||
if [ -z "${BASE:-}" ]; then
|
||||
echo "::error::无法从 version.json 读取 launcher.version"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 北京时间当天日期,让产物名和 tag 与「每晚 9 点」对得上
|
||||
DATE=$(TZ=Asia/Shanghai date +%Y%m%d)
|
||||
# 同一天重跑时用 run_number 区分,tag 不重复
|
||||
VERSION="${BASE}-alpha.${DATE}.${{ github.run_number }}"
|
||||
|
||||
# 传给 flutter 的版本号必须是纯数字分段:
|
||||
# --build-name → macOS CFBundleShortVersionString,只能是 a.b.c
|
||||
# --build-number → CFBundleVersion / 文件版本号,只能是数字
|
||||
# 所以 alpha 的日期与序号放在 build-number 里,不放进 build-name。
|
||||
BUILD_NUMBER="${DATE}$(printf '%02d' "${{ github.run_number }}")"
|
||||
|
||||
{
|
||||
echo "version=$VERSION"
|
||||
echo "base_version=$BASE"
|
||||
echo "tag=v$VERSION"
|
||||
echo "build_number=$BUILD_NUMBER"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
echo "alpha 版本: $VERSION(build-name=$BASE, build-number=$BUILD_NUMBER)"
|
||||
|
||||
- name: 创建预览版草稿
|
||||
id: release
|
||||
env:
|
||||
# 优先用仓库 Secrets 里的 RELEASE_TOKEN;没配就退回 Gitea 自动注入的 github.token。
|
||||
# 某些实例上自动 token 没有 releases 写权限,那时只需在
|
||||
# Settings → Actions → Secrets 加一个 RELEASE_TOKEN,不用改本文件。
|
||||
TOKEN_OVERRIDE: ${{ secrets.RELEASE_TOKEN }}
|
||||
TOKEN_DEFAULT: ${{ github.token }}
|
||||
TAG: ${{ steps.meta.outputs.tag }}
|
||||
VERSION: ${{ steps.meta.outputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
TOKEN="${TOKEN_OVERRIDE:-$TOKEN_DEFAULT}"
|
||||
if [ -z "${TOKEN:-}" ]; then
|
||||
echo "::error::拿不到 Gitea token,无法创建 Release"
|
||||
exit 1
|
||||
fi
|
||||
api="$GITEA_API/repos/$REPO"
|
||||
auth=(-H "Authorization: token $TOKEN")
|
||||
|
||||
# 可重跑:同 tag 的旧发布先删掉(只会是同一天重跑留下的)
|
||||
code=$(curl -sS -o /tmp/existing.json -w '%{http_code}' "${auth[@]}" "$api/releases/tags/$TAG")
|
||||
if [ "$code" = "200" ]; then
|
||||
old_id=$(python3 -c "import json;print(json.load(open('/tmp/existing.json'))['id'])")
|
||||
echo "已存在同 tag 发布 id=$old_id,先删除"
|
||||
curl -sS -X DELETE "${auth[@]}" "$api/releases/$old_id" >/dev/null
|
||||
fi
|
||||
|
||||
# draft=true + prerelease=true:
|
||||
# prerelease → 永不成为 latest
|
||||
# draft → 两个平台都构建成功前不对外可见,由 publish 任务翻成 false
|
||||
payload=$(python3 - "$TAG" "$VERSION" "${{ github.sha }}" "${{ github.server_url }}" <<'PY'
|
||||
import json, sys
|
||||
tag, version, sha, server = sys.argv[1:5]
|
||||
short = sha[:7]
|
||||
body = (
|
||||
"GC-UI 夜间 alpha 构建(自动生成,**预览版 / prerelease**)。\n\n"
|
||||
"- 版本:`%s`\n"
|
||||
"- 提交:`%s`\n"
|
||||
"- 构建来源:%s/commit/%s\n"
|
||||
"- 通道:alpha —— 每晚 21:00(Asia/Shanghai)自动构建\n\n"
|
||||
"产物说明:\n\n"
|
||||
"| 文件 | 平台 | 内容 |\n"
|
||||
"|---|---|---|\n"
|
||||
"| `gc-ui-alpha-windows-x64.zip` | Windows x64 | Flutter 前端 release 目录 |\n"
|
||||
"| `gc-ui-alpha-macos-<arch>.zip` | macOS | `gc_ui.app` 应用包 |\n\n"
|
||||
"这是前端产物,运行时需要配合 `GC-UI/backend/GC.UI.Server` 后端(默认 `127.0.0.1:17890`)。\n"
|
||||
"未做代码签名,首次运行系统可能会提示。\n\n"
|
||||
"> 本发布不是 latest:prerelease 的版本不会出现在「最新版本」里。\n"
|
||||
) % (version, short, server, sha)
|
||||
print(json.dumps({
|
||||
"tag_name": tag,
|
||||
"target_commitish": sha,
|
||||
"name": "GC-UI Alpha " + version,
|
||||
"body": body,
|
||||
"draft": True,
|
||||
"prerelease": True,
|
||||
}))
|
||||
PY
|
||||
)
|
||||
|
||||
resp=$(curl -sS -X POST "${auth[@]}" -H 'Content-Type: application/json' -d "$payload" "$api/releases")
|
||||
rid=$(printf '%s' "$resp" | python3 -c "import json,sys;print(json.load(sys.stdin).get('id',''))" 2>/dev/null || true)
|
||||
if [ -z "$rid" ]; then
|
||||
echo "::error::创建 Release 失败: $resp"
|
||||
exit 1
|
||||
fi
|
||||
echo "release_id=$rid" >> "$GITHUB_OUTPUT"
|
||||
echo "已创建预览版草稿 id=$rid tag=$TAG"
|
||||
|
||||
# ---------------------------------------------------------------- 2. Windows
|
||||
windows:
|
||||
name: 构建 Windows 前端
|
||||
needs: prepare
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- name: 检出代码
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: 准备 Flutter SDK
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if (Get-Command flutter -ErrorAction SilentlyContinue) {
|
||||
Write-Host 'runner 已自带 Flutter:'
|
||||
flutter --version
|
||||
} else {
|
||||
Write-Host "runner 上没有 Flutter,按官方 SDK $env:FLUTTER_VERSION 自举"
|
||||
$url = "https://storage.googleapis.com/flutter_infra_release/releases/stable/windows/flutter_windows_$env:FLUTTER_VERSION-stable.zip"
|
||||
$zip = Join-Path $env:RUNNER_TEMP 'flutter.zip'
|
||||
curl.exe -sSL --retry 3 -o $zip $url
|
||||
if ($LASTEXITCODE -ne 0) { Write-Error "下载 Flutter SDK 失败: $url"; exit 1 }
|
||||
Expand-Archive -Path $zip -DestinationPath $env:RUNNER_TEMP -Force
|
||||
$flutterBin = Join-Path $env:RUNNER_TEMP 'flutter\bin'
|
||||
$flutterBin | Out-File -FilePath $env:GITHUB_PATH -Append -Encoding utf8
|
||||
$env:PATH = "$flutterBin;$env:PATH"
|
||||
flutter --version
|
||||
}
|
||||
# Windows 桌面构建依赖 VS Build Tools 的「使用 C++ 的桌面开发」工作负载
|
||||
$doctor = flutter doctor -v 2>&1 | Out-String
|
||||
if ($doctor -notmatch 'Visual Studio') {
|
||||
Write-Host '::warning::flutter doctor 没看到 Visual Studio,Windows 构建很可能失败'
|
||||
}
|
||||
Write-Host "PROCESSOR_ARCHITECTURE=$env:PROCESSOR_ARCHITECTURE"
|
||||
|
||||
- name: 构建前端(release)
|
||||
shell: pwsh
|
||||
env:
|
||||
VERSION: ${{ needs.prepare.outputs.base_version }}
|
||||
BUILD_NUMBER: ${{ needs.prepare.outputs.build_number }}
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
flutter config --no-analytics 2>&1 | Out-Null
|
||||
Set-Location $env:FRONTEND_DIR
|
||||
flutter pub get
|
||||
if ($LASTEXITCODE -ne 0) { exit 1 }
|
||||
flutter build windows --release --build-name=$env:VERSION --build-number=$env:BUILD_NUMBER
|
||||
if ($LASTEXITCODE -ne 0) { exit 1 }
|
||||
|
||||
- name: 打包
|
||||
id: pack
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
# x64 / arm64 的产物都在 build\windows\<arch>\runner\Release,直接找实际存在的那个
|
||||
$out = Get-ChildItem "$env:FRONTEND_DIR\build\windows" -Directory -ErrorAction SilentlyContinue |
|
||||
ForEach-Object { Join-Path $_.FullName 'runner\Release' } |
|
||||
Where-Object { Test-Path $_ } |
|
||||
Select-Object -First 1
|
||||
if (-not $out) {
|
||||
Write-Error "没有找到 Windows 产物目录($env:FRONTEND_DIR\build\windows\*\runner\Release)"
|
||||
exit 1
|
||||
}
|
||||
$arch = if ($env:PROCESSOR_ARCHITECTURE -eq 'ARM64') { 'arm64' } else { 'x64' }
|
||||
$name = "gc-ui-alpha-windows-$arch.zip"
|
||||
New-Item -ItemType Directory -Force -Path dist | Out-Null
|
||||
$zip = Join-Path (Get-Location) "dist\$name"
|
||||
Compress-Archive -Path (Join-Path $out '*') -DestinationPath $zip -Force
|
||||
Get-Item $zip | Format-List Name, Length
|
||||
"asset=$zip" | Out-File -FilePath $env:GITHUB_OUTPUT -Append -Encoding utf8
|
||||
"asset_name=$name" | Out-File -FilePath $env:GITHUB_OUTPUT -Append -Encoding utf8
|
||||
|
||||
- name: 上传到预览版
|
||||
shell: pwsh
|
||||
env:
|
||||
TOKEN_OVERRIDE: ${{ secrets.RELEASE_TOKEN }}
|
||||
TOKEN_DEFAULT: ${{ github.token }}
|
||||
RELEASE_ID: ${{ needs.prepare.outputs.release_id }}
|
||||
ASSET: ${{ steps.pack.outputs.asset }}
|
||||
ASSET_NAME: ${{ steps.pack.outputs.asset_name }}
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$token = if ($env:TOKEN_OVERRIDE) { $env:TOKEN_OVERRIDE } else { $env:TOKEN_DEFAULT }
|
||||
if (-not $token) { Write-Error '拿不到 Gitea token'; exit 1 }
|
||||
$url = "$env:GITEA_API/repos/$env:REPO/releases/$env:RELEASE_ID/assets?name=$env:ASSET_NAME"
|
||||
curl.exe -sS -X POST -H "Authorization: token $token" -H "Content-Type: application/octet-stream" --data-binary "@$env:ASSET" $url
|
||||
if ($LASTEXITCODE -ne 0) { exit 1 }
|
||||
Write-Host "`n已上传 $env:ASSET_NAME"
|
||||
|
||||
# ---------------------------------------------------------------- 3. macOS
|
||||
macos:
|
||||
name: 构建 macOS 前端
|
||||
needs: prepare
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- name: 检出代码
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: 准备 Flutter SDK
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if command -v flutter >/dev/null 2>&1; then
|
||||
echo "runner 已自带 Flutter:"
|
||||
flutter --version
|
||||
else
|
||||
echo "runner 上没有 Flutter,按官方 SDK $FLUTTER_VERSION 自举"
|
||||
case "$(uname -m)" in
|
||||
arm64) SUFFIX="macos_arm64" ;;
|
||||
*) SUFFIX="macos" ;;
|
||||
esac
|
||||
URL="https://storage.googleapis.com/flutter_infra_release/releases/stable/${SUFFIX}/flutter_${SUFFIX}_${FLUTTER_VERSION}-stable.zip"
|
||||
ZIP="$RUNNER_TEMP/flutter.zip"
|
||||
curl -sSL --retry 3 -o "$ZIP" "$URL"
|
||||
rm -rf "$RUNNER_TEMP/flutter"
|
||||
unzip -q "$ZIP" -d "$RUNNER_TEMP"
|
||||
echo "$RUNNER_TEMP/flutter/bin" >> "$GITHUB_PATH"
|
||||
export PATH="$RUNNER_TEMP/flutter/bin:$PATH"
|
||||
flutter --version
|
||||
fi
|
||||
xcodebuild -version || echo "::warning::没找到 xcodebuild,macOS 构建很可能失败"
|
||||
|
||||
- name: 构建前端(release)
|
||||
env:
|
||||
VERSION: ${{ needs.prepare.outputs.base_version }}
|
||||
BUILD_NUMBER: ${{ needs.prepare.outputs.build_number }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
flutter config --no-analytics || true
|
||||
cd "$FRONTEND_DIR"
|
||||
flutter pub get
|
||||
flutter build macos --release --build-name="$VERSION" --build-number="$BUILD_NUMBER"
|
||||
|
||||
- name: 打包
|
||||
id: pack
|
||||
run: |
|
||||
set -euo pipefail
|
||||
APP="$FRONTEND_DIR/build/macos/Build/Products/Release/gc_ui.app"
|
||||
if [ ! -d "$APP" ]; then
|
||||
echo "::error::没有找到 macOS 产物: $APP"
|
||||
exit 1
|
||||
fi
|
||||
case "$(uname -m)" in
|
||||
arm64) ARCH=arm64 ;;
|
||||
*) ARCH=x64 ;;
|
||||
esac
|
||||
NAME="gc-ui-alpha-macos-${ARCH}.zip"
|
||||
mkdir -p dist
|
||||
# 用 ditto 才能保真 .app 内的符号链接与权限,zip -r 会破坏 .app 结构
|
||||
ditto -c -k --sequesterRsrc --keepParent "$APP" "dist/$NAME"
|
||||
ls -lh "dist/$NAME"
|
||||
{
|
||||
echo "asset=dist/$NAME"
|
||||
echo "asset_name=$NAME"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: 上传到预览版
|
||||
env:
|
||||
TOKEN_OVERRIDE: ${{ secrets.RELEASE_TOKEN }}
|
||||
TOKEN_DEFAULT: ${{ github.token }}
|
||||
RELEASE_ID: ${{ needs.prepare.outputs.release_id }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
TOKEN="${TOKEN_OVERRIDE:-$TOKEN_DEFAULT}"
|
||||
if [ -z "${TOKEN:-}" ]; then
|
||||
echo "::error::拿不到 Gitea token"
|
||||
exit 1
|
||||
fi
|
||||
curl -sS -X POST \
|
||||
-H "Authorization: token $TOKEN" \
|
||||
-H "Content-Type: application/octet-stream" \
|
||||
--data-binary "@${{ steps.pack.outputs.asset }}" \
|
||||
"$GITEA_API/repos/$REPO/releases/$RELEASE_ID/assets?name=${{ steps.pack.outputs.asset_name }}"
|
||||
echo
|
||||
echo "已上传 ${{ steps.pack.outputs.asset_name }}"
|
||||
|
||||
# ---------------------------------------------------------------- 4. 发布预览版
|
||||
publish:
|
||||
name: 发布预览版(保持 prerelease,不占用 latest)
|
||||
needs: [prepare, windows, macos]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: 把草稿翻成正式预览版
|
||||
env:
|
||||
TOKEN_OVERRIDE: ${{ secrets.RELEASE_TOKEN }}
|
||||
TOKEN_DEFAULT: ${{ github.token }}
|
||||
RELEASE_ID: ${{ needs.prepare.outputs.release_id }}
|
||||
TAG: ${{ needs.prepare.outputs.tag }}
|
||||
NOTE: ${{ github.event.inputs.note }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
TOKEN="${TOKEN_OVERRIDE:-$TOKEN_DEFAULT}"
|
||||
api="$GITEA_API/repos/$REPO"
|
||||
auth=(-H "Authorization: token $TOKEN")
|
||||
|
||||
code=$(curl -sS -o /tmp/rel.json -w '%{http_code}' "${auth[@]}" "$api/releases/$RELEASE_ID")
|
||||
if [ "$code" != "200" ]; then
|
||||
echo "::error::读不到 Release $RELEASE_ID (HTTP $code)"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
payload=$(python3 - /tmp/rel.json "${NOTE:-}" <<'PY'
|
||||
import json, sys
|
||||
rel = json.load(open(sys.argv[1]))
|
||||
note = (sys.argv[2] or "").strip()
|
||||
body = rel.get("body") or ""
|
||||
if note:
|
||||
body += "\n---\n\n备注:" + note + "\n"
|
||||
print(json.dumps({
|
||||
"body": body,
|
||||
"draft": False, # 可见
|
||||
"prerelease": True, # 关键:永不成为 latest
|
||||
}))
|
||||
PY
|
||||
)
|
||||
|
||||
patched=$(curl -sS -X PATCH "${auth[@]}" -H 'Content-Type: application/json' -d "$payload" "$api/releases/$RELEASE_ID")
|
||||
printf '%s' "$patched" > /tmp/patched.json
|
||||
python3 - <<'PY'
|
||||
import json
|
||||
d = json.load(open('/tmp/patched.json'))
|
||||
print('发布成功:', d.get('html_url'), '| prerelease =', d.get('prerelease'), '| draft =', d.get('draft'))
|
||||
assert d.get('prerelease') is True, 'Release 没有被标记成 prerelease,会顶掉 latest'
|
||||
assert d.get('draft') is False, 'Release 仍是草稿'
|
||||
PY
|
||||
|
||||
- name: 断言 latest 未被占用
|
||||
env:
|
||||
TAG: ${{ needs.prepare.outputs.tag }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
latest_tag=$(curl -sS "$GITEA_API/repos/$REPO/releases/latest" \
|
||||
| python3 -c "import json,sys;print(json.load(sys.stdin).get('tag_name') or '')" || true)
|
||||
echo "本次 tag: $TAG"
|
||||
echo "latest 指向: ${latest_tag:-(空)}"
|
||||
if [ "$latest_tag" = "$TAG" ]; then
|
||||
echo "::error::本次 alpha 成了 latest,prerelease 标记失效"
|
||||
exit 1
|
||||
fi
|
||||
echo "OK:alpha 未占用 latest"
|
||||
@@ -0,0 +1,115 @@
|
||||
# ---------------------------------------------------------------------------
|
||||
# 每晚预发布(Gitea Actions)
|
||||
#
|
||||
# 触发:每天 UTC 13:00(北京时间 21:00)定时执行,也可手动触发。
|
||||
# 行为:
|
||||
# 1. 编译并发布 Linux / Windows 启动器,打成 zip;
|
||||
# 2. 先删除仓库里所有旧的 nightly-* 预发布(Release 与 tag);
|
||||
# 3. 创建当天的新 Release:prerelease=true(不会成为 Latest),
|
||||
# tag 形如 nightly-20261117,并上传构建产物。
|
||||
#
|
||||
# 注意:Gitea Actions 的 cron 按 UTC 计算,故 13:00 UTC = 21:00 Asia/Shanghai。
|
||||
# ---------------------------------------------------------------------------
|
||||
name: 每晚预发布
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 13 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: nightly-prerelease
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
AVALONIA_TELEMETRY_OPTOUT: '1'
|
||||
DOTNET_NOLOGO: '1'
|
||||
DOTNET_CLI_TELEMETRY_OPTOUT: '1'
|
||||
|
||||
jobs:
|
||||
nightly:
|
||||
name: 构建并发布预发布
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
# 优先用仓库 Secret;未配置时回退到 Actions 内置令牌。
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN || github.token }}
|
||||
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
|
||||
steps:
|
||||
- name: 检出代码
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: 安装 .NET 8
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: '8.0.x'
|
||||
|
||||
- name: 发布启动器(linux-x64 / win-x64)
|
||||
run: |
|
||||
set -eu
|
||||
mkdir -p dist
|
||||
dotnet publish GC-BOOT/GC-BOOT.csproj -c Release -r linux-x64 \
|
||||
--self-contained true -p:PublishTrimmed=false -p:EnableWindowsTargeting=true \
|
||||
-o dist/nightly/linux-x64
|
||||
dotnet publish GC-BOOT/GC-BOOT.csproj -c Release -r win-x64 \
|
||||
--self-contained true -p:PublishTrimmed=false -p:EnableWindowsTargeting=true \
|
||||
-o dist/nightly/win-x64
|
||||
(cd dist/nightly && zip -qr ../GC-nightly-linux-x64.zip linux-x64)
|
||||
(cd dist/nightly && zip -qr ../GC-nightly-win-x64.zip win-x64)
|
||||
ls -lh dist/*.zip
|
||||
|
||||
- name: 删除旧的 nightly 预发布
|
||||
run: |
|
||||
set -eu
|
||||
echo "读取现有 Release…"
|
||||
RELEASES=$(curl -sf -H "Authorization: token $GITEA_TOKEN" "$API/releases?limit=100" || echo '[]')
|
||||
echo "$RELEASES" | jq -r '.[] | select(.prerelease == true and (.tag_name | startswith("nightly-"))) | "\(.id) \(.tag_name)"' |
|
||||
while read -r id tag; do
|
||||
[ -z "${id:-}" ] && continue
|
||||
echo "删除旧预发布: $tag (id=$id)"
|
||||
curl -sf -X DELETE -H "Authorization: token $GITEA_TOKEN" "$API/releases/$id" || true
|
||||
curl -sf -X DELETE -H "Authorization: token $GITEA_TOKEN" "$API/tags/$tag" || true
|
||||
done
|
||||
|
||||
- name: 创建当天预发布并上传产物
|
||||
run: |
|
||||
set -eu
|
||||
TAG="nightly-$(date -u +%Y%m%d)"
|
||||
NOW="$(date -u '+%Y-%m-%d %H:%M UTC')"
|
||||
BODY="自动构建 · ${NOW}
|
||||
基于提交 ${GITHUB_SHA}
|
||||
产物:Linux x64 / Windows x64 启动器(未签名,仅供测试)"
|
||||
echo "创建预发布 $TAG"
|
||||
|
||||
PAYLOAD=$(jq -n \
|
||||
--arg tag "$TAG" \
|
||||
--arg sha "${GITHUB_SHA}" \
|
||||
--arg name "Nightly ${TAG}" \
|
||||
--arg body "$BODY" \
|
||||
'{tag_name:$tag, target_commitish:$sha, name:$name, body:$body, prerelease:true, draft:false}')
|
||||
|
||||
RESP=$(curl -sf -X POST \
|
||||
-H "Authorization: token $GITEA_TOKEN" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d "$PAYLOAD" "$API/releases")
|
||||
ID=$(echo "$RESP" | jq -r '.id')
|
||||
echo "Release id=$ID"
|
||||
|
||||
for f in dist/GC-nightly-*.zip; do
|
||||
[ -e "$f" ] || continue
|
||||
echo "上传 $(basename "$f")"
|
||||
curl -sf -X POST \
|
||||
-H "Authorization: token $GITEA_TOKEN" \
|
||||
-F "attachment=@$f" \
|
||||
"$API/releases/$ID/assets?name=$(basename "$f")" || echo "⚠ 上传失败: $f"
|
||||
done
|
||||
|
||||
echo "完成:$TAG 已作为预发布创建(Latest 仍是最近一次正式版)。"
|
||||
|
||||
- name: 保存构建产物(便于排查)
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: nightly-build
|
||||
path: dist/*.zip
|
||||
if-no-files-found: ignore
|
||||
retention-days: 7
|
||||
@@ -0,0 +1,140 @@
|
||||
# ---------------------------------------------------------------------------
|
||||
# PR 审核流水线(Gitea Actions)
|
||||
#
|
||||
# 触发:向 main / gc-ui 提 PR(新建、追加提交、重新打开、取消草稿)时执行。
|
||||
# 覆盖:后端编译、后端自检、前端静态分析 / 测试、依赖漏洞与硬编码密钥扫描,
|
||||
# 最后用 review-gate 汇总,任意一项失败则整条流水线失败(阻止合并)。
|
||||
# ---------------------------------------------------------------------------
|
||||
name: PR 审核
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main, gc-ui]
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
|
||||
concurrency:
|
||||
group: pr-check-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
# Avalonia 遥测任务在 CI 只读目录会写日志失败并中断编译(MSB4018)
|
||||
AVALONIA_TELEMETRY_OPTOUT: '1'
|
||||
DOTNET_NOLOGO: '1'
|
||||
DOTNET_CLI_TELEMETRY_OPTOUT: '1'
|
||||
|
||||
jobs:
|
||||
backend-build:
|
||||
name: 后端编译
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: 检出代码
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: 安装 .NET 8
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: '8.0.x'
|
||||
|
||||
- name: 还原依赖
|
||||
run: dotnet restore GC.sln
|
||||
|
||||
- name: 编译整个解决方案(Release)
|
||||
run: dotnet build GC.sln -c Release --no-restore
|
||||
|
||||
- name: 编译 GC-UI 后端(前后端契约变更时单独验证)
|
||||
run: dotnet build GC-UI/backend/GC.UI.Server/GC.UI.Server.csproj -c Release --no-restore
|
||||
|
||||
backend-test:
|
||||
name: 后端自检
|
||||
runs-on: ubuntu-latest
|
||||
needs: backend-build
|
||||
steps:
|
||||
- name: 检出代码
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: 安装 .NET 8
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: '8.0.x'
|
||||
|
||||
- name: 运行 GC.Tests(含离屏渲染 / 清单校验)
|
||||
run: dotnet run --project GC/src/test/dotnet/GC.Tests/GC.Tests.csproj -c Release
|
||||
|
||||
frontend:
|
||||
name: 前端检查(Flutter)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: 检出代码
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: 安装 Flutter
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: stable
|
||||
cache: true
|
||||
|
||||
- name: 拉取依赖
|
||||
working-directory: GC-UI/frontend
|
||||
run: flutter pub get
|
||||
|
||||
- name: 静态分析
|
||||
working-directory: GC-UI/frontend
|
||||
run: flutter analyze --no-fatal-infos --no-fatal-warnings
|
||||
|
||||
- name: 单元 / 组件测试
|
||||
working-directory: GC-UI/frontend
|
||||
run: flutter test
|
||||
|
||||
security:
|
||||
name: 安全扫描
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: 检出代码
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: 安装 .NET 8
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: '8.0.x'
|
||||
|
||||
- name: 依赖漏洞扫描(含传递依赖)
|
||||
run: |
|
||||
dotnet restore GC.sln
|
||||
dotnet list GC.sln package --vulnerable --include-transitive
|
||||
|
||||
- name: 硬编码密钥 / 口令扫描
|
||||
run: |
|
||||
set +e
|
||||
echo "扫描源码中的疑似明文口令 / 令牌…"
|
||||
MATCHES=$(grep -rInE \
|
||||
--include='*.cs' --include='*.dart' --include='*.yml' --include='*.yaml' \
|
||||
--include='*.sh' --include='*.ps1' --include='*.json' \
|
||||
'(password|passwd|secret|api[_-]?key|access[_-]?token)[[:space:]]*[:=][[:space:]]*["'\''][^"'\''[:space:]]{6,}' \
|
||||
. 2>/dev/null | grep -vE 'example|placeholder|dummy|CHANGEME|YOUR_|\$\{\{')
|
||||
if [ -n "$MATCHES" ]; then
|
||||
echo "$MATCHES"
|
||||
echo "::error::发现疑似硬编码凭据,请改用 Secrets 或环境变量"
|
||||
exit 1
|
||||
fi
|
||||
echo "未发现硬编码凭据"
|
||||
|
||||
review-gate:
|
||||
name: 审核汇总
|
||||
runs-on: ubuntu-latest
|
||||
needs: [backend-build, backend-test, frontend, security]
|
||||
if: always()
|
||||
steps:
|
||||
- name: 检查各阶段结果
|
||||
run: |
|
||||
echo "后端编译: ${{ needs.backend-build.result }}"
|
||||
echo "后端自检: ${{ needs.backend-test.result }}"
|
||||
echo "前端检查: ${{ needs.frontend.result }}"
|
||||
echo "安全扫描: ${{ needs.security.result }}"
|
||||
if [ "${{ needs.backend-build.result }}" != "success" ] || \
|
||||
[ "${{ needs.backend-test.result }}" != "success" ] || \
|
||||
[ "${{ needs.frontend.result }}" != "success" ] || \
|
||||
[ "${{ needs.security.result }}" != "success" ]; then
|
||||
echo "::error::审核未通过:存在失败阶段,请修复后重新提交"
|
||||
exit 1
|
||||
fi
|
||||
echo "审核通过:可以合并"
|
||||
-72
@@ -1,72 +0,0 @@
|
||||
# GC-UI 持续集成
|
||||
|
||||
夜间 alpha 构建的工作流在 [`.gitea/workflows/gc-ui-alpha.yml`](../.gitea/workflows/gc-ui-alpha.yml)。
|
||||
本仓库是自建 Gitea(不是 GitHub),所以目录是 `.gitea/workflows/`,语法与 GitHub Actions 基本一致,
|
||||
差异集中在 **runner 标签** 和 **API 前缀** 两处。
|
||||
|
||||
## 它做什么
|
||||
|
||||
| 任务 | 运行环境 | 产出 |
|
||||
|---|---|---|
|
||||
| `prepare` | `ubuntu-latest` | 算版本号,建一个 **草稿 + prerelease** 的 Release |
|
||||
| `windows` | `windows-latest` | `gc-ui-alpha-windows-x64.zip`(Flutter release 目录) |
|
||||
| `macos` | `macos-latest` | `gc-ui-alpha-macos-<arch>.zip`(`gc_ui.app`,用 `ditto` 打包保真) |
|
||||
| `publish` | `ubuntu-latest` | 两个平台都成功后才把草稿翻成可见,并断言 latest 没被占用 |
|
||||
|
||||
- **定时**:每天 **21:00(Asia/Shanghai)**,cron 写作 `TZ=Asia/Shanghai 0 21 * * *`。
|
||||
Gitea 1.23 起 Actions 的 cron 默认按 **UTC** 解释,所以这里显式带时区前缀;
|
||||
若你的实例不认 `TZ=`,改成等效的 UTC 写法 `0 13 * * *`。
|
||||
- **alpha 不占用 latest**:Gitea 的 `/releases/latest` 只返回「最近一个既非草稿、也非 prerelease」
|
||||
的发布,所以 `prerelease: true` 的夜间版本永远不会成为 latest。`publish` 任务最后会再查一次
|
||||
`/releases/latest`,一旦指向本次 tag 就 fail。
|
||||
- **手动触发**:Actions 页面 Run workflow;或
|
||||
|
||||
```bash
|
||||
curl -X POST -u "USER:TOKEN" \
|
||||
"https://git.xhmcl.com/api/v1/repos/Morris/GC/actions/workflows/gc-ui-alpha.yml/dispatches" \
|
||||
-H 'Content-Type: application/json' -d '{"ref":"gc-ui","inputs":{"note":"手动验证"}}'
|
||||
```
|
||||
|
||||
## 前置条件(缺一不可)
|
||||
|
||||
### 1. 必须有 act_runner,并且带这三个标签
|
||||
|
||||
```bash
|
||||
# 在准备当构建机的机器上(Windows / macOS 各一台,或一台 Linux 只跑 prepare/publish)
|
||||
docker run -d --name gitea-runner \
|
||||
-v /var/run/docker.sock:/var/run/docker.sock \
|
||||
-v /path/to/runner-data:/data \
|
||||
-e GITEA_INSTANCE_URL=https://git.xhmcl.com \
|
||||
-e GITEA_RUNNER_REGISTRATION_TOKEN=<在 站点管理 → Actions → Runners 里拿> \
|
||||
-e GITEA_RUNNER_LABELS=ubuntu-latest:docker://gitea/runner-images:ubuntu-latest,windows-latest:docker://<你的 windows 镜像>,macos-latest:docker://<你的 macos 镜像> \
|
||||
gitea/act_runner:latest
|
||||
```
|
||||
|
||||
关键点:**`runs-on` 的值必须和 runner 上注册的 label 完全一致**,否则任务永远排队。
|
||||
Windows / macOS 的构建**不能**跑在 Linux docker 容器里(一个要 MSVC,一个要 Xcode),
|
||||
所以那两个 label 需要指向真实的 Windows / macOS 机器(自托管 runner)。
|
||||
|
||||
### 2. Flutter SDK
|
||||
|
||||
工作流里有一条「准备 Flutter SDK」:机器上已有 `flutter` 就直接用;没有就按
|
||||
`FLUTTER_VERSION`(默认 3.24.5,需 >= 3.5.4 以匹配 `pubspec.yaml` 的 `sdk: ^3.5.4`)从
|
||||
`storage.googleapis.com` 下载官方 SDK 并写进 `PATH`。所以机器只要能上外网就够,不必预装。
|
||||
网络受限时请预装 Flutter 并确保 `flutter` 在 `PATH` 里。
|
||||
|
||||
Windows 还需要 **VS Build Tools 的「使用 C++ 的桌面开发」工作负载**;macOS 需要 **Xcode**。
|
||||
|
||||
### 3. Token
|
||||
|
||||
优先用仓库 Secrets 里的 `RELEASE_TOKEN`(Gitea 设置 → Actions → Secrets,需 `repo` 权限的个人访问令牌);
|
||||
没配就退回 Gitea 自动注入的 `github.token`。若自动 token 没有 release 权限,
|
||||
创建 Release 那步会报 401/403 —— 这时配一个 `RELEASE_TOKEN` 即可,不用改工作流文件。
|
||||
|
||||
## 本地构建(不经 CI)
|
||||
|
||||
```bash
|
||||
# macOS
|
||||
./GC-UI/build-ui.sh macos
|
||||
|
||||
# Windows
|
||||
GC-UI\build-ui.cmd
|
||||
```
|
||||
@@ -74,6 +74,7 @@ public sealed record LanguageDto(string Code, string Label);
|
||||
public sealed record SettingsDto(
|
||||
string Language,
|
||||
string Theme,
|
||||
string AccentColor,
|
||||
int RenderFps,
|
||||
int MemoryMb,
|
||||
bool MemoryAuto,
|
||||
@@ -96,6 +97,7 @@ public sealed record SettingsDto(
|
||||
public sealed record SettingsPatch(
|
||||
string? Language,
|
||||
string? Theme,
|
||||
string? AccentColor,
|
||||
int? RenderFps,
|
||||
int? MemoryMb,
|
||||
bool? MemoryAuto,
|
||||
|
||||
@@ -53,18 +53,97 @@ var builder = WebApplication.CreateBuilder(new WebApplicationOptions { Args = ar
|
||||
builder.Logging.ClearProviders();
|
||||
builder.WebHost.UseUrls($"http://127.0.0.1:{port}");
|
||||
|
||||
// 本地伴随进程:限制请求体大小、关闭 Server 头、收紧超时,减少被本地恶意页面
|
||||
// 或异常客户端拖垮的攻击面。
|
||||
builder.WebHost.ConfigureKestrel(options =>
|
||||
{
|
||||
options.AddServerHeader = false;
|
||||
options.Limits.MaxRequestBodySize = 2 * 1024 * 1024;
|
||||
options.Limits.RequestHeadersTimeout = TimeSpan.FromSeconds(15);
|
||||
options.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2);
|
||||
options.Limits.MaxConcurrentConnections = 64;
|
||||
});
|
||||
|
||||
// 桌面端(Windows/macOS)走原生 HTTP,不需要 CORS;
|
||||
// 这里放开本机回环来源,方便用 `flutter run -d chrome` 调试界面。
|
||||
builder.Services.AddCors(options => options.AddDefaultPolicy(policy => policy
|
||||
.SetIsOriginAllowed(origin =>
|
||||
Uri.TryCreate(origin, UriKind.Absolute, out var uri) &&
|
||||
(uri.Host == "127.0.0.1" || uri.Host == "localhost"))
|
||||
(uri.Host == "127.0.0.1" || uri.Host == "localhost" || uri.Host == "::1"))
|
||||
.AllowAnyHeader()
|
||||
.AllowAnyMethod()));
|
||||
|
||||
var app = builder.Build();
|
||||
app.UseCors();
|
||||
|
||||
// 设置白名单 / 标识校验用到的规则(只在本进程内使用)。
|
||||
var allowedLanguages = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
|
||||
{ "auto", "zh-CN", "en" };
|
||||
var allowedThemes = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
|
||||
{ "light", "dark", "system" };
|
||||
var accentHexRegex = new System.Text.RegularExpressions.Regex(
|
||||
"^#(?:[0-9A-Fa-f]{6})$", System.Text.RegularExpressions.RegexOptions.Compiled);
|
||||
var safeIdRegex = new System.Text.RegularExpressions.Regex(
|
||||
"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$", System.Text.RegularExpressions.RegexOptions.Compiled);
|
||||
|
||||
// 安全响应头 + Host/Origin 校验(抵御 DNS rebinding 与跨站调用)。
|
||||
app.Use(async (context, next) =>
|
||||
{
|
||||
var headers = context.Response.Headers;
|
||||
headers["X-Content-Type-Options"] = "nosniff";
|
||||
headers["X-Frame-Options"] = "DENY";
|
||||
headers["Referrer-Policy"] = "no-referrer";
|
||||
headers["Content-Security-Policy"] = "default-src 'none'; frame-ancestors 'none'";
|
||||
headers["Cache-Control"] = "no-store";
|
||||
|
||||
var host = context.Request.Host.Host;
|
||||
if (!string.Equals(host, "127.0.0.1", StringComparison.OrdinalIgnoreCase) &&
|
||||
!string.Equals(host, "localhost", StringComparison.OrdinalIgnoreCase) &&
|
||||
!string.Equals(host, "::1", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
||||
return;
|
||||
}
|
||||
|
||||
var origin = context.Request.Headers.Origin.ToString();
|
||||
if (!string.IsNullOrEmpty(origin) &&
|
||||
!(Uri.TryCreate(origin, UriKind.Absolute, out var parsed) &&
|
||||
(parsed.Host == "127.0.0.1" || parsed.Host == "localhost" || parsed.Host == "::1")))
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
||||
return;
|
||||
}
|
||||
|
||||
await next();
|
||||
});
|
||||
|
||||
// 写入类接口做简单限流:单 IP 每秒最多 40 次,防止本地脚本刷爆下载/更新。
|
||||
var writeBuckets =
|
||||
new System.Collections.Concurrent.ConcurrentDictionary<string, (long Window, int Count)>();
|
||||
app.Use(async (context, next) =>
|
||||
{
|
||||
if (HttpMethods.IsPost(context.Request.Method) ||
|
||||
HttpMethods.IsDelete(context.Request.Method))
|
||||
{
|
||||
var key = context.Connection.RemoteIpAddress?.ToString() ?? "local";
|
||||
var now = Environment.TickCount64;
|
||||
var bucket = writeBuckets.AddOrUpdate(
|
||||
key,
|
||||
_ => (now, 1),
|
||||
(_, old) => now - old.Window > 1000 ? (now, 1) : (old.Window, old.Count + 1));
|
||||
|
||||
if (bucket.Count > 40)
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status429TooManyRequests;
|
||||
await context.Response.WriteAsJsonAsync(
|
||||
new LaunchResultDto(false, "请求过于频繁,请稍后再试"));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
await next();
|
||||
});
|
||||
|
||||
// ---- 健康检查 -------------------------------------------------------------
|
||||
|
||||
app.MapGet("/api/health", () => Results.Ok(new HealthDto(
|
||||
@@ -81,6 +160,7 @@ app.MapGet("/api/models", () =>
|
||||
|
||||
app.MapGet("/api/models/{id}/preview", (string id) =>
|
||||
{
|
||||
if (!IsSafeId(id)) return Results.BadRequest();
|
||||
var package = services.Models.Find(id);
|
||||
if (package == null || !File.Exists(package.PreviewPath)) return Results.NotFound();
|
||||
return Results.File(package.PreviewPath, "image/png");
|
||||
@@ -88,6 +168,7 @@ app.MapGet("/api/models/{id}/preview", (string id) =>
|
||||
|
||||
app.MapPost("/api/models/{id}/launch", async (string id) =>
|
||||
{
|
||||
if (!IsSafeId(id)) return Results.BadRequest(new LaunchResultDto(false, "模型标识无效"));
|
||||
var package = services.Models.Find(id);
|
||||
if (package == null) return Results.NotFound(new LaunchResultDto(false, $"没有找到模型 {id}"));
|
||||
|
||||
@@ -99,12 +180,15 @@ app.MapPost("/api/models/{id}/launch", async (string id) =>
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Results.Json(new LaunchResultDto(false, ex.Message), statusCode: 503);
|
||||
// 细节只写日志,不回显给调用方,避免泄漏本机路径等内部信息。
|
||||
Console.Error.WriteLine($"[launch] 启动模型 {id} 失败: {ex}");
|
||||
return Results.Json(new LaunchResultDto(false, "模型启动失败,请查看后端日志"), statusCode: 503);
|
||||
}
|
||||
});
|
||||
|
||||
app.MapDelete("/api/models/{id}", (string id) =>
|
||||
{
|
||||
if (!IsSafeId(id)) return Results.BadRequest(new LaunchResultDto(false, "模型标识无效"));
|
||||
var ok = services.Models.Delete(id);
|
||||
if (ok) services.Models.NotifyChanged();
|
||||
return ok
|
||||
@@ -120,10 +204,21 @@ app.MapPost("/api/settings", (SettingsPatch? patch) =>
|
||||
{
|
||||
if (patch == null) return Results.BadRequest(new LaunchResultDto(false, "缺少设置内容"));
|
||||
|
||||
// 白名单校验:设置项会写进磁盘并被前端直接使用,不接受任意字符串。
|
||||
if (patch.Language != null && !allowedLanguages.Contains(patch.Language))
|
||||
return Results.BadRequest(new LaunchResultDto(false, "不支持的界面语言"));
|
||||
if (patch.Theme != null && !allowedThemes.Contains(patch.Theme))
|
||||
return Results.BadRequest(new LaunchResultDto(false, "不支持的主题"));
|
||||
if (patch.AccentColor != null && !accentHexRegex.IsMatch(patch.AccentColor))
|
||||
return Results.BadRequest(new LaunchResultDto(false, "主题色需为 #RRGGBB"));
|
||||
if (patch.UpdateRepository != null && !IsAllowedRepository(patch.UpdateRepository))
|
||||
return Results.BadRequest(new LaunchResultDto(false, "更新仓库地址不受信任"));
|
||||
|
||||
services.Settings.Apply(s =>
|
||||
{
|
||||
if (patch.Language != null) s.Language = patch.Language;
|
||||
if (patch.Theme != null) s.Theme = patch.Theme;
|
||||
if (patch.AccentColor != null) s.AccentColor = patch.AccentColor.ToUpperInvariant();
|
||||
if (patch.RenderFps.HasValue) s.RenderFps = Math.Clamp(patch.RenderFps.Value, 12, 120);
|
||||
if (patch.MemoryMb.HasValue) s.MemoryMb = Math.Clamp(patch.MemoryMb.Value, 256, 16384);
|
||||
if (patch.MemoryAuto.HasValue) s.MemoryAuto = patch.MemoryAuto.Value;
|
||||
@@ -159,7 +254,8 @@ app.MapPost("/api/sources/select", async (ForceRequest? request) =>
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Results.Json(new LaunchResultDto(false, ex.Message), statusCode: 503);
|
||||
Console.Error.WriteLine($"[sources] 切换模型源失败: {ex}");
|
||||
return Results.Json(new LaunchResultDto(false, "模型源切换失败"), statusCode: 503);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -326,12 +422,16 @@ app.MapPost("/api/shell/open-folder", (PathRequest? request) =>
|
||||
app.MapPost("/api/shell/open-url", (UrlRequest? request) =>
|
||||
{
|
||||
var url = request?.Url;
|
||||
if (string.IsNullOrWhiteSpace(url) || !Uri.TryCreate(url, UriKind.Absolute, out var uri))
|
||||
if (string.IsNullOrWhiteSpace(url) || url.Length > 2048 ||
|
||||
!Uri.TryCreate(url, UriKind.Absolute, out var uri))
|
||||
return Results.BadRequest(new LaunchResultDto(false, "URL 无效"));
|
||||
|
||||
if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)
|
||||
return Results.BadRequest(new LaunchResultDto(false, "只允许 http/https 链接"));
|
||||
|
||||
if (!string.IsNullOrEmpty(uri.UserInfo))
|
||||
return Results.BadRequest(new LaunchResultDto(false, "URL 不允许携带账号密码"));
|
||||
|
||||
Shell.OpenUrl(url!);
|
||||
return Results.Ok(new LaunchResultDto(true, "已打开链接"));
|
||||
});
|
||||
@@ -416,6 +516,7 @@ SourceDto ToSourceDto(ModelSource source) => new(
|
||||
SettingsDto ToSettingsDto() => new(
|
||||
services.Settings.Current.Language,
|
||||
services.Settings.Current.Theme,
|
||||
services.Settings.Current.AccentColor,
|
||||
services.Settings.Current.RenderFps,
|
||||
services.Settings.Current.MemoryMb,
|
||||
services.Settings.Current.MemoryAuto,
|
||||
@@ -464,6 +565,7 @@ ModelSource? ResolveSource(string? sourceId)
|
||||
|
||||
IResult ActOnJob(string id, Action<IDownloadJob> action)
|
||||
{
|
||||
if (!IsSafeId(id)) return Results.BadRequest(new LaunchResultDto(false, "任务标识无效"));
|
||||
var job = services.Downloads.Jobs.FirstOrDefault(j =>
|
||||
j.Id.Equals(id, StringComparison.OrdinalIgnoreCase));
|
||||
if (job == null) return Results.NotFound(new LaunchResultDto(false, $"没有找到任务 {id}"));
|
||||
@@ -501,3 +603,32 @@ bool IsInsideKnownRoot(string path)
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// 路由标识:只允许字母数字开头,后接字母数字/点/下划线/短横线,长度上限 64。
|
||||
// 用于模型 id、任务 id,杜绝 `../` 之类的路径穿越尝试。
|
||||
bool IsSafeId(string? id) => !string.IsNullOrEmpty(id) && safeIdRegex.IsMatch(id);
|
||||
|
||||
// 更新仓库地址:必须是 https、不带账号密码、不是回环/内网 IP。
|
||||
// 防止把本地后端当成 SSRF 跳板去访问内网服务。
|
||||
bool IsAllowedRepository(string value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value)) return false;
|
||||
if (!Uri.TryCreate(value, UriKind.Absolute, out var uri)) return false;
|
||||
if (uri.Scheme != Uri.UriSchemeHttps) return false;
|
||||
if (!string.IsNullOrEmpty(uri.UserInfo)) return false;
|
||||
if (string.Equals(uri.Host, "localhost", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (System.Net.IPAddress.TryParse(uri.Host, out var ip) &&
|
||||
(System.Net.IPAddress.IsLoopback(ip) || IsPrivateAddress(ip)))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool IsPrivateAddress(System.Net.IPAddress ip)
|
||||
{
|
||||
var bytes = ip.GetAddressBytes();
|
||||
if (bytes.Length != 4) return false;
|
||||
return bytes[0] == 10
|
||||
|| (bytes[0] == 172 && bytes[1] >= 16 && bytes[1] <= 31)
|
||||
|| (bytes[0] == 192 && bytes[1] == 168)
|
||||
|| (bytes[0] == 169 && bytes[1] == 254);
|
||||
}
|
||||
@@ -152,6 +152,7 @@ class SettingsInfo {
|
||||
SettingsInfo.fromJson(Map<String, dynamic> json)
|
||||
: language = json['language'] as String? ?? 'auto',
|
||||
theme = json['theme'] as String? ?? 'light',
|
||||
accentColor = json['accentColor'] as String? ?? '#8FB6FF',
|
||||
renderFps = (json['renderFps'] as num?)?.toInt() ?? 120,
|
||||
memoryMb = (json['memoryMb'] as num?)?.toInt() ?? 2048,
|
||||
memoryAuto = json['memoryAuto'] as bool? ?? true,
|
||||
@@ -176,6 +177,7 @@ class SettingsInfo {
|
||||
|
||||
final String language;
|
||||
final String theme;
|
||||
final String accentColor;
|
||||
final int renderFps;
|
||||
final int memoryMb;
|
||||
final bool memoryAuto;
|
||||
@@ -200,6 +202,7 @@ class SettingsPatch {
|
||||
const SettingsPatch({
|
||||
this.language,
|
||||
this.theme,
|
||||
this.accentColor,
|
||||
this.renderFps,
|
||||
this.memoryMb,
|
||||
this.memoryAuto,
|
||||
@@ -212,6 +215,7 @@ class SettingsPatch {
|
||||
|
||||
final String? language;
|
||||
final String? theme;
|
||||
final String? accentColor;
|
||||
final int? renderFps;
|
||||
final int? memoryMb;
|
||||
final bool? memoryAuto;
|
||||
@@ -225,6 +229,7 @@ class SettingsPatch {
|
||||
final map = <String, dynamic>{};
|
||||
if (language != null) map['language'] = language;
|
||||
if (theme != null) map['theme'] = theme;
|
||||
if (accentColor != null) map['accentColor'] = accentColor;
|
||||
if (renderFps != null) map['renderFps'] = renderFps;
|
||||
if (memoryMb != null) map['memoryMb'] = memoryMb;
|
||||
if (memoryAuto != null) map['memoryAuto'] = memoryAuto;
|
||||
|
||||
@@ -2,6 +2,7 @@ import 'package:flutter/foundation.dart';
|
||||
|
||||
import 'api_client.dart';
|
||||
import 'i18n.dart';
|
||||
import 'theme.dart';
|
||||
|
||||
/// 外壳状态:后端客户端 + 设置 + 健康状态 + 更新状态条。
|
||||
///
|
||||
@@ -27,16 +28,24 @@ class ShellController extends ChangeNotifier {
|
||||
|
||||
Future<void> bootstrap() async {
|
||||
try {
|
||||
health = await api.health();
|
||||
settings = await api.settings();
|
||||
// 健康检查与设置并行请求:两者互不依赖,串行会白白多等一次网络往返。
|
||||
final healthFuture = api.health();
|
||||
final settingsFuture = api.settings();
|
||||
health = await healthFuture;
|
||||
settings = await settingsFuture;
|
||||
loadError = null;
|
||||
I18n.setLanguage(settings!.language);
|
||||
_applySettings(settings!);
|
||||
} catch (error) {
|
||||
loadError = error.toString();
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _applySettings(SettingsInfo value) {
|
||||
I18n.setLanguage(value.language);
|
||||
GcPalette.apply(value.accentColor);
|
||||
}
|
||||
|
||||
void goTo(int value) {
|
||||
if (index == value) return;
|
||||
index = value;
|
||||
@@ -47,7 +56,7 @@ class ShellController extends ChangeNotifier {
|
||||
try {
|
||||
settings = await api.settings();
|
||||
loadError = null;
|
||||
I18n.setLanguage(settings!.language);
|
||||
_applySettings(settings!);
|
||||
} catch (error) {
|
||||
loadError = error.toString();
|
||||
}
|
||||
@@ -58,7 +67,7 @@ class ShellController extends ChangeNotifier {
|
||||
try {
|
||||
settings = await api.saveSettings(patch);
|
||||
loadError = null;
|
||||
I18n.setLanguage(settings!.language);
|
||||
_applySettings(settings!);
|
||||
} catch (error) {
|
||||
loadError = error.toString();
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ class I18n {
|
||||
'home.settings': '设置',
|
||||
'home.installed': '已安装模型',
|
||||
'home.count': '{0} 个模型',
|
||||
'home.noDescription': '暂无简介',
|
||||
'home.empty': '模型库还是空的',
|
||||
'home.emptyHint': '启动时会自动检查并下载模型。若当前断网:可把模型文件夹放进 .GC/model/ 后重新打开,或联网后在「下载」页点重试。',
|
||||
'home.emptyAction': '去下载模型',
|
||||
@@ -62,6 +63,12 @@ class I18n {
|
||||
'set.title': '设置',
|
||||
'set.subtitle': '模型源、启动时内存分配与本地存储。',
|
||||
'set.general': '通用',
|
||||
'set.appearance': '外观',
|
||||
'set.accent': '主题颜色',
|
||||
'set.accent.desc': '选择启动器的主色调,按钮、滑块与高亮会同步换色。',
|
||||
'set.accent.custom': '自定义颜色',
|
||||
'set.accent.hexHint': '格式 #RRGGBB,例如 #8FB6FF',
|
||||
'set.accent.invalid': '颜色格式无效,请使用 #RRGGBB',
|
||||
'set.language': '界面语言',
|
||||
'set.language.auto': '跟随系统',
|
||||
'set.fps': '渲染帧率',
|
||||
@@ -140,6 +147,7 @@ class I18n {
|
||||
'home.settings': 'Settings',
|
||||
'home.installed': 'Installed models',
|
||||
'home.count': '{0} models',
|
||||
'home.noDescription': 'No description',
|
||||
'home.empty': 'No models yet',
|
||||
'home.emptyHint': 'Models are checked and downloaded on startup. Offline: drop model folders into .GC/model/ and reopen, or retry from the Download page once online.',
|
||||
'home.emptyAction': 'Get models',
|
||||
@@ -179,6 +187,12 @@ class I18n {
|
||||
'set.title': 'Settings',
|
||||
'set.subtitle': 'Model sources, startup memory allocation and local storage.',
|
||||
'set.general': 'General',
|
||||
'set.appearance': 'Appearance',
|
||||
'set.accent': 'Theme color',
|
||||
'set.accent.desc': 'Pick the launcher accent color; buttons, sliders and highlights follow it.',
|
||||
'set.accent.custom': 'Custom color',
|
||||
'set.accent.hexHint': 'Format #RRGGBB, e.g. #8FB6FF',
|
||||
'set.accent.invalid': 'Invalid color, use #RRGGBB',
|
||||
'set.language': 'Language',
|
||||
'set.language.auto': 'System',
|
||||
'set.fps': 'Render frame rate',
|
||||
|
||||
@@ -6,6 +6,9 @@ import 'shell.dart';
|
||||
import 'theme.dart';
|
||||
|
||||
void main() {
|
||||
// 桌面端无需异步初始化外部插件:尽早绑定并直接渲染首帧,
|
||||
// 让窗口在引擎就绪后立刻出现,后端探测在外壳里异步进行。
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
runApp(const GcUiApp());
|
||||
}
|
||||
|
||||
@@ -25,14 +28,21 @@ class _GcUiAppState extends State<GcUiApp> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// 语言与强调色都会触发重建:只重建 MaterialApp 的主题层,
|
||||
// 不触碰页面状态(页面由 ShellPage 自己持有)。
|
||||
return ValueListenableBuilder<String>(
|
||||
valueListenable: I18n.language,
|
||||
builder: (context, language, _) {
|
||||
return MaterialApp(
|
||||
title: 'Morris GC',
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: buildGcTheme(),
|
||||
home: ShellPage(controller: _controller),
|
||||
return ValueListenableBuilder<Color>(
|
||||
valueListenable: GcPalette.accent,
|
||||
builder: (context, accent, _) {
|
||||
return MaterialApp(
|
||||
title: 'Morris GC',
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: buildGcTheme(),
|
||||
home: ShellPage(controller: _controller),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
+387
-92
@@ -344,7 +344,7 @@ class _HomePageViewState extends State<HomePageView> {
|
||||
}
|
||||
}
|
||||
|
||||
class _ModelCard extends StatelessWidget {
|
||||
class _ModelCard extends StatefulWidget {
|
||||
const _ModelCard({
|
||||
required this.model,
|
||||
required this.previewUrl,
|
||||
@@ -359,110 +359,249 @@ class _ModelCard extends StatelessWidget {
|
||||
final VoidCallback onOpenFolder;
|
||||
final VoidCallback onDelete;
|
||||
|
||||
@override
|
||||
State<_ModelCard> createState() => _ModelCardState();
|
||||
}
|
||||
|
||||
class _ModelCardState extends State<_ModelCard> {
|
||||
bool _hover = false;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SizedBox(
|
||||
width: 336,
|
||||
child: GcCard(
|
||||
padding: EdgeInsets.zero,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
ClipRRect(
|
||||
borderRadius: const BorderRadius.vertical(top: Radius.circular(13)),
|
||||
child: SizedBox(
|
||||
height: 138,
|
||||
width: double.infinity,
|
||||
child: Container(
|
||||
color: const Color(0xFF0B1226),
|
||||
child: model.hasPreview
|
||||
? Image.network(
|
||||
previewUrl,
|
||||
fit: BoxFit.cover,
|
||||
errorBuilder: (context, error, stack) =>
|
||||
const _PreviewFallback(),
|
||||
)
|
||||
: const _PreviewFallback(),
|
||||
),
|
||||
),
|
||||
final model = widget.model;
|
||||
return MouseRegion(
|
||||
onEnter: (_) => setState(() => _hover = true),
|
||||
onExit: (_) => setState(() => _hover = false),
|
||||
cursor: SystemMouseCursors.click,
|
||||
child: AnimatedContainer(
|
||||
duration: const Duration(milliseconds: 160),
|
||||
curve: Curves.easeOut,
|
||||
width: 336,
|
||||
transform: Matrix4.translationValues(0, _hover ? -3 : 0, 0),
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
boxShadow: <BoxShadow>[
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(_hover ? 0.42 : 0.22),
|
||||
blurRadius: _hover ? 26 : 14,
|
||||
offset: Offset(0, _hover ? 10 : 6),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 13, 16, 15),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Row(
|
||||
],
|
||||
),
|
||||
child: GcCard(
|
||||
padding: EdgeInsets.zero,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
// 封面:图片 + 底部渐变遮罩 + 播放提示 + 版本徽章。
|
||||
ClipRRect(
|
||||
borderRadius:
|
||||
const BorderRadius.vertical(top: Radius.circular(13)),
|
||||
child: SizedBox(
|
||||
height: 152,
|
||||
width: double.infinity,
|
||||
child: Stack(
|
||||
fit: StackFit.expand,
|
||||
children: <Widget>[
|
||||
Expanded(
|
||||
child: Text(
|
||||
model.name,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: GcColors.ink,
|
||||
Container(
|
||||
color: const Color(0xFF0B1226),
|
||||
child: model.hasPreview
|
||||
? Image.network(
|
||||
widget.previewUrl,
|
||||
fit: BoxFit.cover,
|
||||
// 只按展示尺寸解码,避免大图占用内存、拖慢首帧。
|
||||
cacheWidth: 672,
|
||||
errorBuilder: (context, error, stack) =>
|
||||
const _PreviewFallback(),
|
||||
)
|
||||
: const _PreviewFallback(),
|
||||
),
|
||||
const DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: <Color>[
|
||||
Color(0x00000000),
|
||||
Color(0x22000000),
|
||||
Color(0xE60A1226),
|
||||
],
|
||||
stops: <double>[0.45, 0.72, 1.0],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
model.metaText,
|
||||
style: const TextStyle(
|
||||
fontSize: 10.5,
|
||||
color: GcColors.faint,
|
||||
Positioned(
|
||||
left: 14,
|
||||
right: 14,
|
||||
bottom: 11,
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
if (model.version.isNotEmpty)
|
||||
_CoverPill(
|
||||
text: 'v${model.version}',
|
||||
color: GcColors.accent,
|
||||
),
|
||||
if (model.author.isNotEmpty) ...<Widget>[
|
||||
const SizedBox(width: 8),
|
||||
Flexible(
|
||||
child: Text(
|
||||
model.author,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(
|
||||
fontSize: 10.5,
|
||||
color: Colors.white70,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
const Spacer(),
|
||||
AnimatedOpacity(
|
||||
opacity: _hover ? 1 : 0,
|
||||
duration: const Duration(milliseconds: 160),
|
||||
child: Container(
|
||||
width: 30,
|
||||
height: 30,
|
||||
decoration: BoxDecoration(
|
||||
color: GcColors.accent.withOpacity(0.9),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: const Icon(Icons.play_arrow_rounded,
|
||||
size: 20, color: Color(0xFF08101F)),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 7),
|
||||
SizedBox(
|
||||
height: 34,
|
||||
child: Text(
|
||||
model.description,
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(
|
||||
fontSize: 12,
|
||||
color: GcColors.muted,
|
||||
height: 1.4,
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 13, 16, 15),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Row(
|
||||
children: <Widget>[
|
||||
Expanded(
|
||||
child: Text(
|
||||
model.name,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(
|
||||
fontSize: 14.5,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: GcColors.ink,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
model.sizeText,
|
||||
style: const TextStyle(
|
||||
fontSize: 10.5,
|
||||
color: GcColors.faint,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 7),
|
||||
// 简介:固定两行高度,避免卡片高低不齐。
|
||||
SizedBox(
|
||||
height: 34,
|
||||
child: Text(
|
||||
model.description.isEmpty
|
||||
? T('home.noDescription')
|
||||
: model.description,
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
height: 1.4,
|
||||
color: model.description.isEmpty
|
||||
? GcColors.faint
|
||||
: GcColors.muted,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (model.tags.isNotEmpty) ...<Widget>[
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
model.tags.join(' · '),
|
||||
style: const TextStyle(
|
||||
fontSize: 10.5,
|
||||
color: GcColors.faint,
|
||||
if (model.tags.isNotEmpty) ...<Widget>[
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 6,
|
||||
runSpacing: 4,
|
||||
children: <Widget>[
|
||||
for (final tag in model.tags.take(3))
|
||||
_CoverPill(
|
||||
text: tag,
|
||||
color: GcColors.muted,
|
||||
subtle: true,
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 13),
|
||||
Row(
|
||||
children: <Widget>[
|
||||
FilledButton.icon(
|
||||
onPressed: widget.onLaunch,
|
||||
icon: const Icon(Icons.play_arrow_rounded, size: 17),
|
||||
label: Text(T('home.launch')),
|
||||
),
|
||||
const Spacer(),
|
||||
TextButton(
|
||||
onPressed: widget.onOpenFolder,
|
||||
child: Text(T('home.open')),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: widget.onDelete,
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor: GcColors.danger,
|
||||
),
|
||||
child: Text(T('home.delete')),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 12),
|
||||
Row(
|
||||
children: <Widget>[
|
||||
FilledButton(
|
||||
onPressed: onLaunch,
|
||||
child: Text(T('home.launch')),
|
||||
),
|
||||
const Spacer(),
|
||||
TextButton(
|
||||
onPressed: onOpenFolder,
|
||||
child: Text(T('home.open')),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: onDelete,
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor: GcColors.danger,
|
||||
),
|
||||
child: Text(T('home.delete')),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 封面上的小胶囊标签(版本 / 标签)。
|
||||
class _CoverPill extends StatelessWidget {
|
||||
const _CoverPill({
|
||||
required this.text,
|
||||
required this.color,
|
||||
this.subtle = false,
|
||||
});
|
||||
|
||||
final String text;
|
||||
final Color color;
|
||||
final bool subtle;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
|
||||
decoration: BoxDecoration(
|
||||
color: subtle ? GcColors.surfaceAlt : color.withOpacity(0.14),
|
||||
borderRadius: BorderRadius.circular(999),
|
||||
border: Border.all(
|
||||
color: subtle ? GcColors.line : color.withOpacity(0.35),
|
||||
),
|
||||
),
|
||||
child: Text(
|
||||
text,
|
||||
style: TextStyle(
|
||||
fontSize: 10,
|
||||
height: 1.1,
|
||||
color: subtle ? GcColors.faint : color,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -473,12 +612,23 @@ class _PreviewFallback extends StatelessWidget {
|
||||
const _PreviewFallback();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => const Center(
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
decoration: const BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
colors: <Color>[Color(0xFF16233C), Color(0xFF0B1226)],
|
||||
),
|
||||
),
|
||||
child: const Center(
|
||||
child: Text(
|
||||
'◎',
|
||||
style: TextStyle(fontSize: 34, color: Color(0xFF1B2A47)),
|
||||
style: TextStyle(fontSize: 34, color: Color(0xFF24365A)),
|
||||
),
|
||||
);
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -1020,6 +1170,8 @@ class _SettingsPageViewState extends State<SettingsPageView> {
|
||||
const SizedBox(height: 18),
|
||||
_generalCard(settings),
|
||||
const SizedBox(height: 16),
|
||||
_appearanceCard(settings),
|
||||
const SizedBox(height: 16),
|
||||
_memoryCard(settings),
|
||||
const SizedBox(height: 16),
|
||||
_sourcesCard(settings),
|
||||
@@ -1106,6 +1258,149 @@ class _SettingsPageViewState extends State<SettingsPageView> {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _appearanceCard(SettingsInfo settings) {
|
||||
final current =
|
||||
GcPalette.parseHex(settings.accentColor) ?? GcPalette.defaultAccent;
|
||||
return GcCard(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
GcSectionTitle(T('set.appearance')),
|
||||
const SizedBox(height: 8),
|
||||
GcHint(T('set.accent.desc')),
|
||||
const SizedBox(height: 14),
|
||||
Wrap(
|
||||
spacing: 10,
|
||||
runSpacing: 10,
|
||||
children: <Widget>[
|
||||
for (final color in GcPalette.presets)
|
||||
_accentSwatch(color, current),
|
||||
_customAccentChip(),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
'${T('set.accent')}: ${GcPalette.toHex(current)}',
|
||||
style: const TextStyle(fontSize: 11.5, color: GcColors.faint),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _accentSwatch(Color color, Color current) {
|
||||
// ignore: deprecated_member_use
|
||||
final selected = color.value == current.value;
|
||||
return Tooltip(
|
||||
message: GcPalette.toHex(color),
|
||||
child: GestureDetector(
|
||||
onTap: () => _applyAccent(GcPalette.toHex(color)),
|
||||
child: Container(
|
||||
width: 36,
|
||||
height: 36,
|
||||
decoration: BoxDecoration(
|
||||
color: color,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(
|
||||
color: selected ? Colors.white : Colors.transparent,
|
||||
width: 2,
|
||||
),
|
||||
boxShadow: <BoxShadow>[
|
||||
BoxShadow(
|
||||
color: color.withOpacity(selected ? 0.55 : 0.18),
|
||||
blurRadius: selected ? 14 : 6,
|
||||
),
|
||||
],
|
||||
),
|
||||
child: selected
|
||||
? const Icon(Icons.check_rounded,
|
||||
size: 19, color: Color(0xFF08101F))
|
||||
: null,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _customAccentChip() {
|
||||
return MouseRegion(
|
||||
cursor: SystemMouseCursors.click,
|
||||
child: GestureDetector(
|
||||
onTap: _pickCustomAccent,
|
||||
child: Container(
|
||||
height: 36,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12),
|
||||
decoration: BoxDecoration(
|
||||
color: GcColors.surfaceAlt,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(color: GcColors.line),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: <Widget>[
|
||||
const Icon(Icons.colorize_rounded,
|
||||
size: 16, color: GcColors.faint),
|
||||
const SizedBox(width: 6),
|
||||
Text(
|
||||
T('set.accent.custom'),
|
||||
style: const TextStyle(fontSize: 11.5, color: GcColors.muted),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _pickCustomAccent() async {
|
||||
final controller = TextEditingController(
|
||||
text: GcPalette.toHex(GcPalette.accent.value),
|
||||
);
|
||||
final hex = await showDialog<String>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
backgroundColor: GcColors.surfaceAlt,
|
||||
title: Text(T('set.accent.custom')),
|
||||
content: TextField(
|
||||
controller: controller,
|
||||
autofocus: true,
|
||||
style: const TextStyle(color: GcColors.ink),
|
||||
decoration: InputDecoration(
|
||||
hintText: '#8FB6FF',
|
||||
hintStyle: const TextStyle(color: GcColors.faint),
|
||||
helperText: T('set.accent.hexHint'),
|
||||
helperStyle: const TextStyle(color: GcColors.faint, fontSize: 11),
|
||||
),
|
||||
onSubmitted: (value) => Navigator.of(context).pop(value),
|
||||
),
|
||||
actions: <Widget>[
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: Text(T('common.cancel')),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.of(context).pop(controller.text),
|
||||
child: Text(T('common.confirm')),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
controller.dispose();
|
||||
if (hex != null) await _applyAccent(hex);
|
||||
}
|
||||
|
||||
Future<void> _applyAccent(String hex) async {
|
||||
final parsed = GcPalette.parseHex(hex);
|
||||
if (parsed == null) {
|
||||
if (mounted) setState(() => _status = T('set.accent.invalid'));
|
||||
return;
|
||||
}
|
||||
final normalized = GcPalette.toHex(parsed);
|
||||
GcPalette.apply(normalized); // 立即预览
|
||||
await widget.controller
|
||||
.saveSettings(SettingsPatch(accentColor: normalized));
|
||||
if (mounted) setState(() => _status = T('common.applied'));
|
||||
}
|
||||
|
||||
Widget _memoryCard(SettingsInfo settings) {
|
||||
return GcCard(
|
||||
child: Column(
|
||||
@@ -1508,7 +1803,7 @@ class _AboutPageViewState extends State<AboutPageView> {
|
||||
? null
|
||||
: NetworkImage(contributor.avatarUrl!),
|
||||
child: contributor.avatarUrl == null
|
||||
? const Text('◎',
|
||||
? Text('◎',
|
||||
style: TextStyle(
|
||||
fontSize: 12, color: GcColors.accent))
|
||||
: null,
|
||||
|
||||
@@ -31,6 +31,10 @@ class ShellPage extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _ShellPageState extends State<ShellPage> {
|
||||
/// 页面缓存:键为「索引:语言」。同一个页面只构建一次,切走时用
|
||||
/// [Offstage] 保活(不参与布局/绘制),切回来无需重建、状态也不丢。
|
||||
final Map<String, Widget> _pages = <String, Widget>{};
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
@@ -78,7 +82,27 @@ class _ShellPageState extends State<ShellPage> {
|
||||
);
|
||||
}
|
||||
|
||||
switch (controller.index) {
|
||||
// 只构建当前页;其余已访问页面保留在树上但处于 Offstage。
|
||||
final key = '${controller.index}:${I18n.language.value}';
|
||||
_pages.putIfAbsent(key, () => _buildPage(controller, controller.index));
|
||||
|
||||
final visibleKey = key;
|
||||
return Stack(
|
||||
children: <Widget>[
|
||||
for (final entry in _pages.entries)
|
||||
Offstage(
|
||||
offstage: entry.key != visibleKey,
|
||||
child: TickerMode(
|
||||
enabled: entry.key == visibleKey,
|
||||
child: entry.value,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildPage(ShellController controller, int index) {
|
||||
switch (index) {
|
||||
case 1:
|
||||
return DownloadPageView(controller: controller);
|
||||
case 2:
|
||||
@@ -241,7 +265,8 @@ class _UpdateBar extends StatelessWidget {
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 9),
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
const Text('⟳', style: TextStyle(fontSize: 16, color: GcColors.accent)),
|
||||
Text('⟳',
|
||||
style: TextStyle(fontSize: 16, color: GcColors.accent)),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
|
||||
@@ -1,5 +1,58 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// 主题强调色(可在设置页自定义,并持久化到后端 settings.accentColor)。
|
||||
///
|
||||
/// 用 [ValueNotifier] 持有当前颜色:设置页改色后,`main.dart` 监听到变化
|
||||
/// 会重建 `MaterialApp.theme`,所有引用 [GcColors.accent] 的组件随之换色。
|
||||
class GcPalette {
|
||||
GcPalette._();
|
||||
|
||||
/// 默认强调色,与 Avalonia 启动器一致。
|
||||
static const Color defaultAccent = Color(0xFF8FB6FF);
|
||||
|
||||
static final ValueNotifier<Color> accent =
|
||||
ValueNotifier<Color>(defaultAccent);
|
||||
|
||||
/// 设置页可选的预设色板。
|
||||
static const List<Color> presets = <Color>[
|
||||
Color(0xFF8FB6FF), // 极光蓝(默认)
|
||||
Color(0xFF7C6CFF), // 星云紫
|
||||
Color(0xFF4FD1C5), // 湖水青
|
||||
Color(0xFF6BE3A2), // 极光绿
|
||||
Color(0xFFFFC46B), // 暖阳橙
|
||||
Color(0xFFFF8FB1), // 樱粉
|
||||
Color(0xFFFF7A7A), // 珊瑚红
|
||||
Color(0xFFB0BEC5), // 石墨灰
|
||||
];
|
||||
|
||||
/// 把 `#RRGGBB` / `RRGGBB` 解析为颜色;非法返回 null。
|
||||
static Color? parseHex(String? value) {
|
||||
if (value == null) return null;
|
||||
var hex = value.trim();
|
||||
if (hex.startsWith('#')) hex = hex.substring(1);
|
||||
if (hex.length == 8) hex = hex.substring(2); // 忽略 alpha
|
||||
if (hex.length != 6) return null;
|
||||
final parsed = int.tryParse(hex, radix: 16);
|
||||
if (parsed == null) return null;
|
||||
return Color(0xFF000000 | parsed);
|
||||
}
|
||||
|
||||
/// 颜色转 `#RRGGBB`。
|
||||
static String toHex(Color color) {
|
||||
// ignore: deprecated_member_use
|
||||
final rgb = color.value & 0xFFFFFF;
|
||||
return '#${rgb.toRadixString(16).padLeft(6, '0').toUpperCase()}';
|
||||
}
|
||||
|
||||
/// 应用颜色(来自后端设置或用户点选)。
|
||||
static void apply(String? hex) {
|
||||
final color = parseHex(hex);
|
||||
if (color == null) return;
|
||||
// ignore: deprecated_member_use
|
||||
if (accent.value.value != color.value) accent.value = color;
|
||||
}
|
||||
}
|
||||
|
||||
/// 与 Avalonia 启动器一致的深色配色。
|
||||
class GcColors {
|
||||
GcColors._();
|
||||
@@ -9,23 +62,37 @@ class GcColors {
|
||||
static const Color surface = Color(0xFF111C33);
|
||||
static const Color surfaceAlt = Color(0xFF16233C);
|
||||
static const Color line = Color(0xFF1B2740);
|
||||
static const Color accent = Color(0xFF8FB6FF);
|
||||
static const Color accentStrong = Color(0xFF4C7DFF);
|
||||
static const Color ink = Color(0xFFF2F6FF);
|
||||
static const Color muted = Color(0xFFA9B8D4);
|
||||
static const Color faint = Color(0xFF7C90B4);
|
||||
static const Color warn = Color(0xFFFFC46B);
|
||||
static const Color danger = Color(0xFFFF7A7A);
|
||||
static const Color ok = Color(0xFF6BE3A2);
|
||||
|
||||
/// 当前强调色(动态,跟随设置)。
|
||||
static Color get accent => GcPalette.accent.value;
|
||||
|
||||
/// 强调色的加深版本,用于主按钮 / 轨道。
|
||||
static Color get accentStrong => _strongen(accent);
|
||||
|
||||
static Color _strongen(Color color) {
|
||||
final hsl = HSLColor.fromColor(color);
|
||||
return hsl
|
||||
.withSaturation((hsl.saturation + 0.12).clamp(0.0, 1.0))
|
||||
.withLightness((hsl.lightness - 0.10).clamp(0.0, 1.0))
|
||||
.toColor();
|
||||
}
|
||||
}
|
||||
|
||||
ThemeData buildGcTheme() {
|
||||
final base = ThemeData.dark(useMaterial3: true);
|
||||
final accent = GcColors.accent;
|
||||
final accentStrong = GcColors.accentStrong;
|
||||
return base.copyWith(
|
||||
scaffoldBackgroundColor: GcColors.appBg,
|
||||
colorScheme: base.colorScheme.copyWith(
|
||||
primary: GcColors.accentStrong,
|
||||
secondary: GcColors.accent,
|
||||
primary: accentStrong,
|
||||
secondary: accent,
|
||||
surface: GcColors.surface,
|
||||
error: GcColors.danger,
|
||||
),
|
||||
@@ -40,24 +107,24 @@ ThemeData buildGcTheme() {
|
||||
margin: EdgeInsets.zero,
|
||||
),
|
||||
sliderTheme: base.sliderTheme.copyWith(
|
||||
activeTrackColor: GcColors.accentStrong,
|
||||
thumbColor: GcColors.accent,
|
||||
activeTrackColor: accentStrong,
|
||||
thumbColor: accent,
|
||||
inactiveTrackColor: GcColors.line,
|
||||
),
|
||||
switchTheme: SwitchThemeData(
|
||||
thumbColor: WidgetStateProperty.resolveWith(
|
||||
(states) => states.contains(WidgetState.selected)
|
||||
? GcColors.accent
|
||||
? accent
|
||||
: GcColors.faint,
|
||||
),
|
||||
trackColor: WidgetStateProperty.resolveWith(
|
||||
(states) => states.contains(WidgetState.selected)
|
||||
? GcColors.accentStrong.withOpacity(0.45)
|
||||
? accentStrong.withOpacity(0.45)
|
||||
: GcColors.line,
|
||||
),
|
||||
),
|
||||
progressIndicatorTheme: const ProgressIndicatorThemeData(
|
||||
color: GcColors.accent,
|
||||
progressIndicatorTheme: ProgressIndicatorThemeData(
|
||||
color: accent,
|
||||
linearTrackColor: GcColors.line,
|
||||
),
|
||||
tooltipTheme: const TooltipThemeData(
|
||||
|
||||
@@ -13,6 +13,9 @@ public sealed class AppSettings
|
||||
/// <summary>light | dark</summary>
|
||||
public string Theme { get; set; } = "light";
|
||||
|
||||
/// <summary>主题强调色(#RRGGBB),由设置页自定义并持久化。</summary>
|
||||
public string AccentColor { get; set; } = "#8FB6FF";
|
||||
|
||||
/// <summary>渲染帧率:24 / 30 / 60 / 90 / 120(上限 120,关闭 VSync 同步)</summary>
|
||||
public int RenderFps { get; set; } = 120;
|
||||
|
||||
@@ -37,8 +40,8 @@ public sealed class AppSettings
|
||||
/// <summary>启动时检查模型 / 启动器是否为最新版。</summary>
|
||||
public bool AutoUpdateOnStartup { get; set; } = true;
|
||||
|
||||
/// <summary>默认更新仓库地址。</summary>
|
||||
public string UpdateRepository { get; set; } = "https://gitcode.com/Morris_1/GC";
|
||||
/// <summary>默认更新仓库地址(暂时只使用 Xhmcl,GitCode 实现保留但不再调用)。</summary>
|
||||
public string UpdateRepository { get; set; } = "https://git.xhmcl.com/Morris/GC";
|
||||
|
||||
/// <summary>版本清单地址覆盖(留空则按 UpdateRepository 拼接)。</summary>
|
||||
public string? UpdateManifestUrl { get; set; }
|
||||
|
||||
@@ -15,6 +15,9 @@ public sealed class Contributor
|
||||
/// <summary>提交次数(API 里的 contributions)。</summary>
|
||||
public int Contributions { get; set; }
|
||||
|
||||
/// <summary>接口直接返回的头像地址(Gitea 的 avatar_url);为空时按邮箱哈希生成。</summary>
|
||||
public string? Avatar { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 登录名 -> 展示名。GitCode 的 contributors 接口只返回账号登录名,
|
||||
/// 不返回真实姓名,这里做一层映射,让关于页显示作者想展示的名字。
|
||||
@@ -24,14 +27,16 @@ public sealed class Contributor
|
||||
["Morris_1"] = "Morris"
|
||||
};
|
||||
|
||||
/// <summary>头像地址:GitCode 用邮箱哈希拼头像,取不到时返回 null。</summary>
|
||||
/// <summary>头像地址:优先用接口返回的头像,否则按邮箱哈希拼 GitCode 头像。</summary>
|
||||
public string? AvatarUrl =>
|
||||
string.IsNullOrWhiteSpace(Email)
|
||||
? null
|
||||
: $"https://cdn-img.gitcode.com/avatar/{Convert.ToHexString(
|
||||
System.Security.Cryptography.MD5.HashData(
|
||||
System.Text.Encoding.UTF8.GetBytes(Email!.Trim().ToLowerInvariant())))
|
||||
.ToLowerInvariant()}";
|
||||
!string.IsNullOrWhiteSpace(Avatar)
|
||||
? Avatar
|
||||
: string.IsNullOrWhiteSpace(Email)
|
||||
? null
|
||||
: $"https://cdn-img.gitcode.com/avatar/{Convert.ToHexString(
|
||||
System.Security.Cryptography.MD5.HashData(
|
||||
System.Text.Encoding.UTF8.GetBytes(Email!.Trim().ToLowerInvariant())))
|
||||
.ToLowerInvariant()}";
|
||||
|
||||
public string DisplayName
|
||||
{
|
||||
@@ -59,21 +64,26 @@ public static class ContributorsService
|
||||
return c;
|
||||
}
|
||||
|
||||
/// <summary>默认仓库的 contributors 接口地址。</summary>
|
||||
/// <summary>按仓库地址推导贡献者接口:Xhmcl(Gitea) 与 GitCode 结构不同。</summary>
|
||||
public static string BuildUrl(string repository)
|
||||
{
|
||||
var raw = string.IsNullOrWhiteSpace(repository)
|
||||
? SourcePreset.GitCode.HomeUrl : repository.Trim();
|
||||
? SourcePreset.Xhmcl.HomeUrl : repository.Trim();
|
||||
if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri))
|
||||
return "https://api.gitcode.com/api/v5/repos/Morris_1/GC/contributors";
|
||||
return "https://git.xhmcl.com/api/v1/repos/Morris/GC/collaborators";
|
||||
|
||||
var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length < 2)
|
||||
return "https://api.gitcode.com/api/v5/repos/Morris_1/GC/contributors";
|
||||
return "https://git.xhmcl.com/api/v1/repos/Morris/GC/collaborators";
|
||||
|
||||
var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
|
||||
? parts[1][..^4] : parts[1];
|
||||
return $"https://api.gitcode.com/api/v5/repos/{parts[0]}/{repo}/contributors";
|
||||
|
||||
// GitCode 代码保留,仅在仓库确实指向 GitCode 时才走它。
|
||||
if (uri.Host.Contains("gitcode.com", StringComparison.OrdinalIgnoreCase))
|
||||
return $"https://api.gitcode.com/api/v5/repos/{parts[0]}/{repo}/contributors";
|
||||
|
||||
return $"https://{uri.Host}/api/v1/repos/{parts[0]}/{repo}/collaborators";
|
||||
}
|
||||
|
||||
public static async Task<List<Contributor>> FetchAsync(string repository, CancellationToken ct = default)
|
||||
@@ -88,12 +98,33 @@ public static class ContributorsService
|
||||
var trimmed = text.TrimStart();
|
||||
if (trimmed.Length == 0 || trimmed[0] != '[') return new List<Contributor>();
|
||||
|
||||
var list = JsonSerializer.Deserialize<List<Contributor>>(text, new JsonSerializerOptions
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
var list = new List<Contributor>();
|
||||
foreach (var item in doc.RootElement.EnumerateArray())
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
}) ?? new List<Contributor>();
|
||||
// Gitea: login / avatar_url;GitCode: name / email / contributions。
|
||||
if (item.TryGetProperty("login", out var login))
|
||||
{
|
||||
list.Add(new Contributor
|
||||
{
|
||||
Name = login.GetString() ?? "",
|
||||
Avatar = item.TryGetProperty("avatar_url", out var avatar)
|
||||
? avatar.GetString() : null
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
list.Add(new Contributor
|
||||
{
|
||||
Name = item.TryGetProperty("name", out var name)
|
||||
? name.GetString() ?? "" : "",
|
||||
Email = item.TryGetProperty("email", out var email)
|
||||
? email.GetString() : null,
|
||||
Contributions = item.TryGetProperty("contributions", out var c) &&
|
||||
c.TryGetInt32(out var count) ? count : 0
|
||||
});
|
||||
}
|
||||
|
||||
// 按提交数从多到少,贡献最多的排最前
|
||||
list.Sort((a, b) => b.Contributions.CompareTo(a.Contributions));
|
||||
return list;
|
||||
}
|
||||
|
||||
@@ -18,10 +18,11 @@ public sealed class SettingsService
|
||||
public void Load()
|
||||
{
|
||||
Current = Json.Read<AppSettings>(_paths.SettingsFile) ?? new AppSettings();
|
||||
if (Current.UpdateRepository.Contains("gitcode.com/2509_92447106/GC", StringComparison.OrdinalIgnoreCase))
|
||||
|
||||
// 暂时停用 GitCode:旧配置里的 GitCode 仓库地址统一迁到 Xhmcl。
|
||||
if (Current.UpdateRepository.Contains("gitcode.com", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Current.UpdateRepository = Current.UpdateRepository.Replace(
|
||||
"2509_92447106", "Morris_1", StringComparison.OrdinalIgnoreCase);
|
||||
Current.UpdateRepository = SourcePreset.Xhmcl.HomeUrl;
|
||||
Save();
|
||||
}
|
||||
SeedDefaultSource();
|
||||
@@ -29,12 +30,11 @@ public sealed class SettingsService
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 只允许两个内置源:Xhmcl 与 GitCode(同一份仓库的两个镜像)。
|
||||
/// 不再支持用户自定义源 —— 每次加载都把 Sources 规整成这两条,
|
||||
/// 老配置里的自定义源会被清理掉。
|
||||
/// 当前只启用 Xhmcl 一个内置源。GitCode 的定义与下载实现保留在代码里,
|
||||
/// 但不再参与测速 / 下载 / 更新;恢复时把 GitCode 加回 <see cref="SourcePreset.All"/> 即可。
|
||||
/// </summary>
|
||||
public const string DefaultSourceId = "gitcode";
|
||||
public const string DefaultSourceUrl = "https://gitcode.com/Morris_1/GC";
|
||||
public const string DefaultSourceId = "xhmcl";
|
||||
public const string DefaultSourceUrl = "https://git.xhmcl.com/Morris/GC";
|
||||
|
||||
private void SeedDefaultSource()
|
||||
{
|
||||
|
||||
@@ -5,10 +5,11 @@ using System.Linq;
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 内置下载源。只允许这两个,不再支持用户自定义源。
|
||||
/// 内置下载源。
|
||||
///
|
||||
/// 两个源的内容是同一份仓库(同一个 version.json、同一批模型),
|
||||
/// 区别只是**托管在哪台服务器**上;启动时探测两者延迟,取快的那个下载。
|
||||
/// 目前只启用 Xhmcl;GitCode 的 preset 与下载实现仍保留在代码中,
|
||||
/// 但不参与测速 / 下载 / 更新。两个源本来指向同一份仓库内容,
|
||||
/// 区别只是托管服务器;恢复双源时把 GitCode 加回 <see cref="All"/>。
|
||||
/// </summary>
|
||||
public sealed class SourcePreset
|
||||
{
|
||||
@@ -63,17 +64,23 @@ public sealed class SourcePreset
|
||||
Branch = "main"
|
||||
};
|
||||
|
||||
public static readonly SourcePreset[] All = { Xhmcl, GitCode };
|
||||
/// <summary>
|
||||
/// 当前启用的源:暂时只保留 Xhmcl。GitCode 的定义与实现仍保留在代码里,
|
||||
/// 但不参与测速、下载与更新(需要恢复时把 GitCode 加回这个数组即可)。
|
||||
/// </summary>
|
||||
public static readonly SourcePreset[] All = { Xhmcl };
|
||||
|
||||
public static SourcePreset? Find(string? id) =>
|
||||
All.FirstOrDefault(p => string.Equals(p.Id, id, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>把任意仓库地址映射到这两个内置源之一(用于兼容旧配置)。</summary>
|
||||
/// <summary>把任意仓库地址映射到启用的内置源(用于兼容旧配置)。</summary>
|
||||
public static SourcePreset Detect(string? url)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(url)) return GitCode;
|
||||
var u = url!.ToLowerInvariant();
|
||||
if (u.Contains("xhmcl.com")) return Xhmcl;
|
||||
return GitCode;
|
||||
if (!string.IsNullOrWhiteSpace(url) &&
|
||||
url!.Contains("xhmcl.com", StringComparison.OrdinalIgnoreCase))
|
||||
return Xhmcl;
|
||||
|
||||
// 旧配置里的 GitCode 地址不再作为下载源,统一落到 Xhmcl。
|
||||
return Xhmcl;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user