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;
28 using System.Net.Http;
30 using System.Threading;
31 using System.Threading.Tasks;
32 using System.Xml.Serialization;
33 using OpenTween.Connection;
37 public class ImageCache : IDisposable
40 /// キャッシュとして URL と取得した画像を対に保持する辞書
42 internal LRUCacheDictionary<string, Task<MemoryImage>> InnerDictionary;
45 /// 非同期タスクをキャンセルするためのトークンのもと
47 private CancellationTokenSource cancelTokenSource;
52 private bool disposed = false;
56 this.InnerDictionary = new LRUCacheDictionary<string, Task<MemoryImage>>(trimLimit: 300, autoTrimCount: 100);
57 this.InnerDictionary.CacheRemoved += (s, e) =>
59 // まだ参照されている場合もあるのでDisposeはファイナライザ任せ
60 this.CacheRemoveCount++;
62 var task = e.Item.Value;
63 if (task.Status != TaskStatus.RanToCompletion || task.IsFaulted)
65 // Task の例外がハンドルされないまま破棄されると AggregateException が発生するため try-catch で処理する Task を挟む
66 static async Task HandleException<T>(Task<T> t)
70 _ = await t.ConfigureAwait(false);
76 _ = HandleException(task);
80 this.cancelTokenSource = new CancellationTokenSource();
86 public long CacheCount
87 => this.InnerDictionary.Count;
92 public int CacheRemoveCount { get; private set; }
95 /// 指定された URL にある画像を非同期に取得するメソッド
97 /// <param name="address">取得先の URL</param>
98 /// <param name="force">キャッシュを使用せずに取得する場合は true</param>
99 /// <returns>非同期に画像を取得するタスク</returns>
100 public Task<MemoryImage> DownloadImageAsync(string address, bool force = false)
102 var cancelToken = this.cancelTokenSource.Token;
104 this.InnerDictionary.TryGetValue(address, out var cachedImageTask);
106 if (cachedImageTask != null && !force)
107 return cachedImageTask;
109 cancelToken.ThrowIfCancellationRequested();
111 var imageTask = Task.Run(() => this.FetchImageAsync(address, cancelToken));
112 this.InnerDictionary[address] = imageTask;
117 private async Task<MemoryImage> FetchImageAsync(string uri, CancellationToken cancelToken)
119 using var response = await Networking.Http.GetAsync(uri, cancelToken)
120 .ConfigureAwait(false);
122 response.EnsureSuccessStatusCode();
124 using var imageStream = await response.Content.ReadAsStreamAsync()
125 .ConfigureAwait(false);
127 return await MemoryImage.CopyFromStreamAsync(imageStream)
128 .ConfigureAwait(false);
131 public MemoryImage? TryGetFromCache(string address)
133 if (!this.InnerDictionary.TryGetValue(address, out var imageTask) ||
134 imageTask.Status != TaskStatus.RanToCompletion)
137 return imageTask.Result;
140 public MemoryImage? TryGetLargerOrSameSizeFromCache(string normalUrl, string size)
142 var sizes = new[] { "mini", "normal", "bigger", "original" };
143 var minimumIndex = sizes.FindIndex(x => x == size);
145 foreach (var candidateSize in sizes.Skip(minimumIndex))
147 var imageUrl = Twitter.CreateProfileImageUrl(normalUrl, candidateSize);
148 var image = this.TryGetFromCache(imageUrl);
156 public void CancelAsync()
158 var oldTokenSource = this.cancelTokenSource;
159 this.cancelTokenSource = new CancellationTokenSource();
161 oldTokenSource.Cancel();
162 oldTokenSource.Dispose();
165 protected virtual void Dispose(bool disposing)
167 if (this.disposed) return;
173 foreach (var (_, task) in this.InnerDictionary)
175 if (task.Status == TaskStatus.RanToCompletion)
176 task.Result?.Dispose();
179 this.InnerDictionary.Clear();
180 this.cancelTokenSource.Dispose();
183 this.disposed = true;
186 public void Dispose()
189 GC.SuppressFinalize(this);
193 => this.Dispose(false);