From 406485f3f3174c0f4f0214f6cbb7699b677154e5 Mon Sep 17 00:00:00 2001 From: ZhonFortune Date: Sat, 28 Nov 2026 18:14:00 +0800 Subject: [PATCH 1/2] Fix: Improve GitHub avatar resolution with fallback chain - Restrict GitHub noreply email regex to users.noreply.github.com and make it case-insensitive - Add fallback URL chain trying user ID, username, login name based avatar endpoints and Gravatar - Pass author name through avatar requests to allow username based lookups - Validate GitHub login candidates before constructing GitHub avatar URLs - Retry avatar downloads on timeout, rate limit and server error responses with delayed attempts - Stream avatar downloads directly to file to avoid buffering entire response - Register github-actions bot default avatar mapping - Use UTF-8 encoding for email hashing instead of default encoding - Remove null cached bitmaps from image cache instead of returning them - Ignore null bitmaps when adding entries to the image cache - Re-add request name dictionary defensively and clean up entries after each request --- src/Models/AvatarManager.cs | 145 +++++++++++++++++++++++++++++------- src/Views/Avatar.cs | 4 +- 2 files changed, 119 insertions(+), 30 deletions(-) diff --git a/src/Models/AvatarManager.cs b/src/Models/AvatarManager.cs index 7e4593fd86..f8d007f30c 100644 --- a/src/Models/AvatarManager.cs +++ b/src/Models/AvatarManager.cs @@ -32,7 +32,7 @@ public static AvatarManager Instance private static AvatarManager _instance = null; - [GeneratedRegex(@"^(?:(\d+)\+)?(.+?)@.+\.github\.com$")] + [GeneratedRegex(@"^(?:(\d+)\+)?(.+?)@users\.noreply\.github\.com$", RegexOptions.IgnoreCase)] private static partial Regex REG_GITHUB_USER_EMAIL(); private readonly Lock _synclock = new(); @@ -40,6 +40,7 @@ public static AvatarManager Instance private List _avatars = new List(); private Cache _cache = new Cache(256); private HashSet _requesting = new HashSet(); + private Dictionary _requestNames = new Dictionary(); private HashSet _defaultAvatars = new HashSet(); public void Start() @@ -49,6 +50,7 @@ public void Start() Directory.CreateDirectory(_storePath); LoadDefaultAvatar("noreply@github.com", "github.png"); + LoadDefaultAvatar("github-actions[bot]@users.noreply.github.com", "github.png"); LoadDefaultAvatar("unrealbot@epicgames.com", "unreal.png"); Task.Run(async () => @@ -59,14 +61,20 @@ public void Start() while (true) { string email = null; + string name = null; lock (_synclock) { + _requestNames ??= new Dictionary(); + foreach (var one in _requesting) { email = one; break; } + + if (email != null) + _requestNames.TryGetValue(email, out name); } if (email == null) @@ -75,47 +83,57 @@ public void Start() continue; } - var md5 = GetEmailHash(email); - var matchGitHubUser = REG_GITHUB_USER_EMAIL().Match(email); - var url = $"https://www.gravatar.com/avatar/{md5}?d=404"; - if (matchGitHubUser.Success) - { - var githubUser = matchGitHubUser.Groups[2].Value; - if (githubUser.EndsWith("[bot]", StringComparison.OrdinalIgnoreCase)) - githubUser = githubUser.Substring(0, githubUser.Length - 5); - - url = $"https://avatars.githubusercontent.com/{githubUser}"; - } - - var localFile = Path.Combine(_storePath, md5); + var localFile = Path.Combine(_storePath, GetEmailHash(email)); Bitmap img = null; - try + foreach (var url in GetAvatarUrls(email, name)) { - var rsp = await client.GetAsync(url); - if (rsp.IsSuccessStatusCode) + for (var attempt = 0; attempt < 2 && img == null; attempt++) { - using (var stream = rsp.Content.ReadAsStream()) + try { - using (var writer = File.Create(localFile)) + using var rsp = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead); + if (!rsp.IsSuccessStatusCode) { - stream.CopyTo(writer); + if (attempt == 0 && IsRetryableStatus(rsp.StatusCode)) + { + await Task.Delay(150); + continue; + } + + break; + } + + using (var stream = await rsp.Content.ReadAsStreamAsync()) + { + using (var writer = File.Create(localFile)) + { + await stream.CopyToAsync(writer); + } + } + + using (var reader = File.OpenRead(localFile)) + { + img = Bitmap.DecodeToWidth(reader, 128); } - } - using (var reader = File.OpenRead(localFile)) + if (img == null && attempt == 0) + await Task.Delay(150); + } + catch { - img = Bitmap.DecodeToWidth(reader, 128); + if (attempt == 0) + await Task.Delay(150); } } - } - catch - { - // ignored + + if (img != null) + break; } lock (_synclock) { _requesting.Remove(email); + _requestNames.Remove(email); } Dispatcher.UIThread.Post(() => @@ -140,6 +158,11 @@ public void Unsubscribe(IAvatarHost host) } public Bitmap Request(string email, bool forceRefetch) + { + return Request(email, null, forceRefetch); + } + + public Bitmap Request(string email, string name, bool forceRefetch) { if (forceRefetch) { @@ -180,12 +203,64 @@ public Bitmap Request(string email, bool forceRefetch) lock (_synclock) { + _requestNames ??= new Dictionary(); _requesting.Add(email); + _requestNames[email] = name; } return null; } + private IEnumerable GetAvatarUrls(string email, string name) + { + var match = REG_GITHUB_USER_EMAIL().Match(email); + if (match.Success) + { + var userId = match.Groups[1].Value; + var githubUser = match.Groups[2].Value; + if (githubUser.EndsWith("[bot]", StringComparison.OrdinalIgnoreCase)) + githubUser = githubUser.Substring(0, githubUser.Length - 5); + + if (!string.IsNullOrEmpty(userId)) + yield return $"https://avatars.githubusercontent.com/u/{userId}?v=4"; + + if (!string.IsNullOrEmpty(githubUser)) + yield return $"https://avatars.githubusercontent.com/{Uri.EscapeDataString(githubUser)}?v=4"; + } + + if (!string.IsNullOrWhiteSpace(name) && IsGitHubLoginCandidate(name)) + { + yield return $"https://github.com/{Uri.EscapeDataString(name)}.png?size=128"; + yield return $"https://avatars.githubusercontent.com/{Uri.EscapeDataString(name)}?v=4"; + } + + yield return $"https://www.gravatar.com/avatar/{GetEmailHash(email)}?d=404"; + } + + private static bool IsGitHubLoginCandidate(string name) + { + if (name.Length is < 1 or > 39) + return false; + + if (name[0] == '-' || name[^1] == '-') + return false; + + foreach (var c in name) + { + if (!(char.IsAsciiLetterOrDigit(c) || c == '-')) + return false; + } + + return true; + } + + private static bool IsRetryableStatus(System.Net.HttpStatusCode statusCode) + { + return statusCode == System.Net.HttpStatusCode.RequestTimeout || + statusCode == (System.Net.HttpStatusCode)429 || + (int)statusCode >= 500; + } + public void SetFromLocal(string email, string file) { try @@ -224,7 +299,7 @@ private void LoadDefaultAvatar(string key, string img) private string GetEmailHash(string email) { var lowered = email.ToLower(CultureInfo.CurrentCulture).Trim(); - var hash = MD5.HashData(Encoding.Default.GetBytes(lowered)); + var hash = MD5.HashData(Encoding.UTF8.GetBytes(lowered)); return Convert.ToHexStringLower(hash); } @@ -263,6 +338,14 @@ public bool TryGet(string key, out Bitmap bitmap) { if (_key2img.TryGetValue(key, out var node)) { + if (node.Value.Image == null) + { + _imgList.Remove(node); + _key2img.Remove(key); + bitmap = null; + return false; + } + _imgList.Remove(node); _imgList.AddFirst(node); bitmap = node.Value.Image; @@ -275,6 +358,12 @@ public bool TryGet(string key, out Bitmap bitmap) public void AddOrUpdate(string key, Bitmap bitmap) { + if (bitmap == null) + { + Remove(key); + return; + } + if (_key2img.TryGetValue(key, out var node)) { _imgList.Remove(node); diff --git a/src/Views/Avatar.cs b/src/Views/Avatar.cs index 82fa0a8473..0e469f7116 100644 --- a/src/Views/Avatar.cs +++ b/src/Views/Avatar.cs @@ -177,7 +177,7 @@ protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs chang if (_user == null) return; - _img = Models.AvatarManager.Instance.Request(_user.Email, false); + _img = Models.AvatarManager.Instance.Request(_user.Email, _user.Name, false); InvalidateVisual(); } else if (change.Property == UseGitHubStyleAvatarProperty) @@ -202,7 +202,7 @@ private void OnContextRequested(object sender, ContextRequestedEventArgs e) refetch.Click += (_, ev) => { if (_user != null) - Models.AvatarManager.Instance.Request(_user.Email, true); + Models.AvatarManager.Instance.Request(_user.Email, _user.Name, true); ev.Handled = true; }; From a0540e3131288bd475f45322f272763184513d6b Mon Sep 17 00:00:00 2001 From: ZhonFortune Date: Sat, 28 Nov 2026 18:18:59 +0800 Subject: [PATCH 2/2] Fix: Prevent repeated avatar request failures and duplicate initialization - Add a guard flag so AvatarManager.Start only initializes once - Replace Thread.Sleep with await Task.Delay in the avatar request loop to avoid blocking the thread - Record a five minute retry cooldown for emails whose avatar request returned no image and skip them until it expires - Clear the retry cooldown entry when an avatar is loaded successfully, refreshed, or resolved - Delete the cached local avatar file when decoding fails instead of silently ignoring the error - Initialize the retry cooldown dictionary defensively inside the request lock --- src/Models/AvatarManager.cs | 41 +++++++++++++++++++++++++++++++++++-- 1 file changed, 39 insertions(+), 2 deletions(-) diff --git a/src/Models/AvatarManager.cs b/src/Models/AvatarManager.cs index f8d007f30c..f8dd8e7838 100644 --- a/src/Models/AvatarManager.cs +++ b/src/Models/AvatarManager.cs @@ -41,10 +41,20 @@ public static AvatarManager Instance private Cache _cache = new Cache(256); private HashSet _requesting = new HashSet(); private Dictionary _requestNames = new Dictionary(); + private Dictionary _retryAfter = new Dictionary(); private HashSet _defaultAvatars = new HashSet(); + private bool _started = false; public void Start() { + lock (_synclock) + { + if (_started) + return; + + _started = true; + } + _storePath = Path.Combine(Native.OS.BasicDirectories.CacheDir, "avatars"); if (!Directory.Exists(_storePath)) Directory.CreateDirectory(_storePath); @@ -79,7 +89,7 @@ public void Start() if (email == null) { - Thread.Sleep(100); + await Task.Delay(100); continue; } @@ -134,6 +144,11 @@ public void Start() { _requesting.Remove(email); _requestNames.Remove(email); + + if (img == null) + _retryAfter[email] = DateTimeOffset.UtcNow.AddMinutes(5); + else + _retryAfter.Remove(email); } Dispatcher.UIThread.Post(() => @@ -170,6 +185,10 @@ public Bitmap Request(string email, string name, bool forceRefetch) return null; _cache.Remove(email); + lock (_synclock) + { + _retryAfter.Remove(email); + } var localFile = Path.Combine(_storePath, GetEmailHash(email)); if (File.Exists(localFile)) @@ -196,7 +215,14 @@ public Bitmap Request(string email, string name, bool forceRefetch) } catch { - // ignore + try + { + File.Delete(localFile); + } + catch + { + // ignore + } } } } @@ -204,6 +230,16 @@ public Bitmap Request(string email, string name, bool forceRefetch) lock (_synclock) { _requestNames ??= new Dictionary(); + _retryAfter ??= new Dictionary(); + + if (_retryAfter.TryGetValue(email, out var retryAt)) + { + if (retryAt > DateTimeOffset.UtcNow) + return null; + + _retryAfter.Remove(email); + } + _requesting.Add(email); _requestNames[email] = name; } @@ -277,6 +313,7 @@ public void SetFromLocal(string email, string file) lock (_synclock) { _requesting.Remove(email); + _retryAfter.Remove(email); } var store = Path.Combine(_storePath, GetEmailHash(email));