OSDN Git Service

PostRequestクラスを追加
[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.Net;
28 using System.Net.Http;
29 using System.Text;
30 using System.Threading;
31 using System.Threading.Tasks;
32 using System.Xml.Serialization;
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         /// オブジェクトが破棄された否か
51         /// </summary>
52         private bool disposed = false;
53
54         public ImageCache()
55         {
56             this.InnerDictionary = new LRUCacheDictionary<string, Task<MemoryImage>>(trimLimit: 300, autoTrimCount: 100);
57             this.InnerDictionary.CacheRemoved += (s, e) =>
58             {
59                 // まだ参照されている場合もあるのでDisposeはファイナライザ任せ
60                 this.CacheRemoveCount++;
61
62                 var task = e.Item.Value;
63                 if (task.Status != TaskStatus.RanToCompletion || task.IsFaulted)
64                 {
65                     // Task の例外がハンドルされないまま破棄されると AggregateException が発生するため try-catch で処理する Task を挟む
66                     static async Task HandleException<T>(Task<T> t)
67                     {
68                         try
69                         {
70                             _ = await t.ConfigureAwait(false);
71                         }
72                         catch
73                         {
74                         }
75                     }
76                     _ = HandleException(task);
77                 }
78             };
79
80             this.cancelTokenSource = new CancellationTokenSource();
81         }
82
83         /// <summary>
84         /// 保持しているキャッシュの件数
85         /// </summary>
86         public long CacheCount
87             => this.InnerDictionary.Count;
88
89         /// <summary>
90         /// 破棄されたキャッシュの件数
91         /// </summary>
92         public int CacheRemoveCount { get; private set; }
93
94         /// <summary>
95         /// 指定された URL にある画像を非同期に取得するメソッド
96         /// </summary>
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)
101         {
102             var cancelToken = this.cancelTokenSource.Token;
103
104             this.InnerDictionary.TryGetValue(address, out var cachedImageTask);
105
106             if (cachedImageTask != null && !force)
107                 return cachedImageTask;
108
109             cancelToken.ThrowIfCancellationRequested();
110
111             var imageTask = Task.Run(() => this.FetchImageAsync(address, cancelToken));
112             this.InnerDictionary[address] = imageTask;
113
114             return imageTask;
115         }
116
117         private async Task<MemoryImage> FetchImageAsync(string uri, CancellationToken cancelToken)
118         {
119             using var response = await Networking.Http.GetAsync(uri, cancelToken)
120                 .ConfigureAwait(false);
121
122             response.EnsureSuccessStatusCode();
123
124             using var imageStream = await response.Content.ReadAsStreamAsync()
125                 .ConfigureAwait(false);
126
127             return await MemoryImage.CopyFromStreamAsync(imageStream)
128                 .ConfigureAwait(false);
129         }
130
131         public MemoryImage? TryGetFromCache(string address)
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         public MemoryImage? TryGetLargerOrSameSizeFromCache(string normalUrl, string size)
141         {
142             var sizes = new[] { "mini", "normal", "bigger", "original" };
143             var minimumIndex = sizes.FindIndex(x => x == size);
144
145             foreach (var candidateSize in sizes.Skip(minimumIndex))
146             {
147                 var imageUrl = Twitter.CreateProfileImageUrl(normalUrl, candidateSize);
148                 var image = this.TryGetFromCache(imageUrl);
149                 if (image != null)
150                     return image;
151             }
152
153             return null;
154         }
155
156         public void CancelAsync()
157         {
158             var oldTokenSource = this.cancelTokenSource;
159             this.cancelTokenSource = new CancellationTokenSource();
160
161             oldTokenSource.Cancel();
162             oldTokenSource.Dispose();
163         }
164
165         protected virtual void Dispose(bool disposing)
166         {
167             if (this.disposed) return;
168
169             if (disposing)
170             {
171                 this.CancelAsync();
172
173                 foreach (var (_, task) in this.InnerDictionary)
174                 {
175                     if (task.Status == TaskStatus.RanToCompletion)
176                         task.Result?.Dispose();
177                 }
178
179                 this.InnerDictionary.Clear();
180                 this.cancelTokenSource.Dispose();
181             }
182
183             this.disposed = true;
184         }
185
186         public void Dispose()
187         {
188             this.Dispose(true);
189             GC.SuppressFinalize(this);
190         }
191
192         ~ImageCache()
193             => this.Dispose(false);
194     }
195 }