OSDN Git Service

C# 8.0 のnull許容参照型を有効化
[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 #nullable enable
23
24 using System;
25 using System.Collections.Generic;
26 using System.Linq;
27 using System.Text;
28 using System.Threading.Tasks;
29 using System.Net;
30 using System.Threading;
31 using System.Xml.Serialization;
32 using System.Net.Http;
33 using OpenTween.Connection;
34
35 namespace OpenTween
36 {
37     public class ImageCache : IDisposable
38     {
39         /// <summary>
40         /// キャッシュとして URL と取得した画像を対に保持する辞書
41         /// </summary>
42         internal LRUCacheDictionary<string, Task<MemoryImage>> innerDictionary;
43
44         /// <summary>
45         /// 非同期タスクをキャンセルするためのトークンのもと
46         /// </summary>
47         private CancellationTokenSource cancelTokenSource;
48
49         /// <summary>
50         /// innerDictionary の排他制御のためのロックオブジェクト
51         /// </summary>
52         private readonly object lockObject = new object();
53
54         /// <summary>
55         /// オブジェクトが破棄された否か
56         /// </summary>
57         private bool disposed = false;
58
59         public ImageCache()
60         {
61             this.innerDictionary = new LRUCacheDictionary<string, Task<MemoryImage>>(trimLimit: 300, autoTrimCount: 100);
62             this.innerDictionary.CacheRemoved += (s, e) => {
63                 // まだ参照されている場合もあるのでDisposeはファイナライザ任せ
64                 this.CacheRemoveCount++;
65             };
66
67             this.cancelTokenSource = new CancellationTokenSource();
68         }
69
70         /// <summary>
71         /// 保持しているキャッシュの件数
72         /// </summary>
73         public long CacheCount
74             => this.innerDictionary.Count;
75
76         /// <summary>
77         /// 破棄されたキャッシュの件数
78         /// </summary>
79         public int CacheRemoveCount { get; private set; }
80
81         /// <summary>
82         /// 指定された URL にある画像を非同期に取得するメソッド
83         /// </summary>
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)
88         {
89             var cancelToken = this.cancelTokenSource.Token;
90
91             return Task.Run(() =>
92             {
93                 lock (this.lockObject)
94                 {
95                     innerDictionary.TryGetValue(address, out var cachedImageTask);
96
97                     if (cachedImageTask != null)
98                     {
99                         if (force)
100                             this.innerDictionary.Remove(address);
101                         else
102                             return cachedImageTask;
103                     }
104
105                     cancelToken.ThrowIfCancellationRequested();
106
107                     var imageTask = this.FetchImageAsync(address, cancelToken);
108                     this.innerDictionary[address] = imageTask;
109
110                     return imageTask;
111                 }
112             }, cancelToken);
113         }
114
115         private async Task<MemoryImage> FetchImageAsync(string uri, CancellationToken cancelToken)
116         {
117             using var response = await Networking.Http.GetAsync(uri, cancelToken)
118                 .ConfigureAwait(false);
119
120             response.EnsureSuccessStatusCode();
121
122             using var imageStream = await response.Content.ReadAsStreamAsync()
123                 .ConfigureAwait(false);
124
125             return await MemoryImage.CopyFromStreamAsync(imageStream)
126                 .ConfigureAwait(false);
127         }
128
129         public MemoryImage? TryGetFromCache(string address)
130         {
131             lock (this.lockObject)
132             {
133                 if (!this.innerDictionary.TryGetValue(address, out var imageTask) ||
134                     imageTask.Status != TaskStatus.RanToCompletion)
135                     return null;
136
137                 return imageTask.Result;
138             }
139         }
140
141         public void CancelAsync()
142         {
143             lock (this.lockObject)
144             {
145                 var oldTokenSource = this.cancelTokenSource;
146                 this.cancelTokenSource = new CancellationTokenSource();
147
148                 oldTokenSource.Cancel();
149                 oldTokenSource.Dispose();
150             }
151         }
152
153         protected virtual void Dispose(bool disposing)
154         {
155             if (this.disposed) return;
156
157             if (disposing)
158             {
159                 this.CancelAsync();
160
161                 lock (this.lockObject)
162                 {
163                     foreach (var (_, task) in this.innerDictionary)
164                     {
165                         if (task.Status == TaskStatus.RanToCompletion)
166                             task.Result?.Dispose();
167                     }
168
169                     this.innerDictionary.Clear();
170                     this.cancelTokenSource.Dispose();
171                 }
172             }
173
174             this.disposed = true;
175         }
176
177         public void Dispose()
178         {
179             this.Dispose(true);
180             GC.SuppressFinalize(this);
181         }
182
183         ~ImageCache()
184             => this.Dispose(false);
185     }
186 }