OSDN Git Service

806e53f37a88eff0cb0ea7b8a0ac6640e55a2faa
[opentween/open-tween.git] / OpenTween / ImageCache.cs
1 // OpenTween - Client of Twitter
2 // Copyright (c) 2013 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
3 // All rights reserved.
4 //
5 // This file is part of OpenTween.
6 //
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)
10 // any later version.
11 //
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
15 // for more details.
16 //
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.
21
22 using System;
23 using System.Collections.Generic;
24 using System.Linq;
25 using System.Text;
26 using System.Threading.Tasks;
27 using System.Net;
28 using System.Threading;
29 using System.Xml.Serialization;
30 using System.Net.Http;
31
32 namespace OpenTween
33 {
34     public class ImageCache : IDisposable
35     {
36         /// <summary>
37         /// 画像の取得に使用する HttpClient インスタンス
38         /// </summary>
39         private readonly HttpClient http;
40
41         /// <summary>
42         /// キャッシュとして URL と取得した画像を対に保持する辞書
43         /// </summary>
44         internal LRUCacheDictionary<string, Task<MemoryImage>> innerDictionary;
45
46         /// <summary>
47         /// 非同期タスクをキャンセルするためのトークンのもと
48         /// </summary>
49         private CancellationTokenSource cancelTokenSource;
50
51         /// <summary>
52         /// innerDictionary の排他制御のためのロックオブジェクト
53         /// </summary>
54         private object lockObject = new object();
55
56         /// <summary>
57         /// オブジェクトが破棄された否か
58         /// </summary>
59         private bool disposed = false;
60
61         public ImageCache(HttpClient http)
62         {
63             this.http = http;
64
65             this.innerDictionary = new LRUCacheDictionary<string, Task<MemoryImage>>(trimLimit: 300, autoTrimCount: 100);
66             this.innerDictionary.CacheRemoved += (s, e) => {
67                 // まだ参照されている場合もあるのでDisposeはファイナライザ任せ
68                 this.CacheRemoveCount++;
69             };
70
71             this.cancelTokenSource = new CancellationTokenSource();
72         }
73
74         /// <summary>
75         /// 保持しているキャッシュの件数
76         /// </summary>
77         public long CacheCount
78         {
79             get { return this.innerDictionary.Count; }
80         }
81
82         /// <summary>
83         /// 破棄されたキャッシュの件数
84         /// </summary>
85         public int CacheRemoveCount { get; private set; }
86
87         /// <summary>
88         /// 指定された URL にある画像を非同期に取得するメソッド
89         /// </summary>
90         /// <param name="address">取得先の URL</param>
91         /// <param name="force">キャッシュを使用せずに取得する場合は true</param>
92         /// <returns>非同期に画像を取得するタスク</returns>
93         public Task<MemoryImage> DownloadImageAsync(string address, bool force = false)
94         {
95             var cancelToken = this.cancelTokenSource.Token;
96
97             return Task.Run(() =>
98             {
99                 Task<MemoryImage> cachedImageTask = null;
100                 lock (this.lockObject)
101                 {
102                     innerDictionary.TryGetValue(address, out cachedImageTask);
103
104                     if (cachedImageTask != null)
105                     {
106                         if (force)
107                         {
108                             this.innerDictionary.Remove(address);
109
110                             if (cachedImageTask.Status == TaskStatus.RanToCompletion)
111                                 cachedImageTask.Result.Dispose();
112
113                             cachedImageTask.Dispose();
114                             cachedImageTask = null;
115                         }
116                         else
117                             return cachedImageTask;
118                     }
119
120                     cancelToken.ThrowIfCancellationRequested();
121
122                     var imageTask = this.FetchImageAsync(address, cancelToken);
123                     this.innerDictionary[address] = imageTask;
124
125                     return imageTask;
126                 }
127             }, cancelToken);
128         }
129
130         private async Task<MemoryImage> FetchImageAsync(string uri, CancellationToken cancelToken)
131         {
132             using (var response = await this.http.GetAsync(uri, cancelToken).ConfigureAwait(false))
133             {
134                 var imageStream = await response.Content.ReadAsStreamAsync()
135                     .ConfigureAwait(false);
136
137                 return await MemoryImage.CopyFromStreamAsync(imageStream)
138                     .ConfigureAwait(false);
139             }
140         }
141
142         public MemoryImage TryGetFromCache(string address)
143         {
144             lock (this.lockObject)
145             {
146                 Task<MemoryImage> imageTask;
147                 if (!this.innerDictionary.TryGetValue(address, out imageTask) ||
148                     imageTask.Status != TaskStatus.RanToCompletion)
149                     return null;
150
151                 return imageTask.Result;
152             }
153         }
154
155         public void CancelAsync()
156         {
157             lock (this.lockObject)
158             {
159                 var oldTokenSource = this.cancelTokenSource;
160                 this.cancelTokenSource = new CancellationTokenSource();
161
162                 oldTokenSource.Cancel();
163                 oldTokenSource.Dispose();
164             }
165         }
166
167         protected virtual void Dispose(bool disposing)
168         {
169             if (this.disposed) return;
170
171             if (disposing)
172             {
173                 this.CancelAsync();
174
175                 lock (this.lockObject)
176                 {
177                     foreach (var item in this.innerDictionary)
178                     {
179                         var task = item.Value;
180                         if (task.Status == TaskStatus.RanToCompletion && task.Result != null)
181                             task.Result.Dispose();
182                     }
183
184                     this.innerDictionary.Clear();
185                     this.cancelTokenSource.Dispose();
186                 }
187             }
188
189             this.disposed = true;
190         }
191
192         public void Dispose()
193         {
194             this.Dispose(true);
195             GC.SuppressFinalize(this);
196         }
197
198         ~ImageCache()
199         {
200             this.Dispose(false);
201         }
202     }
203 }