From 0d383f96fbd82da9ec64203ddb6029f1529f56f7 Mon Sep 17 00:00:00 2001 From: chenmoyuan1214 Date: Sat, 21 Nov 2026 19:34:46 +0800 Subject: [PATCH 1/7] =?UTF-8?q?ci:=20=E4=BF=AE=E6=AD=A3=20pr-review=20?= =?UTF-8?q?=E7=9A=84=E5=86=B2=E7=AA=81=E5=88=A4=E6=96=AD=E4=B8=8E=E9=9D=99?= =?UTF-8?q?=E6=80=81=E5=88=86=E6=9E=90=E9=98=88=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - mergeable=true 表示「可以合并」,之前误当成冲突,改为 false 才算冲突 - mergeable 为 null 时多等几轮(GitHub 异步计算) - flutter analyze 加 --no-fatal-infos --no-fatal-warnings: 仓库里有 44 条历史 warning/info,不该卡住合并,只让 error 失败 - 结论里区分「error 数」与「历史 warning/info 数」 --- .github/workflows/pr-review.yml | 38 ++++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/.github/workflows/pr-review.yml b/.github/workflows/pr-review.yml index a9e7bc4..4fd1e25 100644 --- a/.github/workflows/pr-review.yml +++ b/.github/workflows/pr-review.yml @@ -61,19 +61,20 @@ jobs: echo "ahead=$AHEAD" >> "$GITHUB_OUTPUT" # GitHub 的 mergeable 字段是异步计算的,前几次可能为 null,重试几次 + MERGEABLE="null" STATE="unknown" - CONFLICT="unknown" - for i in 1 2 3 4 5; do - INFO=$(gh api "repos/${{ github.repository }}/pulls/${PR}" --jq '.mergeable, .mergeable_state' 2>/dev/null || true) - CONFLICT=$(printf '%s\n' "$INFO" | sed -n '1p') - STATE=$(printf '%s\n' "$INFO" | sed -n '2p') - if [ "$CONFLICT" = "true" ] || [ "$CONFLICT" = "false" ]; then break; fi - sleep 3 + for i in 1 2 3 4 5 6 7 8; do + read -r MERGEABLE STATE <<< "$(gh api "repos/${{ github.repository }}/pulls/${PR}" \ + --jq '"\(.mergeable | tostring) \(.mergeable_state // "unknown")"' 2>/dev/null || echo 'null unknown')" + # mergeable 只有 true / false 才是算完的结果,null 说明还在算 + if [ "$MERGEABLE" = "true" ] || [ "$MERGEABLE" = "false" ]; then break; fi + sleep 4 done - case "$CONFLICT" in - false) echo "conflict=ok" >> "$GITHUB_OUTPUT" ;; - true) echo "conflict=conflict" >> "$GITHUB_OUTPUT" ;; + # 注意语义:mergeable=true 表示「可以合并」,false 才是冲突 + case "$MERGEABLE" in + true) echo "conflict=ok" >> "$GITHUB_OUTPUT" ;; + false) echo "conflict=conflict" >> "$GITHUB_OUTPUT" ;; *) echo "conflict=unknown" >> "$GITHUB_OUTPUT" ;; esac echo "merge_state=$STATE" >> "$GITHUB_OUTPUT" @@ -94,7 +95,9 @@ jobs: run: | set -o pipefail flutter pub get 2>&1 | tee ../flutter-pubget.log - flutter analyze 2>&1 | tee ../flutter-analyze.log + # 仓库里已有历史 warning / info,不应该让它们卡住合并; + # 只把真正的 error 当失败。 + flutter analyze --no-fatal-infos --no-fatal-warnings 2>&1 | tee ../flutter-analyze.log exit ${PIPESTATUS[0]} - id: summary @@ -111,13 +114,22 @@ jobs: set -e bad=0 + # 静态分析结果分「错误」和「警告/提示」:只有错误才算不通过 + FE=$(grep -cE '^ *error •' flutter-analyze.log 2>/dev/null || true); FE=${FE:-0} + FW=$(grep -cE '^ *(warning|info) •' flutter-analyze.log 2>/dev/null || true); FW=${FW:-0} + case "$DOTNET_OUTCOME" in success) DOTNET_LINE="✅ .NET 编译通过" ;; *) DOTNET_LINE="❌ .NET 编译失败"; bad=1 ;; esac case "$FLUTTER_OUTCOME" in - success) FLUTTER_LINE="✅ Flutter 静态分析通过" ;; - *) FLUTTER_LINE="❌ Flutter 静态分析有问题"; bad=1 ;; + success) + if [ "$FW" -gt 0 ]; then + FLUTTER_LINE="✅ 无错误(另有 ${FW} 条历史 warning/info,未阻断)" + else + FLUTTER_LINE="✅ 无错误" + fi ;; + *) FLUTTER_LINE="❌ 有 ${FE} 个 error"; bad=1 ;; esac case "$CONFLICT" in ok) CONFLICT_LINE="✅ 与目标分支无冲突" ;; -- 2.54.0 From f64f2708a17dfecd8239cf973ae87679b8493336 Mon Sep 17 00:00:00 2001 From: chenmoyuan1214 Date: Sat, 21 Nov 2026 19:37:43 +0800 Subject: [PATCH 2/7] =?UTF-8?q?ci:=20=E4=BF=AE=20pr-review=20=E6=97=A5?= =?UTF-8?q?=E5=BF=97=E8=B7=AF=E5=BE=84=E4=B8=8D=E4=B8=80=E8=87=B4=E5=AF=BC?= =?UTF-8?q?=E8=87=B4=E3=80=8C(=E6=97=A0=E6=97=A5=E5=BF=97)=E3=80=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit flutter 步骤在 GC-UI/frontend 下运行,tee 写到 ../flutter-analyze.log(= GC-UI/), 但汇总步骤在仓库根目录读 flutter-analyze.log,永远读不到。 改为统一用 $GITHUB_WORKSPACE 绝对路径;日志缺失时提示「步骤可能未执行」。 --- .github/workflows/pr-review.yml | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/.github/workflows/pr-review.yml b/.github/workflows/pr-review.yml index 4fd1e25..f1a60bf 100644 --- a/.github/workflows/pr-review.yml +++ b/.github/workflows/pr-review.yml @@ -84,8 +84,9 @@ jobs: continue-on-error: true run: | set -o pipefail - dotnet restore GC.sln > dotnet-restore.log 2>&1 - dotnet build GC.sln -c Release --no-restore 2>&1 | tee dotnet-build.log + dotnet restore GC.sln > "$GITHUB_WORKSPACE/dotnet-restore.log" 2>&1 + dotnet build GC.sln -c Release --no-restore 2>&1 \ + | tee "$GITHUB_WORKSPACE/dotnet-build.log" exit ${PIPESTATUS[0]} - id: flutter @@ -94,10 +95,12 @@ jobs: working-directory: GC-UI/frontend run: | set -o pipefail - flutter pub get 2>&1 | tee ../flutter-pubget.log + # 日志统一写到仓库根目录:后面的汇总步骤在根目录读,路径必须一致 + flutter pub get 2>&1 | tee "$GITHUB_WORKSPACE/flutter-pubget.log" # 仓库里已有历史 warning / info,不应该让它们卡住合并; # 只把真正的 error 当失败。 - flutter analyze --no-fatal-infos --no-fatal-warnings 2>&1 | tee ../flutter-analyze.log + flutter analyze --no-fatal-infos --no-fatal-warnings 2>&1 \ + | tee "$GITHUB_WORKSPACE/flutter-analyze.log" exit ${PIPESTATUS[0]} - id: summary @@ -165,10 +168,17 @@ jobs: echo echo '```' echo "== dotnet build(尾部 40 行)==" - tail -40 dotnet-build.log 2>/dev/null || echo "(无日志)" + tail -40 dotnet-build.log 2>/dev/null || echo "(日志缺失:编译步骤可能未执行)" echo echo "== flutter analyze(尾部 40 行)==" - tail -40 flutter-analyze.log 2>/dev/null || echo "(无日志)" + if [ -f flutter-analyze.log ]; then + tail -40 flutter-analyze.log + elif [ -f flutter-pubget.log ]; then + echo "(analyze 未产生日志,pub get 输出如下)" + tail -20 flutter-pubget.log + else + echo "(日志缺失:Flutter 步骤可能未执行)" + fi echo '```' echo echo "" -- 2.54.0 From ab0cee8b40c56b4c5e60bb8411953593202f4362 Mon Sep 17 00:00:00 2001 From: chenmoyuan1214 Date: Sat, 21 Nov 2026 19:44:32 +0800 Subject: [PATCH 3/7] =?UTF-8?q?ci:=20build-bot=20=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E3=80=8C=E5=BC=80=E5=A7=8B=E7=BC=96=E8=AF=91=E3=80=8D=E5=9B=9E?= =?UTF-8?q?=E6=89=A7=EF=BC=9BmacOS=20runner=20=E6=94=B9=E7=94=A8=20macos-l?= =?UTF-8?q?atest?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 收到 @build-bot build <目标> 后立即回帖「开始编译」,附来源提交、目标、日志链接 - 编译完成仍走原来的结果回帖(成功给 release 链接,失败给日志链接) - runs-on: macos-14 → macos-latest: macos-14 在本仓库被判为 'macos-14-arm64-us-default' 不受支持,job 在启动前即被取消 --- .github/workflows/build-bot.yml | 31 +++++++++++++++++++++++- .github/workflows/nightly-prerelease.yml | 2 +- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build-bot.yml b/.github/workflows/build-bot.yml index 485f5a8..6283e5a 100644 --- a/.github/workflows/build-bot.yml +++ b/.github/workflows/build-bot.yml @@ -86,10 +86,39 @@ jobs: echo "ref=$REF" >> "$GITHUB_OUTPUT" echo "目标=$TARGET 提交=$REF 是否PR=$IS_PR" + - name: 回复「开始编译」 + if: steps.parse.outputs.ok == 'true' + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + ISSUE: ${{ github.event.issue.number }} + TARGET: ${{ steps.parse.outputs.target }} + REF: ${{ steps.parse.outputs.ref }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + set -e + case "$TARGET" in + mac) PLATFORMS="macOS" ;; + win-amd) PLATFORMS="Windows amd64" ;; + win-arm) PLATFORMS="Windows arm64" ;; + *) PLATFORMS="macOS + Windows amd64 + Windows arm64" ;; + esac + + cat > ack.md < Date: Sat, 21 Nov 2026 19:47:57 +0800 Subject: [PATCH 4/7] =?UTF-8?q?fix:=20macOS=20=E6=9E=84=E5=BB=BA=E5=8E=BB?= =?UTF-8?q?=E6=8E=89=20--no-codesign=EF=BC=9Bbuild-bot=20=E5=A4=B1?= =?UTF-8?q?=E8=B4=A5=E4=B9=9F=E5=9B=9E=E5=B8=96=E7=BB=93=E6=9E=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - flutter build macos 不支持 --no-codesign(那是 iOS 的选项), 传了会直接报 'Could not find an option named no-codesign' 导致编译失败。 macOS 模板本身用 ad-hoc 签名,CI 无证书也能构建。 - 删除 workflow 里的 GC_NO_CODESIGN 环境变量 - build-bot 新增独立 report job(always): 编译/发布任何一步失败都会回帖,列出各平台结果与日志链接, 不再因为 publish 被跳过而静默 --- .github/CI.md | 2 +- .github/workflows/build-bot.yml | 55 +++++++++++++++++++----- .github/workflows/nightly-prerelease.yml | 1 - buildsh/lib/flutter.sh | 13 +++--- 4 files changed, 50 insertions(+), 21 deletions(-) diff --git a/.github/CI.md b/.github/CI.md index 40e14cd..c714f9f 100644 --- a/.github/CI.md +++ b/.github/CI.md @@ -59,5 +59,5 @@ - `Settings → Actions → General → Workflow permissions` 给 **Read and write**, 否则 `gh release` / 评论接口会 403(工作流里已声明 `permissions:`,但组织策略可能覆盖)。 - Secrets 不需要额外配置,统一用内置的 `GITHUB_TOKEN`。 -- macOS 产物是 **未签名** 的(`GC_NO_CODESIGN=1`)。下载后首次打开需右键 →「打开」, +- macOS 产物是 **ad-hoc 签名**(无开发者证书)。下载后首次打开需右键 →「打开」, 或在「系统设置 → 隐私与安全性」里放行。 diff --git a/.github/workflows/build-bot.yml b/.github/workflows/build-bot.yml index 6283e5a..e35800c 100644 --- a/.github/workflows/build-bot.yml +++ b/.github/workflows/build-bot.yml @@ -136,7 +136,6 @@ jobs: - name: 编译 macOS env: - GC_NO_CODESIGN: '1' GC_NO_PROGRESS: '1' run: ./build.sh build --targets=mac @@ -252,18 +251,52 @@ jobs: echo "https://github.com/${{ github.repository }}/releases/tag/$TAG" >> "$GITHUB_STEP_SUMMARY" - - name: 回帖 - if: always() + # 结果回帖独立成一个 job:编译失败 / 发布失败也要有回音, + # 不能因为 publish 被跳过就静默。 + report: + needs: [prepare, build-mac, build-win, publish] + if: always() && needs.prepare.outputs.ok == 'true' + runs-on: ubuntu-latest + steps: + - name: 回帖结果 env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - TARGET: ${{ needs.prepare.outputs.target }} ISSUE: ${{ github.event.issue.number }} - STATE: ${{ steps.publish_step.outcome }} + TARGET: ${{ needs.prepare.outputs.target }} + REF: ${{ needs.prepare.outputs.ref }} + MAC: ${{ needs.build-mac.result }} + WIN: ${{ needs.build-win.result }} + PUB: ${{ needs.publish.result }} RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} run: | - if [ "$STATE" = "success" ]; then - MSG="已编译 **${TARGET}** 并发布到预发布:https://github.com/${{ github.repository }}/releases/tag/ip-prerelease" - else - MSG="编译 **${TARGET}** 失败,见日志:${RUN_URL}" - fi - gh issue comment "$ISSUE" --body "$MSG" + set -e + REPO="${{ github.repository }}" + + line() { + case "$2" in + success) echo "- $1:✅ 成功" ;; + skipped) echo "- $1:⏭ 未请求(跳过)" ;; + cancelled) echo "- $1:⛔ 已取消" ;; + *) echo "- $1:❌ 失败" ;; + esac + } + + { + if [ "$PUB" = "success" ]; then + echo "✅ **编译完成**:\`${TARGET}\`" + else + echo "❌ **编译未完成**:\`${TARGET}\`" + fi + echo + line "macOS" "$MAC" + line "Windows" "$WIN" + echo + echo "- 来源提交:\`${REF:0:7}\`" + if [ "$PUB" = "success" ]; then + echo "- 产物:https://github.com/${REPO}/releases/tag/ip-prerelease" + else + echo "- 日志:${RUN_URL}" + fi + } > result.md + + gh issue comment "$ISSUE" --body-file result.md diff --git a/.github/workflows/nightly-prerelease.yml b/.github/workflows/nightly-prerelease.yml index aed42d9..157ce3f 100644 --- a/.github/workflows/nightly-prerelease.yml +++ b/.github/workflows/nightly-prerelease.yml @@ -59,7 +59,6 @@ jobs: - name: 编译 macOS env: GC_TARGETS: mac - GC_NO_CODESIGN: '1' GC_NO_PROGRESS: '1' run: ./build.sh build --targets=mac diff --git a/buildsh/lib/flutter.sh b/buildsh/lib/flutter.sh index ce732f6..7c02347 100644 --- a/buildsh/lib/flutter.sh +++ b/buildsh/lib/flutter.sh @@ -37,15 +37,12 @@ flutter_build() { _flutter pub get || return 1 fi - # CI 上没有签名证书:GC_NO_CODESIGN=1 时给 macOS 加 --no-codesign, - # 直接产出未签名的 .app(用户首次打开需右键「打开」或在系统设置里放行)。 - _flags="--release" - if [ "${GC_NO_CODESIGN:-0}" = 1 ] && [ "$_plat" = macos ]; then - _flags="$_flags --no-codesign" - fi - + # 注意:macOS 的 `flutter build macos` 没有 --no-codesign 选项(那是 iOS 的), + # 传了会直接报 "Could not find an option named no-codesign"。 + # macOS 模板默认用 ad-hoc 签名(CODE_SIGN_IDENTITY = "-"),无证书的 CI 也能构建出 .app, + # 只是首次打开需要右键「打开」。 run_logged "$GC_ROOT/build/logs/flutter-$_plat.log" "Flutter $_plat 构建 " \ - _flutter build "$_plat" $_flags || return 1 + _flutter build "$_plat" --release || return 1 step_ok "Flutter ${_plat}" } -- 2.54.0 From 5b82a885f9b0c30b792af671ac1ad520b2307814 Mon Sep 17 00:00:00 2001 From: chenmoyuan1214 Date: Sat, 21 Nov 2026 19:56:13 +0800 Subject: [PATCH 5/7] =?UTF-8?q?fix(build-bot):=20report=20job=20=E5=8A=A0?= =?UTF-8?q?=20GH=5FREPO=EF=BC=9B=E5=B7=B2=E5=90=88=E5=B9=B6=20PR=20?= =?UTF-8?q?=E6=94=B9=E4=B8=BA=E7=BC=96=E9=BB=98=E8=AE=A4=E5=88=86=E6=94=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - report job 不 checkout,gh 没有 git 上下文会报 'fatal: not a git repository' → 补 GH_REPO 环境变量 - 只有 state=open 的 PR 才编它的 head.sha; 已合并/已关闭的 PR 编译默认分支,避免编到过期代码 - 回执里提示「PR 已 merged,改为编译默认分支」 --- .github/workflows/build-bot.yml | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build-bot.yml b/.github/workflows/build-bot.yml index e35800c..4699389 100644 --- a/.github/workflows/build-bot.yml +++ b/.github/workflows/build-bot.yml @@ -79,7 +79,15 @@ jobs: echo "is_pr=$IS_PR" >> "$GITHUB_OUTPUT" if [ "$IS_PR" = "true" ]; then - REF=$(gh api "repos/${{ github.repository }}/pulls/${ISSUE_NUMBER}" --jq '.head.sha') + # 只有「还开着」的 PR 才编它的 head;已合并/已关闭的 PR 编默认分支, + # 否则会编到一份过期的代码。 + PR_STATE=$(gh api "repos/${{ github.repository }}/pulls/${ISSUE_NUMBER}" --jq '.state') + if [ "$PR_STATE" = "open" ]; then + REF=$(gh api "repos/${{ github.repository }}/pulls/${ISSUE_NUMBER}" --jq '.head.sha') + else + REF="${{ github.event.repository.default_branch }}" + echo "PR 已 $PR_STATE,改为编译默认分支" + fi else REF="${{ github.event.repository.default_branch }}" fi @@ -261,6 +269,8 @@ jobs: - name: 回帖结果 env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # 本 job 不 checkout(省时间),gh 需要显式指定仓库 + GH_REPO: ${{ github.repository }} ISSUE: ${{ github.event.issue.number }} TARGET: ${{ needs.prepare.outputs.target }} REF: ${{ needs.prepare.outputs.ref }} -- 2.54.0 From e7c1429889ea21129da9c73405e68adcc97e5a6a Mon Sep 17 00:00:00 2001 From: chenmoyuan1214 Date: Sat, 21 Nov 2026 20:18:28 +0800 Subject: [PATCH 6/7] =?UTF-8?q?feat(ci):=20=E6=96=B0=E5=A2=9E=20@build-rel?= =?UTF-8?q?ease-bot=20build=20<=E7=89=88=E6=9C=AC=E5=8F=B7>?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 编译 macOS + Windows(amd64/arm64),发布 tag = 版本号的正式 Release(非预发布)。 - prepare 解析版本号(必须 主.次.修订),tag 已存在则拒绝并回帖说明 - 两个平台都成功才发 Release,附 SHA256SUMS.txt - 独立的 report job:任何一步失败都会回帖,列出各平台与发布状态 - 不动 version.json(需 SAVEDOG 签名,CI 无私钥),文档里注明走本地 ./build.sh stamp - mac job 增加环境自检(sw_vers / xcodebuild -version / flutter --version) --- .github/CI.md | 26 ++- .github/workflows/build-release.yml | 293 ++++++++++++++++++++++++++++ 2 files changed, 318 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/build-release.yml diff --git a/.github/CI.md b/.github/CI.md index c714f9f..a4da922 100644 --- a/.github/CI.md +++ b/.github/CI.md @@ -6,9 +6,11 @@ | --- | --- | --- | | `nightly-prerelease.yml` | 每天 21:00(Asia/Shanghai),或手动 | 编译 macOS + Windows(amd64/arm64),发布 **`nightly`** 预发布 | | `build-bot.yml` | Issue / PR 评论里 `@build-bot build <目标>` | 只编译指定平台,发布 **`ip-prerelease`** 预发布 | +| `build-release.yml` | Issue / PR 评论里 `@build-release-bot build <版本号>` | 编译三平台,发布 **tag = 版本号** 的正式 Release | | `pr-review.yml` | 向 main 提 PR(新建 / 有新提交 / 重新打开) | 检查能否编译、是否有错、是否冲突、是否落后 main | -两个预发布用**不同的 tag**,互不覆盖:夜间构建发 `nightly`,手动触发的发 `ip-prerelease`。 +预发布用**不同的 tag**,互不覆盖:夜间构建发 `nightly`,`@build-bot` 发 `ip-prerelease`; +`@build-release-bot` 发的是正式版本(tag 就是版本号,会更新 latest)。 ## 每夜构建 @@ -61,3 +63,25 @@ - Secrets 不需要额外配置,统一用内置的 `GITHUB_TOKEN`。 - macOS 产物是 **ad-hoc 签名**(无开发者证书)。下载后首次打开需右键 →「打开」, 或在「系统设置 → 隐私与安全性」里放行。 + +## build-release 用法 + +在 Issue 或 PR 里评论: + +``` +@build-release-bot build 1.1.3 +``` + +规则: + +- 版本号必须是 `主.次.修订`(如 `1.1.3`),其它写法会被忽略 +- tag 已存在时不会触发,会回帖说明「请换一个版本号」——同一个 tag 发两次会让客户端拿到两份不同内容 +- 只有 `OWNER` / `MEMBER` / `COLLABORATOR` 能触发 +- 编 macOS + Windows(amd64/arm64),**两个平台都成功**才发 Release,否则只回帖失败原因 +- Release 附带 `SHA256SUMS.txt` +- **不会**改动仓库里的 `version.json`:它由 GC-SAVEDOG 签名,CI 没有签名私钥。清单更新请在本地跑 `./build.sh stamp` + +## macOS runner + +统一用 `macos-latest`。`macos-14` 在本账号会被判为 `macos-14-arm64-us-default` 不受支持, +job 在启动前就变成 cancelled。runner 自带多个版本的 Xcode 和 CocoaPods,不需要额外安装。 diff --git a/.github/workflows/build-release.yml b/.github/workflows/build-release.yml new file mode 100644 index 0000000..43e4b72 --- /dev/null +++ b/.github/workflows/build-release.yml @@ -0,0 +1,293 @@ +name: build-release + +# 在 Issue / PR 里评论触发「编译 + 发布正式版本」: +# @build-release-bot build 1.1.3 +# +# 与 build-bot 的区别: +# build-bot 只编译,产物丢进 ip-prerelease(预发布,反复覆盖) +# build-release 编译三平台,发一个 tag = 版本号的正式 Release(会更新 latest) +# +# 不会改动仓库里的 version.json:它由 GC-SAVEDOG 签名,CI 里没有签名私钥, +# 重新 stamp 会产出一份客户端拒绝接受的清单。清单更新请走本地 ./build.sh stamp。 + +on: + issue_comment: + types: [created] + +concurrency: + group: release-manual + cancel-in-progress: false + +permissions: + contents: write + issues: write + pull-requests: write + +env: + TZ: Asia/Shanghai + DOTNET_VERSION: '8.0.x' + FLUTTER_VERSION: '3.24.5' + +jobs: + prepare: + if: | + contains(github.event.comment.body, '@build-release-bot') && + (github.event.comment.author_association == 'OWNER' || + github.event.comment.author_association == 'MEMBER' || + github.event.comment.author_association == 'COLLABORATOR') + runs-on: ubuntu-latest + outputs: + ok: ${{ steps.parse.outputs.ok }} + version: ${{ steps.parse.outputs.version }} + ref: ${{ steps.parse.outputs.ref }} + reason: ${{ steps.parse.outputs.reason }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - id: parse + name: 解析版本号并预检 + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + BODY: ${{ github.event.comment.body }} + run: | + set -e + # 只认 主.次.修订,其它写法直接忽略 + VER=$(printf '%s' "$BODY" \ + | grep -oiE '@build-release-bot[[:space:]]+build[[:space:]]+[0-9]+\.[0-9]+\.[0-9]+' \ + | head -1 \ + | awk '{print $NF}' || true) + + if [ -z "$VER" ]; then + echo "ok=false" >> "$GITHUB_OUTPUT" + echo "reason=没有匹配到合法版本号(格式:@build-release-bot build 1.2.3)" >> "$GITHUB_OUTPUT" + echo "未匹配到版本号,忽略" + exit 0 + fi + + echo "version=$VER" >> "$GITHUB_OUTPUT" + echo "ref=${{ github.event.repository.default_branch }}" >> "$GITHUB_OUTPUT" + echo "版本号=$VER" + + # tag 已存在就不能再发:重复 tag 会让客户端拿到两份不同内容 + if gh api "repos/${{ github.repository }}/git/ref/tags/${VER}" >/dev/null 2>&1; then + echo "ok=false" >> "$GITHUB_OUTPUT" + echo "reason=tag ${VER} 已存在,请换一个版本号" >> "$GITHUB_OUTPUT" + echo "tag ${VER} 已存在" + exit 0 + fi + + echo "ok=true" >> "$GITHUB_OUTPUT" + echo "reason=" >> "$GITHUB_OUTPUT" + + - name: 回复「开始编译并发布」 + if: steps.parse.outputs.ok == 'true' + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_REPO: ${{ github.repository }} + ISSUE: ${{ github.event.issue.number }} + VER: ${{ steps.parse.outputs.version }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + set -e + cat > ack.md < SHA256SUMS.txt 2>/dev/null || sha256sum *.zip > SHA256SUMS.txt + cat SHA256SUMS.txt + + - name: 发布 Release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_REPO: ${{ github.repository }} + VER: ${{ needs.prepare.outputs.version }} + REF: ${{ needs.prepare.outputs.ref }} + ACTOR: ${{ github.event.comment.user.login }} + ISSUE: ${{ github.event.issue.number }} + run: | + set -e + cat > notes.md < macOS 包为 ad-hoc 签名,首次打开需右键 →「打开」,或在「系统设置 → 隐私与安全性」里放行。 + EOF + + gh release create "$VER" out/* \ + --target "$REF" \ + --title "GC ${VER}" \ + --notes-file notes.md + + echo "https://github.com/${{ github.repository }}/releases/tag/$VER" >> "$GITHUB_STEP_SUMMARY" + + report: + needs: [prepare, build-mac, build-win, publish] + if: always() && needs.prepare.outputs.ok == 'true' + runs-on: ubuntu-latest + steps: + - name: 回帖结果 + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_REPO: ${{ github.repository }} + ISSUE: ${{ github.event.issue.number }} + VER: ${{ needs.prepare.outputs.version }} + MAC: ${{ needs.build-mac.result }} + WIN: ${{ needs.build-win.result }} + PUB: ${{ needs.publish.result }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + set -e + REPO="${{ github.repository }}" + + line() { + case "$2" in + success) echo "- $1:✅ 成功" ;; + skipped) echo "- $1:⏭ 跳过" ;; + cancelled) echo "- $1:⛔ 已取消" ;; + *) echo "- $1:❌ 失败" ;; + esac + } + + if [ "$PUB" = "success" ]; then + HEADLINE="✅ **已发布 \`${VER}\`**" + elif [ "$MAC" = "success" ] || [ "$WIN" = "success" ]; then + HEADLINE="⚠️ **编译完成但未发布 \`${VER}\`**(需要两个平台都成功才会发 Release)" + else + HEADLINE="❌ **\`${VER}\` 编译失败**" + fi + + { + echo "$HEADLINE" + echo + line "macOS" "$MAC" + line "Windows" "$WIN" + line "发布" "$PUB" + echo + if [ "$PUB" = "success" ]; then + echo "- Release:https://github.com/${REPO}/releases/tag/${VER}" + else + echo "- 日志:${RUN_URL}" + fi + } > result.md + + gh issue comment "$ISSUE" --body-file result.md -- 2.54.0 From ecb71ad347f742b60accd6ea99963ce3bd89f810 Mon Sep 17 00:00:00 2001 From: chenmoyuan1214 Date: Sat, 21 Nov 2026 20:26:02 +0800 Subject: [PATCH 7/7] =?UTF-8?q?feat(user):=20=E7=94=A8=E6=88=B7=E7=B3=BB?= =?UTF-8?q?=E7=BB=9F=E9=87=8D=E5=81=9A=E2=80=94=E2=80=94=E4=BA=BA=E6=9C=BA?= =?UTF-8?q?=E9=AA=8C=E8=AF=81=E3=80=8130=20=E5=A4=A9=E7=AD=BE=E5=88=B0?= =?UTF-8?q?=E3=80=81=E4=B8=BB=E9=A2=98=E8=89=B2=E8=B4=AD=E4=B9=B0=E4=B8=8E?= =?UTF-8?q?=E9=80=80=E6=AC=BE=E3=80=81=E4=BA=BA=E5=93=81=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 存储 - 目录改为 .GC/user/<用户名>/pw.yaml(用户名、积分、sha512 口令 + 盐) - .GC/user/user.yaml 记住当前登录(用户名 + session token),启动自动登录 - 自动迁移旧的 .GC/user/<用户名>.yaml 注册 / 登录 - 新增算术人机验证:GET /api/user/captcha(5 分钟有效、一次性、用后即焚) - 用户名不可重复、不能含空格、1–20 字符 - 口令只存 sha512(密码 + ":" + 随机盐),不存明文 - 新增 /api/user/logout 签到 - 30 天一循环:1–6 天 +10,第 7 天 +30,8–13 +15,第 14 天 +40, 15–20 +20,第 21 天 +50,22–27 +25,第 28 天 +60,29 天 +40,第 30 天 +100 - 断签重置连续天数;接口返回 cycle_day / next_reward / today_signed 主题色 - 默认蓝免费,预置色 50,自定义色 150(服务端算价,不信客户端) - 购买后 1 小时内换色退 80%,record 里存 theme_paid / theme_paid_at - 禁止充值:积分只能签到获得 前端用户页 - 账号卡片:积分、连续天数、周期进度条、一键签到、退出登录 - 注册表单内嵌验证码(换一题、失败自动刷新) - 人品值:0–100 随机 + 评语,每天不限次数 - 二选一:两个输入框随机选一个 - 主题色:8 个预置色 + 自定义色取色(十六进制 + 预览),积分不足上锁 - 应用主题色时同步覆盖全局强调色 --- GC-UI/backend/GC.UI.Server/ApiModels.cs | 13 +- GC-UI/backend/GC.UI.Server/BackendServer.cs | 82 +- GC-UI/backend/GC.UI.Server/UserService.cs | 436 ++++++-- GC-UI/frontend/lib/api_client.dart | 94 +- GC-UI/frontend/lib/i18n.dart | 72 +- GC-UI/frontend/lib/models/user.dart | 138 ++- GC-UI/frontend/lib/pages/user_page.dart | 1047 ++++++++++++++----- 7 files changed, 1419 insertions(+), 463 deletions(-) diff --git a/GC-UI/backend/GC.UI.Server/ApiModels.cs b/GC-UI/backend/GC.UI.Server/ApiModels.cs index 0dc70d1..4b11edb 100644 --- a/GC-UI/backend/GC.UI.Server/ApiModels.cs +++ b/GC-UI/backend/GC.UI.Server/ApiModels.cs @@ -124,9 +124,18 @@ public sealed record UpdateCheckDto( public sealed record ContributorDto(string Name, int Contributions, string? AvatarUrl); // ---- 用户 API DTO ---- -public sealed record RegisterRequest(string Username, string Password); +public sealed record RegisterRequest( + string Username, + string Password, + string? CaptchaId = null, + string? Captcha = null); + public sealed record LoginRequest(string Username, string Password); -public sealed record ThemeRequest(string Color, int Cost); + +/// 换主题色:只传颜色,价格由服务端按预置/自定义判定。 +public sealed record ThemeRequest(string Color, int? Cost = null); + +public sealed record CaptchaDto(string Id, string Question); /// 「重新下载启动器」结果:State = Ready / UpToDate / Failed。 diff --git a/GC-UI/backend/GC.UI.Server/BackendServer.cs b/GC-UI/backend/GC.UI.Server/BackendServer.cs index c62c0b2..89f8e47 100644 --- a/GC-UI/backend/GC.UI.Server/BackendServer.cs +++ b/GC-UI/backend/GC.UI.Server/BackendServer.cs @@ -193,7 +193,7 @@ public static class BackendServer // 简单 session 存储:key = username(lower), value = session token var userSessions = new System.Collections.Concurrent.ConcurrentDictionary(); - // 中间件:从 header 提取当前用户 + // 中间件:从 header 提取当前用户;没有 token 时回退到 user.yaml 记住的用户(自动登录) app.Use(async (context, next) => { context.Items["user"] = null as string; @@ -209,14 +209,52 @@ public static class BackendServer } } } + if (context.Items["user"] is not string u || string.IsNullOrEmpty(u)) + context.Items["user"] = userService.RestoredUser; await next(); }); + // 统一的用户响应体:前端一次拿齐签到 / 主题色需要的所有字段 + object UserPayload(UserRecord r) + { + var today = DateTime.UtcNow.Date; + int nextConsecutive; + if (!r.LastSignIn.HasValue) nextConsecutive = 1; + else + { + var diff = (today - r.LastSignIn.Value.Date).Days; + nextConsecutive = diff <= 1 ? r.ConsecutiveDays + 1 : 1; + } + var refund = UserService.RefundRemaining(r); + + return new + { + username = r.Username, + points = r.Points, + consecutive_days = r.ConsecutiveDays, + cycle_day = UserService.CycleDay(r.ConsecutiveDays), + cycle_days = UserService.SignInCycleDays, + today_signed = r.LastSignIn.HasValue && r.LastSignIn.Value.Date == today, + next_reward = UserService.GetSignInReward(UserService.CycleDay(nextConsecutive)), + last_sign_in = r.LastSignIn?.ToString("yyyy-MM-dd") ?? "", + theme_color = r.ThemeColor ?? UserService.DefaultThemeColor, + theme_paid = r.ThemePaid, + refund_seconds = refund.HasValue ? (int)refund.Value.TotalSeconds : 0 + }; + } + + // 人机验证:算术题,5 分钟有效、一次性 + app.MapGet("/api/user/captcha", () => + { + var (id, question) = userService.IssueCaptcha(); + return Results.Ok(new CaptchaDto(id, question)); + }); + app.MapPost("/api/user/register", (RegisterRequest? req) => { if (req == null) return Results.BadRequest(new { error = "请求体为空" }); if (string.IsNullOrWhiteSpace(req.Username)) return Results.BadRequest(new { error = "用户名不能为空" }); if (string.IsNullOrWhiteSpace(req.Password)) return Results.BadRequest(new { error = "密码不能为空" }); - var ok = userService.Register(req.Username, req.Password, out var err); + var ok = userService.Register(req.Username, req.Password, req.CaptchaId, req.Captcha, out var err); return ok ? Results.Ok(new { message = "注册成功" }) : Results.BadRequest(new { error = err }); }); @@ -226,7 +264,9 @@ public static class BackendServer if (!ok) return Results.BadRequest(new { error = err }); // 生成 session token var sessionToken = Convert.ToBase64String(System.Security.Cryptography.RandomNumberGenerator.GetBytes(32)).Replace("/", "_").Replace("+", "-").Substring(0, 32); - userSessions[rec!.Username.ToLower()] = sessionToken; + userSessions[rec!.Username.ToLowerInvariant()] = sessionToken; + // 记住登录:写 .GC/user/user.yaml,下次启动自动登录 + userService.SaveSession(rec.Username, sessionToken); return Results.Ok(new { username = rec.Username, points = rec.Points, @@ -237,18 +277,19 @@ public static class BackendServer }); }); + app.MapPost("/api/user/logout", (HttpContext ctx) => { + var username = ctx.Items["user"] as string; + if (!string.IsNullOrEmpty(username)) userSessions.TryRemove(username, out _); + userService.ClearSession(); + return Results.Ok(new { message = "已退出登录" }); + }); + app.MapGet("/api/user/me", (HttpContext ctx) => { var username = ctx.Items["user"] as string; if (string.IsNullOrEmpty(username) || !userService.TryGetUser(username, out var rec)) return Results.Json(new { error = "未登录" }, statusCode: 401); - return Results.Ok(new { - username = rec.Username, - points = rec.Points, - consecutive_days = rec.ConsecutiveDays, - last_sign_in = rec.LastSignIn?.ToString("yyyy-MM-dd") ?? "", - theme_color = rec.ThemeColor ?? "" - }); + return Results.Ok(UserPayload(rec)); }); app.MapPost("/api/user/signin", (HttpContext ctx) => @@ -256,18 +297,16 @@ public static class BackendServer var username = ctx.Items["user"] as string; if (string.IsNullOrEmpty(username) || !userService.TryGetUser(username, out var rec)) return Results.Json(new { error = "未登录" }, statusCode: 401); - var ok = userService.UpdateSignIn(username, out var err); + var ok = userService.UpdateSignIn(username, out var err, out var reward); if (!ok) { if (err == "今日已签到") - return Results.Ok(new { message = err, points = rec.Points, consecutive_days = rec.ConsecutiveDays }); + return Results.Ok(new { message = err, user = UserPayload(rec) }); return Results.BadRequest(new { error = err }); } return Results.Ok(new { - points = rec.Points, - consecutive_days = rec.ConsecutiveDays, - reward = userService.GetSignInReward(rec.ConsecutiveDays), - last_sign_in = rec.LastSignIn?.ToString("yyyy-MM-dd") ?? "" + reward, + user = UserPayload(rec) }); }); @@ -277,8 +316,15 @@ public static class BackendServer if (string.IsNullOrEmpty(username) || !userService.TryGetUser(username, out var rec)) return Results.Json(new { error = "未登录" }, statusCode: 401); if (req == null) return Results.BadRequest(new { error = "请求体为空" }); - var ok = userService.ChangeThemeColor(username, req.Color, req.Cost, out var err); - return ok ? Results.Ok(new { message = "主题已更新", points = rec.Points, theme_color = rec.ThemeColor }) : Results.BadRequest(new { error = err }); + + var ok = userService.ChangeThemeColor(username, req.Color, out var err, out var refunded); + if (!ok) return Results.BadRequest(new { error = err }); + + return Results.Ok(new { + message = "主题已更新", + refunded, + user = UserPayload(rec) + }); }); app.MapGet("/api/health", () => Results.Ok(new HealthDto( diff --git a/GC-UI/backend/GC.UI.Server/UserService.cs b/GC-UI/backend/GC.UI.Server/UserService.cs index 63c0989..fc225a7 100644 --- a/GC-UI/backend/GC.UI.Server/UserService.cs +++ b/GC-UI/backend/GC.UI.Server/UserService.cs @@ -9,43 +9,99 @@ using System.Text; namespace GC.UI.Server; /// -/// 本地用户系统:用户名/密码/积分,数据存在 .GC/user/ 目录。 +/// 本地用户系统:注册 / 登录 / 签到 / 积分 / 主题色。 +/// +/// 目录结构(都在 .GC/user 下): +/// .GC/user/user.yaml 本地登录信息(当前用户 + session token) +/// .GC/user/<用户名>/pw.yaml 该用户的账号数据(用户名、积分、密码 sha512) +/// +/// 密码只存 sha512(密码 + ":" + 随机盐),不存明文;盐单独一行保存。 /// public sealed class UserService { + /// 默认主题色(蓝色):免费。 + public const string DefaultThemeColor = "4A90D9"; + + /// 预置颜色单价。 + public const int PresetColorCost = 50; + + /// 自定义颜色单价。 + public const int CustomColorCost = 150; + + /// 退款窗口:购买后 1 小时内换色可退 80%。 + public static readonly TimeSpan RefundWindow = TimeSpan.FromHours(1); + + /// 退款比例。 + public const double RefundRate = 0.8; + + /// 签到周期长度(天)。 + public const int SignInCycleDays = 30; + + private static readonly string[] PresetColors = + { + "4A90D9", "E74C3C", "27AE60", "9B59B6", + "F39C12", "1ABC9C", "E91E63", "2C3E50" + }; + private readonly string _userDir; + private readonly string _sessionFile; + public readonly ConcurrentDictionary _users = new(); + /// 验证码:id → (答案, 过期时间)。一次性,用后即删。 + private readonly ConcurrentDictionary _captchas = new(); + + /// 记住的登录用户(来自 user.yaml),没有显式 token 时用它。 + private string? _restoredUser; + public UserService(string homeRoot) { _userDir = Path.Combine(homeRoot, "user"); + _sessionFile = Path.Combine(_userDir, "user.yaml"); Directory.CreateDirectory(_userDir); LoadAll(); + LoadSession(); } + // ---------------------------------------------------------------- 读写磁盘 + private void LoadAll() { - foreach (var file in Directory.GetFiles(_userDir, "*.yaml")) + foreach (var dir in Directory.GetDirectories(_userDir)) { try { - var username = Path.GetFileNameWithoutExtension(file); - var content = File.ReadAllText(file); - var rec = DeserializeUser(username, content); - if (rec != null) _users[username] = rec; + var file = Path.Combine(dir, "pw.yaml"); + if (!File.Exists(file)) continue; + var rec = DeserializeUser(Path.GetFileName(dir), File.ReadAllText(file)); + if (rec != null) _users[rec.Username.ToLowerInvariant()] = rec; } - catch { /* 忽略损坏文件 */ } + catch { /* 单个用户文件损坏不影响其他用户 */ } + } + + // 兼容旧布局:.GC/user/<用户名>.yaml 直接放在根下(迁移到 <用户名>/pw.yaml) + foreach (var legacy in Directory.GetFiles(_userDir, "*.yaml")) + { + if (string.Equals(legacy, _sessionFile, StringComparison.OrdinalIgnoreCase)) continue; + try + { + var name = Path.GetFileNameWithoutExtension(legacy); + var rec = DeserializeUser(name, File.ReadAllText(legacy)); + if (rec == null) continue; + _users[rec.Username.ToLowerInvariant()] = rec; + SaveUser(rec); + File.Delete(legacy); + } + catch { /* 忽略 */ } } } - private UserRecord? DeserializeUser(string username, string yaml) + private static UserRecord? DeserializeUser(string fallbackName, string yaml) { var lines = yaml.Split('\n', StringSplitOptions.RemoveEmptyEntries); - string? pwHash = null, pwSalt = null; - int points = 0; - DateTime? lastSignIn = null; - int consecutiveDays = 0; - string? themeColor = null; + string? username = null, pwHash = null, pwSalt = null, themeColor = null; + int points = 0, consecutiveDays = 0, themePaid = 0; + DateTime? lastSignIn = null, themePaidAt = null; foreach (var line in lines) { @@ -55,44 +111,190 @@ public sealed class UserService var val = parts[1].Trim(); switch (key) { + case "username": username = val; break; case "pw_hash": pwHash = val; break; case "pw_salt": pwSalt = val; break; - case "points": points = int.TryParse(val, out var p) ? p : 0; break; + case "points": int.TryParse(val, out var p); points = p; break; case "last_sign_in": if (DateTime.TryParse(val, out var ls)) lastSignIn = ls; break; - case "consecutive_days": consecutiveDays = int.TryParse(val, out var d) ? d : 0; break; + case "consecutive_days": int.TryParse(val, out var d); consecutiveDays = d; break; case "theme_color": themeColor = val; break; + case "theme_paid": int.TryParse(val, out var tp); themePaid = tp; break; + case "theme_paid_at": + if (DateTime.TryParse(val, out var ta)) themePaidAt = ta; + break; } } + if (string.IsNullOrWhiteSpace(username)) username = fallbackName; if (pwHash == null || pwSalt == null) return null; - return new UserRecord(username, pwHash, pwSalt, points, lastSignIn, consecutiveDays, themeColor); + + return new UserRecord(username!, pwHash, pwSalt, points, lastSignIn, consecutiveDays, + string.IsNullOrWhiteSpace(themeColor) ? DefaultThemeColor : themeColor, + themePaid, themePaidAt); } - public bool Register(string username, string password, out string error) + private void SaveUser(UserRecord rec) + { + try + { + var dir = Path.Combine(_userDir, SafeDirName(rec.Username)); + Directory.CreateDirectory(dir); + + var yaml = new StringBuilder() + .AppendLine($"username: {rec.Username}") + .AppendLine($"pw_hash: {rec.PwHash}") + .AppendLine($"pw_salt: {rec.PwSalt}") + .AppendLine($"points: {rec.Points}") + .AppendLine($"last_sign_in: {rec.LastSignIn?.ToString("yyyy-MM-dd") ?? ""}") + .AppendLine($"consecutive_days: {rec.ConsecutiveDays}") + .AppendLine($"theme_color: {rec.ThemeColor ?? DefaultThemeColor}") + .AppendLine($"theme_paid: {rec.ThemePaid}") + .AppendLine($"theme_paid_at: {rec.ThemePaidAt?.ToString("o") ?? ""}") + .ToString(); + + File.WriteAllText(Path.Combine(dir, "pw.yaml"), yaml); + } + catch { /* 写盘失败不影响内存状态 */ } + } + + /// 用户名做目录名时过滤掉路径分隔符与 Windows 保留字符。 + private static string SafeDirName(string username) + { + var invalid = Path.GetInvalidFileNameChars(); + var chars = username.Select(c => invalid.Contains(c) || c == '.' ? '_' : c).ToArray(); + var name = new string(chars).Trim(); + return string.IsNullOrEmpty(name) ? "_" : name; + } + + // ---------------------------------------------------------------- 登录态 + + private void LoadSession() + { + try + { + if (!File.Exists(_sessionFile)) return; + foreach (var line in File.ReadAllLines(_sessionFile)) + { + var parts = line.Split(':', 2); + if (parts.Length == 2 && parts[0].Trim() == "username") + { + var name = parts[1].Trim(); + if (!string.IsNullOrEmpty(name) && _users.ContainsKey(name.ToLowerInvariant())) + _restoredUser = name.ToLowerInvariant(); + } + } + } + catch { /* 忽略 */ } + } + + public void SaveSession(string username, string token) + { + try + { + var lower = username.ToLowerInvariant(); + _restoredUser = lower; + Directory.CreateDirectory(_userDir); + File.WriteAllText(_sessionFile, + $"username: {username}\nsession_token: {token}\n"); + } + catch { /* 忽略 */ } + } + + public void ClearSession() + { + _restoredUser = null; + try { if (File.Exists(_sessionFile)) File.Delete(_sessionFile); } catch { /* 忽略 */ } + } + + /// 没有携带 token 时,回退到 user.yaml 里记住的用户(自动登录)。 + public string? RestoredUser => _restoredUser; + + // ---------------------------------------------------------------- 验证码 + + /// 签发一个算术验证码,5 分钟内有效,用后即焚。 + public (string Id, string Question) IssueCaptcha() + { + var now = DateTime.UtcNow; + + // 顺手清理过期项,避免长时间运行后字典无限增长 + if (_captchas.Count > 128) + { + foreach (var kv in _captchas) + if (kv.Value.Expires < now) _captchas.TryRemove(kv.Key, out _); + } + + var a = RandomNumberGenerator.GetInt32(2, 10); + var b = RandomNumberGenerator.GetInt32(2, 10); + var plus = RandomNumberGenerator.GetInt32(0, 2) == 0; + var answer = plus ? a + b : Math.Max(a, b) - Math.Min(a, b); + var id = Convert.ToHexString(RandomNumberGenerator.GetBytes(12)).ToLowerInvariant(); + + _captchas[id] = (answer, now.AddMinutes(5)); + var question = plus ? $"{a} + {b} = ?" : $"{Math.Max(a, b)} - {Math.Min(a, b)} = ?"; + return (id, question); + } + + public bool VerifyCaptcha(string? id, string? answer, out string error) { error = ""; + if (string.IsNullOrWhiteSpace(id) || string.IsNullOrWhiteSpace(answer)) + { + error = "请先完成人机验证"; + return false; + } + if (!_captchas.TryRemove(id, out var entry)) + { + error = "验证码已失效,请重新获取"; + return false; + } + if (entry.Expires < DateTime.UtcNow) + { + error = "验证码已过期,请重新获取"; + return false; + } + if (!int.TryParse(answer.Trim(), out var value) || value != entry.Answer) + { + error = "验证码答案错误"; + return false; + } + return true; + } + + // ---------------------------------------------------------------- 账号 + + public bool Register(string username, string password, string? captchaId, string? captcha, + out string error) + { + if (!VerifyCaptcha(captchaId, captcha, out error)) return false; + if (string.IsNullOrWhiteSpace(username) || username.Length > 20) { - error = "用户名无效"; + error = "用户名需为 1–20 个字符"; + return false; + } + if (username.Any(char.IsWhiteSpace)) + { + error = "用户名不能包含空格"; + return false; + } + if (_users.ContainsKey(username.Trim().ToLowerInvariant())) + { + error = "用户名已存在,请换一个"; return false; } if (string.IsNullOrWhiteSpace(password) || password.Length < 6) { - error = "密码至少6位"; - return false; - } - if (_users.ContainsKey(username.ToLower())) - { - error = "用户名已存在"; + error = "密码至少 6 位"; return false; } + var name = username.Trim(); var salt = GenerateSalt(); - var hash = HashPassword(password, salt); - var rec = new UserRecord(username, hash, salt, 0, null, 0, null); - _users[username.ToLower()] = rec; + var rec = new UserRecord(name, HashPassword(password, salt), salt, + 0, null, 0, DefaultThemeColor, 0, null); + _users[name.ToLowerInvariant()] = rec; SaveUser(rec); return true; } @@ -101,13 +303,12 @@ public sealed class UserService { error = ""; record = null; - if (!_users.TryGetValue(username.ToLower(), out var rec)) + if (!_users.TryGetValue(username.Trim().ToLowerInvariant(), out var rec)) { error = "用户名或密码错误"; return false; } - var hash = HashPassword(password, rec.PwSalt); - if (hash != rec.PwHash) + if (HashPassword(password, rec.PwSalt) != rec.PwHash) { error = "用户名或密码错误"; return false; @@ -116,24 +317,60 @@ public sealed class UserService return true; } + public bool TryGetUser(string username, out UserRecord? record) + => _users.TryGetValue(username.Trim().ToLowerInvariant(), out record); + + public UserRecord? GetFirstUser() => _users.Values.FirstOrDefault(); + public bool UpdatePoints(string username, int deltaPoints, out string error) { error = ""; - if (!_users.TryGetValue(username, out var rec)) + if (!_users.TryGetValue(username.Trim().ToLowerInvariant(), out var rec)) { error = "用户不存在"; return false; } rec.Points = Math.Max(0, rec.Points + deltaPoints); - _users[username] = rec; SaveUser(rec); return true; } - public bool UpdateSignIn(string username, out string error) + // ---------------------------------------------------------------- 签到 + + /// + /// 30 天一循环的签到奖励。第 7/14/21/28 天给「周奖励」,第 30 天给满月奖励。 + /// + public static int GetSignInReward(int cycleDay) + { + if (cycleDay < 1) cycleDay = 1; + if (cycleDay > SignInCycleDays) cycleDay = ((cycleDay - 1) % SignInCycleDays) + 1; + + return cycleDay switch + { + 7 => 30, + 14 => 40, + 21 => 50, + 28 => 60, + 30 => 100, + <= 6 => 10, + <= 13 => 15, + <= 20 => 20, + <= 27 => 25, + _ => 40 + }; + } + + public static int CycleDay(int consecutiveDays) + { + if (consecutiveDays < 1) return 1; + return ((consecutiveDays - 1) % SignInCycleDays) + 1; + } + + public bool UpdateSignIn(string username, out string error, out int reward) { error = ""; - if (!_users.TryGetValue(username, out var rec)) + reward = 0; + if (!_users.TryGetValue(username.Trim().ToLowerInvariant(), out var rec)) { error = "用户不存在"; return false; @@ -142,85 +379,119 @@ public sealed class UserService var today = DateTime.UtcNow.Date; if (rec.LastSignIn.HasValue) { - var last = rec.LastSignIn.Value.Date; - var diff = (today - last).Days; + var diff = (today - rec.LastSignIn.Value.Date).Days; if (diff == 0) { error = "今日已签到"; return false; } - if (diff == 1) - { - rec.ConsecutiveDays++; - } - else - { - rec.ConsecutiveDays = 1; - } + // 断签超过一天:连续天数重置(但 30 天周期按新的连续天数重新算) + rec.ConsecutiveDays = diff == 1 ? rec.ConsecutiveDays + 1 : 1; } else { rec.ConsecutiveDays = 1; } + rec.LastSignIn = today; - - var cycleDay = (rec.ConsecutiveDays - 1) % 30 + 1; - int reward = GetSignInReward(cycleDay); + reward = GetSignInReward(CycleDay(rec.ConsecutiveDays)); rec.Points += reward; - - _users[username] = rec; SaveUser(rec); return true; } - public int GetSignInReward(int day) + // ---------------------------------------------------------------- 主题色 + + /// 某个颜色的价格:默认蓝免费,预置色 50,其它(自定义)150。 + public static int ThemeCost(string hex) { - if (day <= 7) return 10; - if (day <= 15) return 20; - return 30; + var h = NormalizeHex(hex); + if (string.IsNullOrEmpty(h)) return -1; + if (string.Equals(h, DefaultThemeColor, StringComparison.OrdinalIgnoreCase)) return 0; + return PresetColors.Contains(h, StringComparer.OrdinalIgnoreCase) + ? PresetColorCost + : CustomColorCost; } - public UserRecord? GetFirstUser() + public static string NormalizeHex(string? hex) { - return _users.Values.FirstOrDefault(); + if (string.IsNullOrWhiteSpace(hex)) return ""; + var h = hex.Trim().TrimStart('#'); + if (h.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) h = h[2..]; + if (h.Length != 6) return ""; + return h.All(Uri.IsHexDigit) ? h.ToUpperInvariant() : ""; } - public bool TryGetUser(string username, out UserRecord? record) - { - return _users.TryGetValue(username.ToLower(), out record); - } - - public bool ChangeThemeColor(string username, string colorHex, int cost, out string error) + /// + /// 换主题色。服务端自己算价,不信客户端传的 cost。 + /// 上次购买在 1 小时内,先按 80% 退还上次花费。 + /// + public bool ChangeThemeColor(string username, string colorHex, out string error, out int refunded) { error = ""; - if (!_users.TryGetValue(username, out var rec)) + refunded = 0; + + if (!_users.TryGetValue(username.Trim().ToLowerInvariant(), out var rec)) { error = "用户不存在"; return false; } - if (rec.Points < cost) + + var hex = NormalizeHex(colorHex); + if (string.IsNullOrEmpty(hex)) { - error = "积分不足"; + error = "颜色格式应为 #RRGGBB"; return false; } - rec.Points -= cost; - rec.ThemeColor = colorHex; - _users[username] = rec; + + var cost = ThemeCost(hex); + if (cost < 0) + { + error = "颜色格式应为 #RRGGBB"; + return false; + } + + if (string.Equals(NormalizeHex(rec.ThemeColor), hex, StringComparison.OrdinalIgnoreCase)) + { + error = "当前已经是这个颜色"; + return false; + } + + // 1 小时内换色:退回上次花费的 80% + var available = rec.Points; + if (rec.ThemePaid > 0 && rec.ThemePaidAt.HasValue && + DateTime.UtcNow - rec.ThemePaidAt.Value <= RefundWindow) + { + refunded = (int)Math.Floor(rec.ThemePaid * RefundRate); + available += refunded; + } + + if (available < cost) + { + error = refunded > 0 + ? $"积分不足(含可退 {refunded},需 {cost})" + : $"积分不足,需要 {cost} 积分"; + return false; + } + + rec.Points = available - cost; + rec.ThemeColor = hex; + rec.ThemePaid = cost; + rec.ThemePaidAt = cost > 0 ? DateTime.UtcNow : null; SaveUser(rec); return true; } - private void SaveUser(UserRecord rec) + /// 距离退款窗口关闭还剩多久;没有可退的就返回 null。 + public static TimeSpan? RefundRemaining(UserRecord rec) { - try - { - var file = Path.Combine(_userDir, $"{rec.Username.ToLower()}.yaml"); - var yaml = $"username: {rec.Username}\npw_hash: {rec.PwHash}\npw_salt: {rec.PwSalt}\npoints: {rec.Points}\nlast_sign_in: {rec.LastSignIn?.ToString("yyyy-MM-dd") ?? ""}\nconsecutive_days: {rec.ConsecutiveDays}\ntheme_color: {rec.ThemeColor ?? ""}\n"; - File.WriteAllText(file, yaml); - } - catch { /* 忽略写入失败 */ } + if (rec.ThemePaid <= 0 || !rec.ThemePaidAt.HasValue) return null; + var left = RefundWindow - (DateTime.UtcNow - rec.ThemePaidAt.Value); + return left > TimeSpan.Zero ? left : null; } + // ---------------------------------------------------------------- 散列 + private static string GenerateSalt() { var bytes = new byte[16]; @@ -232,8 +503,7 @@ public sealed class UserService private static string HashPassword(string password, string salt) { using var sha512 = SHA512.Create(); - var combined = Encoding.UTF8.GetBytes(password + ":" + salt); - var hash = sha512.ComputeHash(combined); + var hash = sha512.ComputeHash(Encoding.UTF8.GetBytes(password + ":" + salt)); return Convert.ToBase64String(hash); } } @@ -248,7 +518,15 @@ public class UserRecord public int ConsecutiveDays { get; set; } public string? ThemeColor { get; set; } - public UserRecord(string username, string pwHash, string pwSalt, int points, DateTime? lastSignIn, int consecutiveDays, string? themeColor = null) + /// 当前这个颜色实际花了多少分(用于 1 小时内退款)。 + public int ThemePaid { get; set; } + + /// 购买该颜色的时间(UTC)。 + public DateTime? ThemePaidAt { get; set; } + + public UserRecord(string username, string pwHash, string pwSalt, int points, + DateTime? lastSignIn, int consecutiveDays, string? themeColor = null, + int themePaid = 0, DateTime? themePaidAt = null) { Username = username; PwHash = pwHash; @@ -257,5 +535,7 @@ public class UserRecord LastSignIn = lastSignIn; ConsecutiveDays = consecutiveDays; ThemeColor = themeColor; + ThemePaid = themePaid; + ThemePaidAt = themePaidAt; } } diff --git a/GC-UI/frontend/lib/api_client.dart b/GC-UI/frontend/lib/api_client.dart index 6c20b1c..fdbbb1d 100644 --- a/GC-UI/frontend/lib/api_client.dart +++ b/GC-UI/frontend/lib/api_client.dart @@ -514,46 +514,11 @@ class GcApi { /// 是否拿到了会话令牌(诊断用)。 bool get hasSessionToken => _sessionToken != null; - /// 用户 session token(登录时后端返回,持久化到 ~/.GC/user/user.yaml) + /// 用户 session token:登录时后端返回,只放内存。 + /// 持久化由后端负责(写 .GC/user/user.yaml),下次启动后端会用它自动登录, + /// 前端不需要自己去猜 .GC 在哪。 static String? _userToken; - static String? _username; - static String? get userToken => _userToken; - static String? get username => _username; - - static Future _loadUserToken() async { - try { - final dir = Directory('${Platform.environment['HOME'] ?? '.'}/.GC/user'); - if (!dir.existsSync()) return; - final file = File('${dir.path}/user.yaml'); - if (!file.existsSync()) return; - final lines = file.readAsLinesSync(); - for (var line in lines) { - if (line.startsWith('username:')) _username = line.split(':').skip(1).join(':').trim(); - if (line.startsWith('session_token:')) _userToken = line.split(':').skip(1).join(':').trim(); - } - } catch (_) {} - } - - static Future _saveUserToken(String username, String token) async { - try { - final dir = Directory('${Platform.environment['HOME'] ?? '.'}/.GC/user'); - dir.createSync(recursive: true); - final file = File('${dir.path}/user.yaml'); - file.writeAsStringSync('username: $username\nsession_token: $token\n'); - _username = username; - _userToken = token; - } catch (_) {} - } - - static Future clearUserToken() async { - _username = null; - _userToken = null; - try { - final file = File('${Platform.environment['HOME'] ?? '.'}/.GC/user/user.yaml'); - if (file.existsSync()) file.deleteSync(); - } catch (_) {} - } /// 带会话令牌的请求头;没有令牌时返回 const 空 map(调试/独立后端模式)。 Map get _authHeaders => { @@ -705,27 +670,34 @@ class GcApi { // ==================== 用户系统 ==================== - /// 初始化:加载本地保存的用户token - Future initUserSession() async { - await _loadUserToken(); + /// 取一个人机验证题(算术题,5 分钟内有效、一次性)。 + Future captcha() async { + final r = await _send('GET', '/api/user/captcha'); + return CaptchaInfo.fromJson(r as Map); } + /// 当前登录用户;未登录返回 null(后端会用 .GC/user/user.yaml 自动登录)。 Future?> me() async { try { final r = await _send('GET', '/api/user/me'); return r as Map?; } on ApiException catch (e) { if (e.statusCode == 401 || e.statusCode == 403) { - await clearUserToken(); + _userToken = null; return null; } rethrow; } } - Future> register(String username, String password) async { - final r = await _send('POST', '/api/user/register', - body: {'username': username, 'password': password}); + Future> register(String username, String password, + {required String captchaId, required String captchaAnswer}) async { + final r = await _send('POST', '/api/user/register', body: { + 'username': username, + 'password': password, + 'captchaId': captchaId, + 'captcha': captchaAnswer, + }); return r as Map; } @@ -733,15 +705,18 @@ class GcApi { final r = await _send('POST', '/api/user/login', body: {'username': username, 'password': password}); final result = r as Map; - // 保存 session token - if (result.containsKey('session_token')) { - await _saveUserToken(username, result['session_token'] as String); - } + _userToken = result['session_token'] as String?; return result; } + /// 退出登录:清掉后端的 user.yaml 与内存 token。 Future logout() async { - await clearUserToken(); + try { + await _send('POST', '/api/user/logout'); + } catch (_) { + // 后端连不上也要让界面退出 + } + _userToken = null; } Future> signin() async { @@ -749,9 +724,22 @@ class GcApi { return r as Map; } - Future> changeTheme(String color, int cost) async { - final r = await _send('POST', '/api/user/theme', - body: {'color': color, 'cost': cost}); + /// 换主题色:只传颜色,价格由后端判定(预置 50 / 自定义 150)。 + Future> changeTheme(String color) async { + final r = await _send('POST', '/api/user/theme', body: {'color': color}); return r as Map; } } + +/// 人机验证题 +class CaptchaInfo { + const CaptchaInfo({required this.id, required this.question}); + + final String id; + final String question; + + factory CaptchaInfo.fromJson(Map json) => CaptchaInfo( + id: json['id'] as String? ?? '', + question: json['question'] as String? ?? '', + ); +} diff --git a/GC-UI/frontend/lib/i18n.dart b/GC-UI/frontend/lib/i18n.dart index 4156d54..b0b9b0c 100644 --- a/GC-UI/frontend/lib/i18n.dart +++ b/GC-UI/frontend/lib/i18n.dart @@ -160,7 +160,7 @@ class I18n { 'user.login': '登录', 'user.register': '注册', 'user.pick': '二选一', - 'user.theme': '主题颜色', + 'user.themeColor': '主题颜色', 'user.username': '用户名', 'user.password': '密码', 'user.option1': '选项一', @@ -175,6 +175,40 @@ class I18n { 'user.fillAll': '请填写用户名和密码', 'user.fillOptions': '请填写两个选项', 'user.loginFirst': '请先登录', + 'user.notLoggedIn': '未登录', + 'user.loginHint': '登录后可签到攒积分、解锁主题色', + 'user.logout': '退出登录', + 'user.logoutDone': '已退出登录', + 'user.cycleDay': '第 {0} / {1} 天', + 'user.signedToday': '今天已签到,明天再来', + 'user.signedTodayShort': '已签到', + 'user.nextReward': '现在签到可得 {0} 积分', + 'user.refunded': '已退回', + 'user.usernameRule': '1–20 个字符,不能有空格,不能与他人重复', + 'user.captcha': '人机验证', + 'user.captchaMissing': '请先获取人机验证题', + 'user.captchaAnswer': '验证码答案', + 'user.fillCaptcha': '请填写验证码答案', + 'user.refreshCaptcha': '换一题', + 'user.noRecharge': '积分只能通过每日签到获得,不提供任何充值渠道。', + 'user.fortune': '人品值', + 'user.fortuneDesc': '每天可以无限次计算,纯属娱乐,不影响积分。', + 'user.fortuneIdle': '点一下,看看今天手气', + 'user.fortuneRoll': '开始计算', + 'user.fortuneAgain': '再算一次', + 'user.pickDesc': '填两个选项,随机帮你选一个。', + 'user.pickResult': '结果:', + 'user.themeDesc': '默认蓝色免费;预置色 50 积分一个,自定义色 150 积分一个。', + 'user.custom': '自定义', + 'user.customColor': '自定义颜色', + 'user.customColorCost': '自定义颜色需要 {0} 积分。', + 'user.confirmBuy': '购买并应用', + 'user.hexInvalid': '格式应为 #RRGGBB', + 'user.free': '免费', + 'user.themeUpdated': '主题色已更新', + 'user.refundHint': '1 小时内换色可退 80%,当前可退(剩余 {0})', + 'user.minutes': '分钟', + 'user.seconds': '秒', }, 'en': { 'app.name': 'Morris GC', @@ -327,7 +361,7 @@ class I18n { 'user.login': 'Login', 'user.register': 'Register', 'user.pick': 'Pick One', - 'user.theme': 'Theme Color', + 'user.themeColor': 'Theme Color', 'user.username': 'Username', 'user.password': 'Password', 'user.option1': 'Option A', @@ -342,6 +376,40 @@ class I18n { 'user.fillAll': 'Please fill in username and password', 'user.fillOptions': 'Please fill in both options', 'user.loginFirst': 'Please login first', + 'user.notLoggedIn': 'Not signed in', + 'user.loginHint': 'Sign in to earn points and unlock theme colors', + 'user.logout': 'Sign out', + 'user.logoutDone': 'Signed out', + 'user.cycleDay': 'Day {0} / {1}', + 'user.signedToday': 'Signed in today, come back tomorrow', + 'user.signedTodayShort': 'Signed', + 'user.nextReward': 'Sign in now for {0} points', + 'user.refunded': 'refunded', + 'user.usernameRule': '1–20 chars, no spaces, must be unique', + 'user.captcha': 'Verification', + 'user.captchaMissing': 'Please load the verification question first', + 'user.captchaAnswer': 'Answer', + 'user.fillCaptcha': 'Please answer the verification question', + 'user.refreshCaptcha': 'New question', + 'user.noRecharge': 'Points come from daily check-ins only. There is no way to buy points.', + 'user.fortune': 'Luck Meter', + 'user.fortuneDesc': 'Unlimited rolls per day. Just for fun — no points involved.', + 'user.fortuneIdle': 'Tap to see how lucky you are today', + 'user.fortuneRoll': 'Roll', + 'user.fortuneAgain': 'Roll again', + 'user.pickDesc': 'Two options, one random pick.', + 'user.pickResult': 'Result:', + 'user.themeDesc': 'Default blue is free; preset colors cost 50, custom colors 150.', + 'user.custom': 'Custom', + 'user.customColor': 'Custom color', + 'user.customColorCost': 'A custom color costs {0} points.', + 'user.confirmBuy': 'Buy & apply', + 'user.hexInvalid': 'Format must be #RRGGBB', + 'user.free': 'Free', + 'user.themeUpdated': 'Theme color updated', + 'user.refundHint': 'Change within 1 hour for a 80% refund (left {0})', + 'user.minutes': 'min', + 'user.seconds': 's', }, }; diff --git a/GC-UI/frontend/lib/models/user.dart b/GC-UI/frontend/lib/models/user.dart index dce9f87..b5cfccb 100644 --- a/GC-UI/frontend/lib/models/user.dart +++ b/GC-UI/frontend/lib/models/user.dart @@ -1,47 +1,95 @@ -/// 用户记录 +/// 用户记录(对应后端 UserPayload) class UserRecord { const UserRecord({ required this.username, required this.points, required this.consecutiveDays, + required this.cycleDay, + required this.cycleDays, + required this.todaySigned, + required this.nextReward, this.lastSignIn, this.themeColor, + this.themePaid = 0, + this.refundSeconds = 0, }); final String username; final int points; + + /// 连续签到天数(断签会重置) final int consecutiveDays; + + /// 当前处在 30 天周期的第几天(1–30) + final int cycleDay; + + /// 周期长度,固定 30 + final int cycleDays; + + /// 今天是否已签到 + final bool todaySigned; + + /// 下一次签到能拿多少分 + final int nextReward; + final String? lastSignIn; + + /// 形如 `4A90D9`(不带 #) final String? themeColor; + /// 当前这个颜色实际花了多少分 + final int themePaid; + + /// 退款窗口剩余秒数(0 表示没有可退的) + final int refundSeconds; + factory UserRecord.fromJson(Map json) { return UserRecord( username: json['username'] as String? ?? '', - points: json['points'] as int? ?? 0, - consecutiveDays: json['consecutive_days'] as int? ?? 0, + points: (json['points'] as num?)?.toInt() ?? 0, + consecutiveDays: (json['consecutive_days'] as num?)?.toInt() ?? 0, + cycleDay: (json['cycle_day'] as num?)?.toInt() ?? 1, + cycleDays: (json['cycle_days'] as num?)?.toInt() ?? 30, + todaySigned: json['today_signed'] as bool? ?? false, + nextReward: (json['next_reward'] as num?)?.toInt() ?? 10, lastSignIn: json['last_sign_in'] as String?, themeColor: json['theme_color'] as String?, + themePaid: (json['theme_paid'] as num?)?.toInt() ?? 0, + refundSeconds: (json['refund_seconds'] as num?)?.toInt() ?? 0, ); } } -/// 签到奖励配置(30天周期) +/// 签到奖励:30 天一循环,第 7/14/21/28 天给周奖励,第 30 天给满月奖励。 +/// 与后端 `UserService.GetSignInReward` 保持一致。 class SignInRewards { - static const List rewards = [ - 10, 10, 10, 10, 10, 10, 10, // 第1-7天:每天+10 - 20, 20, 20, 20, 20, 20, 20, // 第8-15天:每天+20 - 30, 30, 30, 30, 30, 30, 30, // 第16-23天:每天+30 - 30, 30, 30, 30, 30, 30, 30, // 第24-30天:每天+30 - ]; + static const int cycleDays = 30; static int getReward(int day) { - if (day < 1) day = 1; - if (day > 30) day = ((day - 1) % 30) + 1; - return rewards[day - 1]; + var d = day; + if (d < 1) d = 1; + if (d > cycleDays) d = ((d - 1) % cycleDays) + 1; + switch (d) { + case 7: + return 30; + case 14: + return 40; + case 21: + return 50; + case 28: + return 60; + case 30: + return 100; + } + if (d <= 6) return 10; + if (d <= 13) return 15; + if (d <= 20) return 20; + if (d <= 27) return 25; + return 40; } } -/// 主题颜色 +/// 主题颜色:预置色 50 分一个,自定义色 150 分一个,默认蓝免费。 class ThemeColor { const ThemeColor({required this.name, required this.hex, required this.cost}); @@ -49,14 +97,58 @@ class ThemeColor { final String hex; final int cost; - static const List predefined = [ - ThemeColor(name: '蓝色', hex: '4A90D9', cost: 0), - ThemeColor(name: '红色', hex: 'E74C3C', cost: 50), - ThemeColor(name: '绿色', hex: '27AE60', cost: 50), - ThemeColor(name: '紫色', hex: '9B59B6', cost: 50), - ThemeColor(name: '橙色', hex: 'F39C12', cost: 50), - ThemeColor(name: '青色', hex: '1ABC9C', cost: 50), - ThemeColor(name: '粉色', hex: 'E91E63', cost: 50), - ThemeColor(name: '深蓝', hex: '2C3E50', cost: 50), + /// 默认色(免费) + static const String defaultHex = '4A90D9'; + + /// 预置色单价 + static const int presetCost = 50; + + /// 自定义色单价 + static const int customCost = 150; + + /// 购买后 1 小时内换色可退 80% + static const Duration refundWindow = Duration(hours: 1); + static const double refundRate = 0.8; + + static const List predefined = [ + ThemeColor(name: '蓝色', hex: defaultHex, cost: 0), + ThemeColor(name: '红色', hex: 'E74C3C', cost: presetCost), + ThemeColor(name: '绿色', hex: '27AE60', cost: presetCost), + ThemeColor(name: '紫色', hex: '9B59B6', cost: presetCost), + ThemeColor(name: '橙色', hex: 'F39C12', cost: presetCost), + ThemeColor(name: '青色', hex: '1ABC9C', cost: presetCost), + ThemeColor(name: '粉色', hex: 'E91E63', cost: presetCost), + ThemeColor(name: '深蓝', hex: '2C3E50', cost: presetCost), ]; + + /// 某个十六进制颜色的价格;默认蓝 0,预置色 50,其它 150。 + static int costOf(String hex) { + final h = hex.replaceAll('#', '').toUpperCase(); + if (h == defaultHex) return 0; + for (final c in predefined) { + if (c.hex.toUpperCase() == h) return presetCost; + } + return customCost; + } +} + +/// 人品值结果 +class FortuneResult { + const FortuneResult(this.value, this.comment); + + final int value; + final String comment; + + /// 0–100,越高越「人品爆发」 + static String commentFor(int value) { + if (value >= 96) return '欧皇附体,今天买彩票吧'; + if (value >= 90) return '运气爆棚,适合干大事'; + if (value >= 80) return '手气不错,稳'; + if (value >= 65) return '中上水平,稍微努一下'; + if (value >= 50) return '普普通通,够用'; + if (value >= 35) return '有点背,低调点'; + if (value >= 20) return '今天别赌任何东西'; + if (value >= 8) return '极差,建议躺平'; + return '非酋之王,明天再来'; + } } diff --git a/GC-UI/frontend/lib/pages/user_page.dart b/GC-UI/frontend/lib/pages/user_page.dart index 28dd837..a5f95dc 100644 --- a/GC-UI/frontend/lib/pages/user_page.dart +++ b/GC-UI/frontend/lib/pages/user_page.dart @@ -1,11 +1,14 @@ -import 'package:flutter/material.dart'; import 'dart:math'; + +import 'package:flutter/material.dart'; + import '../controller.dart'; -import '../theme.dart'; +import '../api_client.dart'; import '../i18n.dart'; +import '../theme.dart'; import '../models/user.dart'; -/// 用户页面:登录/注册、签到、主题颜色、二选一 +/// 用户页面:账号(注册/登录/人机验证)、签到、人品值、二选一、主题色 class UserPage extends StatefulWidget { const UserPage({super.key, required this.controller}); @@ -20,16 +23,26 @@ class _UserPageState extends State { bool _loading = true; String? _error; - // 登录/注册表单 + // 登录 / 注册 final _usernameCtrl = TextEditingController(); final _passwordCtrl = TextEditingController(); + final _captchaCtrl = TextEditingController(); bool _isLogin = true; + CaptchaInfo? _captcha; + bool _captchaLoading = false; + bool _submitting = false; + + // 人品值 + FortuneResult? _fortune; + bool _rolling = false; // 二选一 final _option1Ctrl = TextEditingController(); final _option2Ctrl = TextEditingController(); String? _randomResult; + final _rand = Random(); + @override void initState() { super.initState(); @@ -40,30 +53,27 @@ class _UserPageState extends State { void dispose() { _usernameCtrl.dispose(); _passwordCtrl.dispose(); + _captchaCtrl.dispose(); _option1Ctrl.dispose(); _option2Ctrl.dispose(); super.dispose(); } + // ---------------------------------------------------------------- 账号 + Future _loadUser() async { setState(() { _loading = true; _error = null; }); try { - await widget.controller.api.initUserSession(); final resp = await widget.controller.api.me(); if (!mounted) return; - if (resp != null) { - setState(() { - _user = UserRecord.fromJson(resp); - _loading = false; - }); - } else { - setState(() { - _loading = false; - }); - } + setState(() { + _user = resp == null ? null : UserRecord.fromJson(resp); + _loading = false; + }); + _applyTheme(); } catch (e) { if (!mounted) return; setState(() { @@ -73,332 +83,795 @@ class _UserPageState extends State { } } - Future _loginOrRegister() async { + /// 用户买的主题色覆盖全局强调色 + void _applyTheme() { + final hex = _user?.themeColor; + if (hex == null || hex.isEmpty) return; + GcPalette.apply('#$hex'); + } + + Future _refreshCaptcha() async { + setState(() => _captchaLoading = true); + try { + final c = await widget.controller.api.captcha(); + if (!mounted) return; + setState(() { + _captcha = c; + _captchaLoading = false; + _captchaCtrl.clear(); + }); + } catch (e) { + if (!mounted) return; + setState(() => _captchaLoading = false); + _toast(e.toString()); + } + } + + Future _submit() async { final username = _usernameCtrl.text.trim(); final password = _passwordCtrl.text; + if (username.isEmpty || password.isEmpty) { - _showError(T('user.fillAll')); + _toast(T('user.fillAll')); return; } - try { - Map resp; - if (_isLogin) { - resp = await widget.controller.api.login(username, password); - } else { - resp = await widget.controller.api.register(username, password); - if (!mounted) return; - // 注册成功后自动登录 - resp = await widget.controller.api.login(username, password); + if (!_isLogin) { + if (_captcha == null) { + _toast(T('user.captchaMissing')); + return; } + if (_captchaCtrl.text.trim().isEmpty) { + _toast(T('user.fillCaptcha')); + return; + } + } + + setState(() => _submitting = true); + try { + if (_isLogin) { + await widget.controller.api.login(username, password); + } else { + await widget.controller.api.register( + username, + password, + captchaId: _captcha!.id, + captchaAnswer: _captchaCtrl.text.trim(), + ); + await widget.controller.api.login(username, password); + } + + final resp = await widget.controller.api.me(); if (!mounted) return; setState(() { - _user = UserRecord.fromJson(resp); + _user = resp == null ? null : UserRecord.fromJson(resp); _usernameCtrl.clear(); _passwordCtrl.clear(); + _captchaCtrl.clear(); + _captcha = null; + _submitting = false; }); - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text(_isLogin ? T('user.loginSuccess') : T('user.registerSuccess'))), - ); + _applyTheme(); + _toast(_isLogin ? T('user.loginSuccess') : T('user.registerSuccess')); } catch (e) { if (!mounted) return; - _showError(e.toString()); + setState(() => _submitting = false); + // 注册失败时换一题:验证码是一次性的 + if (!_isLogin) _refreshCaptcha(); + _toast(e.toString()); } } + Future _logout() async { + await widget.controller.api.logout(); + if (!mounted) return; + setState(() { + _user = null; + _fortune = null; + }); + GcPalette.apply('#${ThemeColor.defaultHex}'); + _toast(T('user.logoutDone')); + } + Future _signin() async { try { final resp = await widget.controller.api.signin(); if (!mounted) return; - if (resp.containsKey('message') && resp['message'] == '今日已签到') { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text(T('user.alreadySigned'))), - ); + + if (resp['message'] == '今日已签到') { + _toast(T('user.alreadySigned')); return; } + + final payload = resp['user'] as Map?; + final reward = (resp['reward'] as num?)?.toInt() ?? 0; setState(() { - _user = UserRecord.fromJson({ - ...resp, - 'username': _user?.username ?? '', - }); + if (payload != null) _user = UserRecord.fromJson(payload); }); - final reward = resp['reward'] as int? ?? 0; - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text('${T('user.signinSuccess')} +$reward ${T('user.points')}')), - ); + _toast('${T('user.signinSuccess')} +$reward ${T('user.points')}'); } catch (e) { if (!mounted) return; - _showError(e.toString()); + _toast(e.toString()); } } + // ---------------------------------------------------------------- 人品值 + + void _rollFortune() { + setState(() => _rolling = true); + + // 短延时让数字有个「落定」的观感;每天不限次数 + Future.delayed(const Duration(milliseconds: 260), () { + if (!mounted) return; + final value = _rand.nextInt(101); + setState(() { + _fortune = FortuneResult(value, FortuneResult.commentFor(value)); + _rolling = false; + }); + }); + } + + // ---------------------------------------------------------------- 二选一 + void _pickRandom() { - final opt1 = _option1Ctrl.text.trim(); - final opt2 = _option2Ctrl.text.trim(); - if (opt1.isEmpty || opt2.isEmpty) { - _showError(T('user.fillOptions')); + final a = _option1Ctrl.text.trim(); + final b = _option2Ctrl.text.trim(); + if (a.isEmpty || b.isEmpty) { + _toast(T('user.fillOptions')); return; } - final result = Random().nextBool() ? opt1 : opt2; - setState(() => _randomResult = result); + setState(() => _randomResult = _rand.nextBool() ? a : b); } - Future _changeTheme(String hex, int cost) async { + // ---------------------------------------------------------------- 主题色 + + Future _changeTheme(String hex) async { if (_user == null) { - _showError(T('user.loginFirst')); + _toast(T('user.loginFirst')); return; } try { - final resp = await widget.controller.api.changeTheme(hex, cost); + final resp = await widget.controller.api.changeTheme(hex); if (!mounted) return; - if (resp.containsKey('message')) { - setState(() { - _user = UserRecord( - username: _user!.username, - points: resp['points'] as int? ?? _user!.points, - consecutiveDays: _user!.consecutiveDays, - lastSignIn: _user!.lastSignIn, - themeColor: '0x${resp['theme_color'] ?? hex}', - ); - }); - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('主题已更新')), - ); - } + + final payload = resp['user'] as Map?; + setState(() { + if (payload != null) _user = UserRecord.fromJson(payload); + }); + _applyTheme(); + + final refunded = (resp['refunded'] as num?)?.toInt() ?? 0; + _toast(refunded > 0 + ? '${T('user.themeUpdated')},${T('user.refunded')} +$refunded' + : T('user.themeUpdated')); } catch (e) { if (!mounted) return; - _showError(e.toString()); + _toast(e.toString()); } } - void _showError(String msg) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text(msg)), + Future _pickCustomColor() async { + if (_user == null) { + _toast(T('user.loginFirst')); + return; + } + + final controller = TextEditingController(text: '#7C6CFF'); + final hex = await showDialog( + context: context, + builder: (ctx) => StatefulBuilder( + builder: (ctx, setLocal) { + final raw = controller.text.replaceAll('#', '').trim(); + final valid = raw.length == 6 && int.tryParse(raw, radix: 16) != null; + final preview = valid + ? Color(0xFF000000 | int.parse(raw, radix: 16)) + : GcColors.surface; + + return AlertDialog( + title: Text(T('user.customColor')), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + T('user.customColorCost', ['${ThemeColor.customCost}']), + style: TextStyle(color: GcColors.muted, fontSize: 13), + ), + const SizedBox(height: GcSpace.md), + TextField( + controller: controller, + autofocus: true, + decoration: InputDecoration( + labelText: '#RRGGBB', + border: const OutlineInputBorder(), + errorText: valid || raw.isEmpty ? null : T('user.hexInvalid'), + ), + onChanged: (_) => setLocal(() {}), + ), + const SizedBox(height: GcSpace.md), + Row( + children: [ + Container( + width: 44, + height: 44, + decoration: BoxDecoration( + color: preview, + borderRadius: BorderRadius.circular(GcRadius.control), + border: Border.all(color: GcColors.line), + ), + ), + const SizedBox(width: GcSpace.md), + Expanded( + child: Text( + valid ? '#${raw.toUpperCase()}' : '—', + style: TextStyle(color: GcColors.muted), + ), + ), + ], + ), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(ctx).pop(), + child: Text(T('common.cancel')), + ), + FilledButton( + onPressed: + valid ? () => Navigator.of(ctx).pop(raw.toUpperCase()) : null, + child: Text(T('user.confirmBuy')), + ), + ], + ); + }, + ), ); + + controller.dispose(); + if (hex != null) await _changeTheme(hex); } + // ---------------------------------------------------------------- 工具 + + void _toast(String message) { + if (!mounted) return; + ScaffoldMessenger.of(context) + ..hideCurrentSnackBar() + ..showSnackBar(SnackBar(content: Text(message))); + } + + String _formatRefund(int seconds) { + if (seconds >= 60) return '${seconds ~/ 60} ${T('user.minutes')}'; + return '$seconds ${T('user.seconds')}'; + } + + // ---------------------------------------------------------------- UI + @override Widget build(BuildContext context) { + if (_loading) { + return Scaffold( + backgroundColor: GcColors.appBg, + body: const Center(child: CircularProgressIndicator()), + ); + } + return Scaffold( backgroundColor: GcColors.appBg, - body: _loading - ? const Center(child: CircularProgressIndicator()) - : SingleChildScrollView( - padding: const EdgeInsets.all(GcSpace.xxl), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - // 用户信息卡片 - if (_user != null) ...[ - GcCard( - padding: const EdgeInsets.all(GcSpace.lg), - child: Row( - children: [ - Icon(Icons.person_rounded, size: 40, color: GcColors.accent), - const SizedBox(width: GcSpace.md), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - _user!.username, - style: const TextStyle( - fontSize: 18, - fontWeight: FontWeight.w700, - ), - ), - const SizedBox(height: 4), - Text( - '${T('user.points')}: ${_user!.points}', - style: TextStyle(color: GcColors.muted), - ), - Text( - '${T('user.days')}: ${_user!.consecutiveDays}', - style: TextStyle(color: GcColors.muted), - ), - ], - ), - ), - FilledButton( - onPressed: _signin, - child: Text(T('user.signin')), - ), - ], - ), - ), - const SizedBox(height: GcSpace.lg), - ], - - // 登录/注册表单 - GcCard( - padding: const EdgeInsets.all(GcSpace.lg), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - _isLogin ? T('user.login') : T('user.register'), - style: const TextStyle( - fontSize: 16, - fontWeight: FontWeight.w600, - ), - ), - const SizedBox(height: GcSpace.md), - TextField( - controller: _usernameCtrl, - decoration: InputDecoration( - labelText: T('user.username'), - border: const OutlineInputBorder(), - ), - ), - const SizedBox(height: GcSpace.md), - TextField( - controller: _passwordCtrl, - decoration: InputDecoration( - labelText: T('user.password'), - border: const OutlineInputBorder(), - ), - obscureText: true, - ), - const SizedBox(height: GcSpace.md), - FilledButton( - onPressed: _loginOrRegister, - child: Text(_isLogin ? T('user.login') : T('user.register')), - ), - TextButton( - onPressed: () => setState(() => _isLogin = !_isLogin), - child: Text(_isLogin ? T('user.switchToRegister') : T('user.switchToLogin')), - ), - ], - ), - ), - const SizedBox(height: GcSpace.lg), - - // 二选一 - GcCard( - padding: const EdgeInsets.all(GcSpace.lg), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - T('user.pick'), - style: const TextStyle( - fontSize: 16, - fontWeight: FontWeight.w600, - ), - ), - const SizedBox(height: GcSpace.md), - TextField( - controller: _option1Ctrl, - decoration: InputDecoration( - labelText: T('user.option1'), - border: const OutlineInputBorder(), - ), - ), - const SizedBox(height: GcSpace.md), - TextField( - controller: _option2Ctrl, - decoration: InputDecoration( - labelText: T('user.option2'), - border: const OutlineInputBorder(), - ), - ), - const SizedBox(height: GcSpace.md), - FilledButton( - onPressed: _pickRandom, - child: Text(T('user.pickRandom')), - ), - if (_randomResult != null) ...[ - const SizedBox(height: GcSpace.md), - GcCard( - child: Text( - _randomResult!, - textAlign: TextAlign.center, - style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600), - ), - ), - ], - ], - ), - ), - const SizedBox(height: GcSpace.lg), - - // 主题颜色 - GcCard( - padding: const EdgeInsets.all(GcSpace.lg), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - T('user.theme'), - style: const TextStyle( - fontSize: 16, - fontWeight: FontWeight.w600, - ), - ), - const SizedBox(height: GcSpace.md), - Wrap( - spacing: GcSpace.md, - runSpacing: GcSpace.md, - children: ThemeColor.predefined.map((c) { - final canAfford = _user == null || _user!.points >= c.cost; - final isCurrent = _user?.themeColor == '0x$c.hex'; - return InkWell( - onTap: canAfford ? () => _changeTheme(c.hex, c.cost) : null, - borderRadius: BorderRadius.circular(8), - child: Container( - width: 60, - height: 60, - decoration: BoxDecoration( - color: Color(int.parse('0xFF${c.hex}')), - borderRadius: BorderRadius.circular(8), - border: Border.all( - color: isCurrent ? GcColors.accent : GcColors.line, - width: isCurrent ? 2 : 1, - ), - ), - child: Stack( - children: [ - if (c.cost > 0 && !_canAfford(c.cost)) - Container( - decoration: BoxDecoration( - color: Colors.black.withOpacity(0.5), - borderRadius: BorderRadius.circular(8), - ), - child: Center( - child: Text( - '${c.cost}', - style: const TextStyle(color: Colors.white, fontSize: 12), - ), - ), - ), - if (isCurrent) - const Positioned( - bottom: 2, - right: 2, - child: Icon(Icons.check_rounded, size: 16, color: Colors.white), - ), - ], - ), - ), - ); - }).toList(), - ), - ], - ), - ), - if (_error != null) ...[ - const SizedBox(height: GcSpace.md), - Text(_error!, style: const TextStyle(color: Colors.red)), - ], - ], - ), - ), + body: SingleChildScrollView( + padding: const EdgeInsets.all(GcSpace.xxl), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _header(), + const SizedBox(height: GcSpace.lg), + if (_user == null) ...[ + _authCard(), + const SizedBox(height: GcSpace.lg), + ], + _fortuneCard(), + const SizedBox(height: GcSpace.lg), + _pickCard(), + const SizedBox(height: GcSpace.lg), + _themeCard(), + if (_error != null) ...[ + const SizedBox(height: GcSpace.md), + Text(_error!, style: TextStyle(color: GcColors.danger)), + ], + ], + ), + ), ); } - bool _canAfford(int cost) { - if (cost <= 0) return true; - if (_user == null) return false; - return _user!.points >= cost; + Widget _header() { + final user = _user; + return GcCard( + padding: const EdgeInsets.all(GcSpace.lg), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + CircleAvatar( + radius: 22, + backgroundColor: GcColors.accentSoft, + child: Icon(Icons.person_rounded, color: GcColors.accent), + ), + const SizedBox(width: GcSpace.md), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + user?.username ?? T('user.notLoggedIn'), + style: const TextStyle( + fontSize: 18, fontWeight: FontWeight.w700), + ), + const SizedBox(height: 2), + Text( + user == null + ? T('user.loginHint') + : '${T('user.points')} ${user.points} · ' + '${T('user.days')} ${user.consecutiveDays}', + style: TextStyle(color: GcColors.muted, fontSize: 13), + ), + ], + ), + ), + if (user != null) + OutlinedButton( + onPressed: _logout, + child: Text(T('user.logout')), + ), + ], + ), + if (user != null) ...[ + const SizedBox(height: GcSpace.lg), + Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + T('user.cycleDay', + ['${user.cycleDay}', '${user.cycleDays}']), + style: TextStyle(color: GcColors.muted, fontSize: 13), + ), + const SizedBox(height: 6), + ClipRRect( + borderRadius: BorderRadius.circular(GcRadius.pill), + child: LinearProgressIndicator( + value: user.cycleDay / user.cycleDays, + minHeight: 6, + backgroundColor: GcColors.surfaceAlt, + ), + ), + const SizedBox(height: 6), + Text( + user.todaySigned + ? T('user.signedToday') + : T('user.nextReward', ['${user.nextReward}']), + style: TextStyle(color: GcColors.faint, fontSize: 12), + ), + ], + ), + ), + const SizedBox(width: GcSpace.lg), + FilledButton( + onPressed: user.todaySigned ? null : _signin, + child: Text(user.todaySigned + ? T('user.signedTodayShort') + : T('user.signin')), + ), + ], + ), + ], + ], + ), + ); + } + + Widget _authCard() { + return GcCard( + padding: const EdgeInsets.all(GcSpace.lg), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Text( + _isLogin ? T('user.login') : T('user.register'), + style: + const TextStyle(fontSize: 16, fontWeight: FontWeight.w600), + ), + const Spacer(), + TextButton( + onPressed: () { + setState(() { + _isLogin = !_isLogin; + _captcha = null; + _captchaCtrl.clear(); + }); + if (!_isLogin) _refreshCaptcha(); + }, + child: Text(_isLogin + ? T('user.switchToRegister') + : T('user.switchToLogin')), + ), + ], + ), + const SizedBox(height: GcSpace.md), + TextField( + controller: _usernameCtrl, + decoration: InputDecoration( + labelText: T('user.username'), + helperText: _isLogin ? null : T('user.usernameRule'), + border: const OutlineInputBorder(), + ), + ), + const SizedBox(height: GcSpace.md), + TextField( + controller: _passwordCtrl, + obscureText: true, + decoration: InputDecoration( + labelText: T('user.password'), + border: const OutlineInputBorder(), + ), + onSubmitted: (_) => _submit(), + ), + + // 注册才需要人机验证 + if (!_isLogin) ...[ + const SizedBox(height: GcSpace.lg), + Row( + children: [ + Expanded( + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: GcSpace.md, vertical: GcSpace.md), + decoration: BoxDecoration( + color: GcColors.surfaceAlt, + borderRadius: BorderRadius.circular(GcRadius.control), + border: Border.all(color: GcColors.line), + ), + child: Row( + children: [ + Icon(Icons.shield_outlined, + size: 18, color: GcColors.muted), + const SizedBox(width: GcSpace.sm), + Text( + _captchaLoading + ? T('common.loading') + : (_captcha?.question ?? T('user.captcha')), + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.w600, + letterSpacing: 1), + ), + ], + ), + ), + ), + IconButton( + tooltip: T('user.refreshCaptcha'), + onPressed: _captchaLoading ? null : _refreshCaptcha, + icon: const Icon(Icons.refresh_rounded), + ), + ], + ), + const SizedBox(height: GcSpace.md), + TextField( + controller: _captchaCtrl, + keyboardType: TextInputType.number, + decoration: InputDecoration( + labelText: T('user.captchaAnswer'), + border: const OutlineInputBorder(), + ), + onSubmitted: (_) => _submit(), + ), + ], + + const SizedBox(height: GcSpace.lg), + SizedBox( + height: GcSize.control, + child: FilledButton( + onPressed: _submitting ? null : _submit, + child: _submitting + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2)) + : Text(_isLogin ? T('user.login') : T('user.register')), + ), + ), + const SizedBox(height: GcSpace.sm), + Text( + T('user.noRecharge'), + style: TextStyle(color: GcColors.faint, fontSize: 12), + ), + ], + ), + ); + } + + Widget _fortuneCard() { + return GcCard( + padding: const EdgeInsets.all(GcSpace.lg), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(T('user.fortune'), + style: + const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)), + const SizedBox(height: 4), + Text(T('user.fortuneDesc'), + style: TextStyle(color: GcColors.muted, fontSize: 13)), + const SizedBox(height: GcSpace.lg), + Row( + children: [ + Container( + width: 96, + height: 96, + alignment: Alignment.center, + decoration: BoxDecoration( + color: GcColors.accentSoft, + shape: BoxShape.circle, + border: Border.all(color: GcColors.accent, width: 2), + ), + child: Text( + _rolling ? '…' : (_fortune?.value.toString() ?? '?'), + style: const TextStyle( + fontSize: 34, fontWeight: FontWeight.w700, height: 1.0), + ), + ), + const SizedBox(width: GcSpace.lg), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + _fortune?.comment ?? T('user.fortuneIdle'), + style: const TextStyle( + fontSize: 14, fontWeight: FontWeight.w600), + ), + const SizedBox(height: GcSpace.md), + FilledButton( + onPressed: _rolling ? null : _rollFortune, + child: Text(_fortune == null + ? T('user.fortuneRoll') + : T('user.fortuneAgain')), + ), + ], + ), + ), + ], + ), + ], + ), + ); + } + + Widget _pickCard() { + return GcCard( + padding: const EdgeInsets.all(GcSpace.lg), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(T('user.pick'), + style: + const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)), + const SizedBox(height: 4), + Text(T('user.pickDesc'), + style: TextStyle(color: GcColors.muted, fontSize: 13)), + const SizedBox(height: GcSpace.md), + Row( + children: [ + Expanded( + child: TextField( + controller: _option1Ctrl, + decoration: InputDecoration( + labelText: T('user.option1'), + border: const OutlineInputBorder(), + ), + ), + ), + const SizedBox(width: GcSpace.md), + Expanded( + child: TextField( + controller: _option2Ctrl, + decoration: InputDecoration( + labelText: T('user.option2'), + border: const OutlineInputBorder(), + ), + ), + ), + ], + ), + const SizedBox(height: GcSpace.md), + Row( + children: [ + FilledButton( + onPressed: _pickRandom, + child: Text(T('user.pickRandom')), + ), + if (_randomResult != null) ...[ + const SizedBox(width: GcSpace.lg), + Expanded( + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: GcSpace.md, vertical: GcSpace.sm), + decoration: BoxDecoration( + color: GcColors.accentSoft, + borderRadius: BorderRadius.circular(GcRadius.control), + ), + child: Text( + '${T('user.pickResult')} ${_randomResult!}', + style: const TextStyle( + fontSize: 15, fontWeight: FontWeight.w600), + ), + ), + ), + ], + ], + ), + ], + ), + ); + } + + Widget _themeCard() { + final user = _user; + final current = user?.themeColor?.toUpperCase(); + final canRefund = (user?.refundSeconds ?? 0) > 0; + + return GcCard( + padding: const EdgeInsets.all(GcSpace.lg), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(T('user.themeColor'), + style: + const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)), + const SizedBox(height: 4), + Text(T('user.themeDesc'), + style: TextStyle(color: GcColors.muted, fontSize: 13)), + if (canRefund) ...[ + const SizedBox(height: 6), + Text( + T('user.refundHint', [_formatRefund(user!.refundSeconds)]), + style: TextStyle(color: GcColors.ok, fontSize: 12), + ), + ], + const SizedBox(height: GcSpace.lg), + Wrap( + spacing: GcSpace.md, + runSpacing: GcSpace.md, + children: [ + ...ThemeColor.predefined.map((c) => _swatch( + name: c.name, + hex: c.hex, + cost: c.cost, + selected: current == c.hex.toUpperCase(), + )), + _customSwatch( + selected: current != null && + ThemeColor.costOf(current) == ThemeColor.customCost, + ), + ], + ), + ], + ), + ); + } + + Widget _swatch({ + required String name, + required String hex, + required int cost, + required bool selected, + }) { + final points = _user?.points ?? 0; + final affordable = cost == 0 || points >= cost; + + return InkWell( + onTap: () => _changeTheme(hex), + borderRadius: BorderRadius.circular(GcRadius.control), + child: Column( + children: [ + Stack( + children: [ + Container( + width: 56, + height: 56, + decoration: BoxDecoration( + color: Color(0xFF000000 | int.parse(hex, radix: 16)), + borderRadius: BorderRadius.circular(GcRadius.control), + border: Border.all( + color: selected ? GcColors.accent : GcColors.line, + width: selected ? 2.5 : 1, + ), + ), + ), + if (selected) + const Positioned( + right: 3, + bottom: 3, + child: Icon(Icons.check_circle_rounded, + size: 16, color: Colors.white), + ), + if (!affordable) + Positioned.fill( + child: Container( + decoration: BoxDecoration( + // ignore: deprecated_member_use + color: Colors.black.withOpacity(0.45), + borderRadius: BorderRadius.circular(GcRadius.control), + ), + child: const Icon(Icons.lock_outline, + size: 18, color: Colors.white), + ), + ), + ], + ), + const SizedBox(height: 4), + Text(name, style: TextStyle(fontSize: 11, color: GcColors.muted)), + Text( + cost == 0 ? T('user.free') : '$cost', + style: TextStyle( + fontSize: 11, + color: affordable ? GcColors.faint : GcColors.danger, + ), + ), + ], + ), + ); + } + + Widget _customSwatch({required bool selected}) { + final canAfford = (_user?.points ?? 0) >= ThemeColor.customCost; + return InkWell( + onTap: _pickCustomColor, + borderRadius: BorderRadius.circular(GcRadius.control), + child: Column( + children: [ + Container( + width: 56, + height: 56, + decoration: BoxDecoration( + gradient: const SweepGradient( + colors: [ + Color(0xFFFF7A7A), + Color(0xFFFFC46B), + Color(0xFF6BE3A2), + Color(0xFF4FD1C5), + Color(0xFF7C6CFF), + Color(0xFFFF8FB1), + Color(0xFFFF7A7A), + ], + ), + borderRadius: BorderRadius.circular(GcRadius.control), + border: Border.all( + color: selected ? GcColors.accent : GcColors.line, + width: selected ? 2.5 : 1, + ), + ), + child: Icon(Icons.colorize_rounded, + size: 20, color: canAfford ? Colors.white : Colors.white70), + ), + const SizedBox(height: 4), + Text(T('user.custom'), + style: TextStyle(fontSize: 11, color: GcColors.muted)), + Text( + '${ThemeColor.customCost}', + style: TextStyle( + fontSize: 11, + color: canAfford ? GcColors.faint : GcColors.danger, + ), + ), + ], + ), + ); } } -- 2.54.0