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, + ), + ), + ], + ), + ); } }