1 // OpenTween - Client of Twitter
2 // Copyright (c) 2013 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
3 // All rights reserved.
5 // This file is part of OpenTween.
7 // This program is free software; you can redistribute it and/or modify it
8 // under the terms of the GNU General Public License as published by the Free
9 // Software Foundation; either version 3 of the License, or (at your option)
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 // You should have received a copy of the GNU General Public License along
18 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
19 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
20 // Boston, MA 02110-1301, USA.
25 using System.Collections.Generic;
29 using System.Net.Http;
31 using System.Threading;
32 using System.Threading.Tasks;
33 using System.Xml.Serialization;
34 using OpenTween.Connection;
38 public class ImageCache : IDisposable
41 /// キャッシュとして URL と取得した画像を対に保持する辞書
43 internal LRUCacheDictionary<string, Task<MemoryImage>> InnerDictionary;
46 /// 非同期タスクをキャンセルするためのトークンのもと
48 private CancellationTokenSource cancelTokenSource;
53 private bool disposed = false;
57 this.InnerDictionary = new LRUCacheDictionary<string, Task<MemoryImage>>(trimLimit: 300, autoTrimCount: 100);
58 this.InnerDictionary.CacheRemoved += (s, e) =>
60 this.CacheRemoveCount++;
62 // まだ参照されている場合もあるのでDisposeはファイナライザ任せ
63 var task = e.Item.Value;
64 _ = AsyncExceptionBoundary.IgnoreException(task);
67 this.cancelTokenSource = new CancellationTokenSource();
73 public long CacheCount
74 => this.InnerDictionary.Count;
79 public int CacheRemoveCount { get; private set; }
82 /// 指定された URL にある画像を非同期に取得するメソッド
84 /// <param name="address">取得先の URL</param>
85 /// <param name="force">キャッシュを使用せずに取得する場合は true</param>
86 /// <returns>非同期に画像を取得するタスク</returns>
87 public Task<MemoryImage> DownloadImageAsync(string address, bool force = false)
89 var cancelToken = this.cancelTokenSource.Token;
91 this.InnerDictionary.TryGetValue(address, out var cachedImageTask);
93 if (cachedImageTask != null && !force)
94 return cachedImageTask;
96 cancelToken.ThrowIfCancellationRequested();
98 var imageTask = Task.Run(() => this.FetchImageAsync(address, cancelToken));
99 this.InnerDictionary[address] = imageTask;
104 private async Task<MemoryImage> FetchImageAsync(string uri, CancellationToken cancelToken)
108 using var response = await Networking.Http.GetAsync(uri, cancelToken)
109 .ConfigureAwait(false);
111 response.EnsureSuccessStatusCode();
113 using var imageStream = await response.Content.ReadAsStreamAsync()
114 .ConfigureAwait(false);
116 return await MemoryImage.CopyFromStreamAsync(imageStream)
117 .ConfigureAwait(false);
120 when (ex is HttpRequestException or OperationCanceledException or InvalidImageException)
122 return this.CreateBlankImage();
126 private MemoryImage CreateBlankImage()
128 using var bitmap = new Bitmap(1, 1);
129 return MemoryImage.CopyFromImage(bitmap);
132 public MemoryImage? TryGetFromCache(string address)
134 if (!this.InnerDictionary.TryGetValue(address, out var imageTask) ||
135 imageTask.Status != TaskStatus.RanToCompletion)
138 return imageTask.Result;
141 public MemoryImage? TryGetLargerOrSameSizeFromCache(string normalUrl, string size)
143 var sizes = new[] { "mini", "normal", "bigger", "original" };
144 var minimumIndex = sizes.FindIndex(x => x == size);
146 foreach (var candidateSize in sizes.Skip(minimumIndex))
148 var imageUrl = Twitter.CreateProfileImageUrl(normalUrl, candidateSize);
149 var image = this.TryGetFromCache(imageUrl);
157 public void CancelAsync()
159 var oldTokenSource = this.cancelTokenSource;
160 this.cancelTokenSource = new CancellationTokenSource();
162 oldTokenSource.Cancel();
163 oldTokenSource.Dispose();
166 protected virtual void Dispose(bool disposing)
168 if (this.disposed) return;
174 foreach (var (_, task) in this.InnerDictionary)
176 if (task.Status == TaskStatus.RanToCompletion)
177 task.Result?.Dispose();
180 this.InnerDictionary.Clear();
181 this.cancelTokenSource.Dispose();
184 this.disposed = true;
187 public void Dispose()
190 GC.SuppressFinalize(this);
194 => this.Dispose(false);