Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
186 changes: 156 additions & 30 deletions src/Models/AvatarManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,23 +32,35 @@ 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();
private string _storePath;
private List<IAvatarHost> _avatars = new List<IAvatarHost>();
private Cache _cache = new Cache(256);
private HashSet<string> _requesting = new HashSet<string>();
private Dictionary<string, string> _requestNames = new Dictionary<string, string>();
private Dictionary<string, DateTimeOffset> _retryAfter = new Dictionary<string, DateTimeOffset>();
private HashSet<string> _defaultAvatars = new HashSet<string>();
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);

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 () =>
Expand All @@ -59,63 +71,84 @@ public void Start()
while (true)
{
string email = null;
string name = null;

lock (_synclock)
{
_requestNames ??= new Dictionary<string, string>();

foreach (var one in _requesting)
{
email = one;
break;
}

if (email != null)
_requestNames.TryGetValue(email, out name);
}

if (email == null)
{
Thread.Sleep(100);
await Task.Delay(100);
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 reader = File.OpenRead(localFile))
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);
}

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);

if (img == null)
_retryAfter[email] = DateTimeOffset.UtcNow.AddMinutes(5);
else
_retryAfter.Remove(email);
}

Dispatcher.UIThread.Post(() =>
Expand All @@ -140,13 +173,22 @@ 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)
{
if (_defaultAvatars.Contains(email))
return null;

_cache.Remove(email);
lock (_synclock)
{
_retryAfter.Remove(email);
}

var localFile = Path.Combine(_storePath, GetEmailHash(email));
if (File.Exists(localFile))
Expand All @@ -173,19 +215,88 @@ public Bitmap Request(string email, bool forceRefetch)
}
catch
{
// ignore
try
{
File.Delete(localFile);
}
catch
{
// ignore
}
}
}
}

lock (_synclock)
{
_requestNames ??= new Dictionary<string, string>();
_retryAfter ??= new Dictionary<string, DateTimeOffset>();

if (_retryAfter.TryGetValue(email, out var retryAt))
{
if (retryAt > DateTimeOffset.UtcNow)
return null;

_retryAfter.Remove(email);
}

_requesting.Add(email);
_requestNames[email] = name;
}

return null;
}

private IEnumerable<string> 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
Expand All @@ -202,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));
Expand All @@ -224,7 +336,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);
}

Expand Down Expand Up @@ -263,6 +375,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;
Expand All @@ -275,6 +395,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);
Expand Down
4 changes: 2 additions & 2 deletions src/Views/Avatar.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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;
};
Expand Down