public virtual void SetUp() { _inner = Substitute.For <IAvatarProvider>(); _inner.GetAvatarAsync(_email1, _size).Returns(Task.FromResult(_img1)); _inner.GetAvatarAsync(_email2, _size).Returns(Task.FromResult(_img2)); _inner.GetAvatarAsync(_email3, _size).Returns(Task.FromResult(_img3)); _inner.GetAvatarAsync(_email4, _size).Returns(Task.FromResult(_img4)); }
protected async Task MissAsync(string email, string name, Image expected = null) { _inner.ClearReceivedCalls(); var actual = await _cache.GetAvatarAsync(email, name, _size); _ = _inner.Received(1).GetAvatarAsync(email, name, _size); if (expected is not null) { Assert.AreSame(expected, actual); } }
private async Task UpdateAvatarAsync() { await this.SwitchToMainThreadAsync(); // resize our control (I'm not using AutoSize for a reason) var size = new Size(AppSettings.AuthorImageSizeInCommitInfo, AppSettings.AuthorImageSizeInCommitInfo); DpiUtil.Scale(ref size); Size = _avatarImage.Size = size; var email = Email; if (!AppSettings.ShowAuthorAvatarInCommitInfo || string.IsNullOrWhiteSpace(email)) { RefreshImage(Images.User80); return; } var token = _cancellationTokenSequence.Next(); var image = await _avatarProvider.GetAvatarAsync(email, AuthorName, Math.Max(size.Width, size.Height)); if (!token.IsCancellationRequested) { await this.SwitchToMainThreadAsync(); RefreshImage(image); } }
public async Task <Image> GetAvatarAsync([NotNull] string email, string name, int imageSize) { if (imageSize < 1) { imageSize = _defaultSize; } if (imageSize > _upperSizeLimit) { imageSize = _upperSizeLimit; } try { var image = await _avatarProvider.GetAvatarAsync(email, name, imageSize); if (image != null) { return(image); } } catch (Exception ex) { // Something went wrong. Log, ignore and proceed with fallback. Trace.WriteLine(ex.Message); } return(_safetyNetFallback.Value); }
/// <inheritdoc /> public async Task <Image> GetAvatarAsync(string email, string name, int imageSize) { var cacheDir = AppSettings.AvatarImageCachePath; var path = Path.Combine(cacheDir, $"{email}.{imageSize}px.png"); var image = ReadImage() ?? await _inner.GetAvatarAsync(email, name, imageSize); if (image is not null) { WriteImage(); } return(image); void WriteImage() { if (!_fileSystem.Directory.Exists(cacheDir)) { _fileSystem.Directory.CreateDirectory(cacheDir); } try { using (var output = _fileSystem.File.OpenWrite(path)) { image.Save(output, ImageFormat.Png); } } catch { // do nothing } } Image ReadImage() { if (!HasExpired()) { try { using (var stream = _fileSystem.File.OpenRead(path)) { return(Image.FromStream(stream)); } } catch { // ignore } } TryDelete(); return(null); bool HasExpired() { var info = _fileSystem.FileInfo.FromFileName(path); var cacheDays = AppSettings.AvatarImageCacheDays; if (cacheDays < 1) { cacheDays = DefaultCacheDays; } return(!info.Exists || info.LastWriteTime < DateTime.Now.AddDays(-cacheDays)); } void TryDelete() { try { _fileSystem.File.Delete(path); } catch { // ignore } } } }