OSDN Git Service

graphqlエンドポイントを使用した関連発言表示に対応
[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                 this.CacheRemoveCount++;
60
61                 // まだ参照されている場合もあるのでDisposeはファイナライザ任せ
62                 var task = e.Item.Value;
63                 _ = AsyncExceptionBoundary.IgnoreException(task);
64             };
65
66             this.cancelTokenSource = new CancellationTokenSource();
67         }
68
69         /// <summary>
70         /// 保持しているキャッシュの件数
71         /// </summary>
72         public long CacheCount
73             => this.InnerDictionary.Count;
74
75         /// <summary>
76         /// 破棄されたキャッシュの件数
77         /// </summary>
78         public int CacheRemoveCount { get; private set; }
79
80         /// <summary>
81         /// 指定された URL にある画像を非同期に取得するメソッド
82         /// </summary>
83         /// <param name="address">取得先の URL</param>
84         /// <param name="force">キャッシュを使用せずに取得する場合は true</param>
85         /// <returns>非同期に画像を取得するタスク</returns>
86         public Task<MemoryImage> DownloadImageAsync(string address, bool force = false)
87         {
88             var cancelToken = this.cancelTokenSource.Token;
89
90             this.InnerDictionary.TryGetValue(address, out var cachedImageTask);
91
92             if (cachedImageTask != null && !force)
93                 return cachedImageTask;
94
95             cancelToken.ThrowIfCancellationRequested();
96
97             var imageTask = Task.Run(() => this.FetchImageAsync(address, cancelToken));
98             this.InnerDictionary[address] = imageTask;
99
100             return imageTask;
101         }
102
103         private async Task<MemoryImage> FetchImageAsync(string uri, CancellationToken cancelToken)
104         {
105             using var response = await Networking.Http.GetAsync(uri, cancelToken)
106                 .ConfigureAwait(false);
107
108             response.EnsureSuccessStatusCode();
109
110             using var imageStream = await response.Content.ReadAsStreamAsync()
111                 .ConfigureAwait(false);
112
113             return await MemoryImage.CopyFromStreamAsync(imageStream)
114                 .ConfigureAwait(false);
115         }
116
117         public MemoryImage? TryGetFromCache(string address)
118         {
119             if (!this.InnerDictionary.TryGetValue(address, out var imageTask) ||
120                 imageTask.Status != TaskStatus.RanToCompletion)
121                 return null;
122
123             return imageTask.Result;
124         }
125
126         public MemoryImage? TryGetLargerOrSameSizeFromCache(string normalUrl, string size)
127         {
128             var sizes = new[] { "mini", "normal", "bigger", "original" };
129             var minimumIndex = sizes.FindIndex(x => x == size);
130
131             foreach (var candidateSize in sizes.Skip(minimumIndex))
132             {
133                 var imageUrl = Twitter.CreateProfileImageUrl(normalUrl, candidateSize);
134                 var image = this.TryGetFromCache(imageUrl);
135                 if (image != null)
136                     return image;
137             }
138
139             return null;
140         }
141
142         public void CancelAsync()
143         {
144             var oldTokenSource = this.cancelTokenSource;
145             this.cancelTokenSource = new CancellationTokenSource();
146
147             oldTokenSource.Cancel();
148             oldTokenSource.Dispose();
149         }
150
151         protected virtual void Dispose(bool disposing)
152         {
153             if (this.disposed) return;
154
155             if (disposing)
156             {
157                 this.CancelAsync();
158
159                 foreach (var (_, task) in this.InnerDictionary)
160                 {
161                     if (task.Status == TaskStatus.RanToCompletion)
162                         task.Result?.Dispose();
163                 }
164
165                 this.InnerDictionary.Clear();
166                 this.cancelTokenSource.Dispose();
167             }
168
169             this.disposed = true;
170         }
171
172         public void Dispose()
173         {
174             this.Dispose(true);
175             GC.SuppressFinalize(this);
176         }
177
178         ~ImageCache()
179             => this.Dispose(false);
180     }
181 }