From 06eb4875a10f608d2d1d810a2b57da404ae3ff95 Mon Sep 17 00:00:00 2001 From: Morris Date: Wed, 18 Nov 2026 00:23:48 +0800 Subject: [PATCH] =?UTF-8?q?fix(about):=20=E5=BC=80=E5=8F=91=E8=80=85?= =?UTF-8?q?=E6=94=B9=E4=B8=BA=E8=AF=BB=E5=8F=96=E4=BB=93=E5=BA=93=E7=9C=9F?= =?UTF-8?q?=E5=AE=9E=E6=8F=90=E4=BA=A4=E8=80=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - ContributorsService 改用 /commits 分页统计,不再依赖需要登录的 /collaborators - 同一人的多个 git 身份按别名归并(Morris_1 / 2509_92447106 / 两个邮箱) - 自动化提交(agent@teamily.ai)不计入开发者,避免出现在关于页 - 关于页「开发者」标题标注数据来源,贡献数为真实提交数 - 结果缓存 10 分钟;接口失败时静默降级为空列表,不影响关于页其它内容 --- GC-UI/frontend/lib/i18n.dart | 2 + GC-UI/frontend/lib/pages.dart | 5 +- GC/src/Services/ContributorsService.cs | 234 ++++++++++++++++++------- 3 files changed, 180 insertions(+), 61 deletions(-) diff --git a/GC-UI/frontend/lib/i18n.dart b/GC-UI/frontend/lib/i18n.dart index c386d42..88ebf21 100644 --- a/GC-UI/frontend/lib/i18n.dart +++ b/GC-UI/frontend/lib/i18n.dart @@ -124,6 +124,7 @@ class I18n { 'common.error': '出错了', 'common.refresh': '刷新', 'about.developers': '开发者', + 'about.contributorsHint': '来自仓库提交记录', 'about.repository': '仓库', 'about.openRepository': '打开仓库', 'about.contributions': '{0} 次提交', @@ -248,6 +249,7 @@ class I18n { 'common.error': 'Something went wrong', 'common.refresh': 'Refresh', 'about.developers': 'Developers', + 'about.contributorsHint': 'From repository commits', 'about.repository': 'Repository', 'about.openRepository': 'Open repository', 'about.contributions': '{0} commits', diff --git a/GC-UI/frontend/lib/pages.dart b/GC-UI/frontend/lib/pages.dart index 7a1a6f4..1b43e7c 100644 --- a/GC-UI/frontend/lib/pages.dart +++ b/GC-UI/frontend/lib/pages.dart @@ -1786,7 +1786,10 @@ class _AboutPageViewState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - GcSectionTitle(T('about.developers')), + GcSectionTitle( + T('about.developers'), + trailing: GcHint(T('about.contributorsHint')), + ), const SizedBox(height: 12), if ((_about?.contributors ?? const []).isEmpty) GcHint(T('about.noContributors')) diff --git a/GC/src/Services/ContributorsService.cs b/GC/src/Services/ContributorsService.cs index 5193309..ce3c5b4 100644 --- a/GC/src/Services/ContributorsService.cs +++ b/GC/src/Services/ContributorsService.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Net.Http; using System.Text.Json; using System.Threading; @@ -7,25 +8,22 @@ using System.Threading.Tasks; namespace GC.Services; -/// GitCode 仓库的一位贡献者。 +/// 仓库的一位贡献者(按人归并后的结果)。 public sealed class Contributor { public string Name { get; set; } = ""; public string? Email { get; set; } - /// 提交次数(API 里的 contributions)。 + /// 提交次数。 public int Contributions { get; set; } /// 接口直接返回的头像地址(Gitea 的 avatar_url);为空时按邮箱哈希生成。 public string? Avatar { get; set; } - /// - /// 登录名 -> 展示名。GitCode 的 contributors 接口只返回账号登录名, - /// 不返回真实姓名,这里做一层映射,让关于页显示作者想展示的名字。 - /// - private static readonly Dictionary DisplayNames = new(StringComparer.OrdinalIgnoreCase) - { - ["Morris_1"] = "Morris" - }; + /// 最近一次提交时间,用于贡献数相同时排序。 + public DateTimeOffset? LastCommit { get; set; } + + /// 关于页展示的名字。 + public string DisplayName => string.IsNullOrWhiteSpace(Name) ? "匿名" : Name; /// 头像地址:优先用接口返回的头像,否则按邮箱哈希拼 GitCode 头像。 public string? AvatarUrl => @@ -37,25 +35,43 @@ public sealed class Contributor System.Security.Cryptography.MD5.HashData( System.Text.Encoding.UTF8.GetBytes(Email!.Trim().ToLowerInvariant()))) .ToLowerInvariant()}"; - - public string DisplayName - { - get - { - if (string.IsNullOrWhiteSpace(Name)) return "匿名"; - return DisplayNames.TryGetValue(Name.Trim(), out var mapped) ? mapped : Name; - } - } } /// -/// 读取 GitCode 仓库的贡献者列表(用于「关于」页面展示开发者)。 -/// 失败时静默返回空列表,不影响关于页其它内容。 +/// 读取仓库的真实贡献者:翻页拉提交记录,按作者归并统计。 +/// +/// 为什么不用 /collaborators:Gitea 的协同者列表要求登录,且只包含被显式 +/// 添加的协作者,和「谁真的写了代码」是两回事。这里直接读 /commits, +/// 统计每个人真实的提交数,失败时静默返回空列表,不影响关于页其它内容。 /// public static class ContributorsService { + private const int PageSize = 50; + private const int MaxPages = 12; + private const int MaxShown = 8; + private static readonly TimeSpan CacheTtl = TimeSpan.FromMinutes(10); + private static readonly HttpClient Http = CreateHttp(); + /// 同一作者的多个 git 身份 -> 统一展示名。 + private static readonly Dictionary Aliases = new(StringComparer.OrdinalIgnoreCase) + { + ["morris"] = "Morris", + ["morris_1"] = "Morris", + ["2509_92447106"] = "Morris", + ["chenmoyuan1214@qq.com"] = "Morris", + ["morris@xhmcl.com"] = "Morris", + }; + + /// 自动化提交(CI / 助手账号),不计入开发者。 + private static readonly HashSet IgnoredEmails = new(StringComparer.OrdinalIgnoreCase) + { + "agent@teamily.ai", + }; + + private static readonly object Gate = new(); + private static (DateTimeOffset At, string Key, List Items)? _cache; + private static HttpClient CreateHttp() { var c = new HttpClient { Timeout = TimeSpan.FromSeconds(10) }; @@ -64,74 +80,172 @@ public static class ContributorsService return c; } - /// 按仓库地址推导贡献者接口:Xhmcl(Gitea) 与 GitCode 结构不同。 + /// 按仓库地址推导接口:Xhmcl(Gitea) 与 GitCode 结构不同。 public static string BuildUrl(string repository) { var raw = string.IsNullOrWhiteSpace(repository) ? SourcePreset.Xhmcl.HomeUrl : repository.Trim(); if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri)) - return "https://git.xhmcl.com/api/v1/repos/Morris/GC/collaborators"; + return "https://git.xhmcl.com/api/v1/repos/Morris/GC/commits"; var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries); if (parts.Length < 2) - return "https://git.xhmcl.com/api/v1/repos/Morris/GC/collaborators"; + return "https://git.xhmcl.com/api/v1/repos/Morris/GC/commits"; var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase) ? parts[1][..^4] : parts[1]; - // GitCode 代码保留,仅在仓库确实指向 GitCode 时才走它。 + // GitCode 的实现在仓库仍指向 gitcode.com 时才走它。 if (uri.Host.Contains("gitcode.com", StringComparison.OrdinalIgnoreCase)) return $"https://api.gitcode.com/api/v5/repos/{parts[0]}/{repo}/contributors"; - return $"https://{uri.Host}/api/v1/repos/{parts[0]}/{repo}/collaborators"; + return $"https://{uri.Host}/api/v1/repos/{parts[0]}/{repo}/commits"; } public static async Task> FetchAsync(string repository, CancellationToken ct = default) { var url = BuildUrl(repository); + lock (Gate) + { + if (_cache is { } hit && hit.Key == url && DateTimeOffset.UtcNow - hit.At < CacheTtl) + return hit.Items; + } + + List list; try { using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); - timeout.CancelAfter(TimeSpan.FromSeconds(10)); + timeout.CancelAfter(TimeSpan.FromSeconds(15)); - var text = await Http.GetStringAsync(url, timeout.Token); - var trimmed = text.TrimStart(); - if (trimmed.Length == 0 || trimmed[0] != '[') return new List(); - - using var doc = JsonDocument.Parse(text); - var list = new List(); - foreach (var item in doc.RootElement.EnumerateArray()) - { - // Gitea: login / avatar_url;GitCode: name / email / contributions。 - if (item.TryGetProperty("login", out var login)) - { - list.Add(new Contributor - { - Name = login.GetString() ?? "", - Avatar = item.TryGetProperty("avatar_url", out var avatar) - ? avatar.GetString() : null - }); - continue; - } - - list.Add(new Contributor - { - Name = item.TryGetProperty("name", out var name) - ? name.GetString() ?? "" : "", - Email = item.TryGetProperty("email", out var email) - ? email.GetString() : null, - Contributions = item.TryGetProperty("contributions", out var c) && - c.TryGetInt32(out var count) ? count : 0 - }); - } - - list.Sort((a, b) => b.Contributions.CompareTo(a.Contributions)); - return list; + list = url.Contains("api.gitcode.com", StringComparison.OrdinalIgnoreCase) + ? await FetchFromGitCodeAsync(url, timeout.Token) + : await FetchFromCommitsAsync(url, timeout.Token); } catch (Exception ex) { Console.Error.WriteLine($"读取贡献者失败: {ex.Message}"); return new List(); } + + lock (Gate) _cache = (DateTimeOffset.UtcNow, url, list); + return list; } + + /// Gitea:翻页读提交记录并归并作者。 + private static async Task> FetchFromCommitsAsync(string commitUrl, CancellationToken ct) + { + var byKey = new Dictionary(StringComparer.OrdinalIgnoreCase); + + for (var page = 1; page <= MaxPages; page++) + { + var url = $"{commitUrl}?limit={PageSize}&page={page}&stat=false"; + var text = await Http.GetStringAsync(url, ct); + using var doc = JsonDocument.Parse(text); + if (doc.RootElement.ValueKind != JsonValueKind.Array) break; + + var seen = 0; + foreach (var item in doc.RootElement.EnumerateArray()) + { + seen++; + + string? login = null, name = null, email = null, avatar = null; + DateTimeOffset? date = null; + + if (item.TryGetProperty("author", out var author) && + author.ValueKind == JsonValueKind.Object) + { + login = author.TryGetProperty("login", out var l) ? l.GetString() : null; + avatar = author.TryGetProperty("avatar_url", out var a) ? a.GetString() : null; + } + + if (item.TryGetProperty("commit", out var commit) && + commit.TryGetProperty("author", out var ca) && + ca.ValueKind == JsonValueKind.Object) + { + name = ca.TryGetProperty("name", out var n) ? n.GetString() : null; + email = ca.TryGetProperty("email", out var e) ? e.GetString() : email; + if (ca.TryGetProperty("date", out var d) && + DateTimeOffset.TryParse(d.GetString(), out var parsed)) + date = parsed; + } + + Add(byKey, login, name, email, avatar, date); + } + + if (seen < PageSize) break; + } + + return Sort(byKey.Values); + } + + /// GitCode:contributors 接口直接返回贡献数与邮箱。 + private static async Task> FetchFromGitCodeAsync(string url, CancellationToken ct) + { + var text = await Http.GetStringAsync(url, ct); + if (text.TrimStart().Length == 0 || text.TrimStart()[0] != '[') + return new List(); + + var byKey = new Dictionary(StringComparer.OrdinalIgnoreCase); + using var doc = JsonDocument.Parse(text); + foreach (var item in doc.RootElement.EnumerateArray()) + { + var name = item.TryGetProperty("name", out var n) ? n.GetString() : null; + var email = item.TryGetProperty("email", out var e) ? e.GetString() : null; + var count = item.TryGetProperty("contributions", out var c) && c.TryGetInt32(out var v) ? v : 1; + var contributor = Add(byKey, null, name, email, null, null, count); + if (contributor != null) contributor.Contributions = Math.Max(contributor.Contributions, count); + } + + return Sort(byKey.Values); + } + + private static Contributor? Add( + Dictionary byKey, + string? login, string? name, string? email, string? avatar, DateTimeOffset? date, + int weight = 1) + { + if (!string.IsNullOrWhiteSpace(email) && IgnoredEmails.Contains(email.Trim())) + return null; + + var (key, display) = Resolve(login, name, email); + if (!byKey.TryGetValue(key, out var contributor)) + { + contributor = new Contributor { Name = display }; + byKey[key] = contributor; + } + + contributor.Contributions += weight; + if (string.IsNullOrWhiteSpace(contributor.Email) && !string.IsNullOrWhiteSpace(email)) + contributor.Email = email; + if (string.IsNullOrWhiteSpace(contributor.Avatar) && !string.IsNullOrWhiteSpace(avatar)) + contributor.Avatar = avatar; + if (date.HasValue && (contributor.LastCommit == null || date > contributor.LastCommit)) + contributor.LastCommit = date; + + return contributor; + } + + /// 把同一个人在不同时期的 git 身份归并到同一个展示名。 + private static (string Key, string Display) Resolve(string? login, string? name, string? email) + { + foreach (var raw in new[] { login, name, email }) + { + if (string.IsNullOrWhiteSpace(raw)) continue; + if (Aliases.TryGetValue(raw.Trim(), out var display)) + return ("#" + display.ToLowerInvariant(), display); + } + + var label = !string.IsNullOrWhiteSpace(login) ? login! + : !string.IsNullOrWhiteSpace(name) ? name! + : email!; + return (label.Trim().ToLowerInvariant(), label.Trim()); + } + + private static List Sort(IEnumerable items) => + items + .OrderByDescending(c => c.Contributions) + .ThenByDescending(c => c.LastCommit ?? DateTimeOffset.MinValue) + .ThenBy(c => c.Name, StringComparer.OrdinalIgnoreCase) + .Take(MaxShown) + .ToList(); }