markus / KCOM / PageManager / PageStorage.cs @ f5f788c2
이력 | 보기 | 이력해설 | 다운로드 (13.7 KB)
1 |
using System; |
---|---|
2 |
using System.Collections.Concurrent; |
3 |
using System.Collections.Generic; |
4 |
using System.ComponentModel; |
5 |
using System.Linq; |
6 |
using System.Net; |
7 |
using System.Text; |
8 |
using System.Threading.Tasks; |
9 |
using System.Windows.Media.Imaging; |
10 |
|
11 |
namespace KCOM.PageManager |
12 |
{ |
13 |
public class PageStorage |
14 |
{ |
15 |
private const int DEFUALT_TALK_PAGE_COUNT = 10; |
16 |
|
17 |
public event EventHandler<PageLoadCompletedEventArgs> PageLoadCompleted; |
18 |
|
19 |
List<int> WorkItems = new List<int>(); |
20 |
ConcurrentBag<PageItem> fileItems = new ConcurrentBag<PageItem>(); |
21 |
BackgroundWorker backgroundWorker; |
22 |
|
23 |
//List<PageItem> fileItems = new List<PageItem>(); |
24 |
public string LocalStorage; |
25 |
string _fileExt; |
26 |
string _BaseUri; |
27 |
int _TotalPages; |
28 |
int _TakeCount; |
29 |
|
30 |
bool IsBusy = false; |
31 |
|
32 |
BitmapFrame PageImage; |
33 |
|
34 |
public PageStorage(string BaseUri, string localStoragePath, string fileExt, int totalPages, int takeCount = 5) |
35 |
{ |
36 |
try |
37 |
{ |
38 |
backgroundWorker = new BackgroundWorker { WorkerSupportsCancellation = true, WorkerReportsProgress = true }; |
39 |
|
40 |
backgroundWorker.DoWork += BackgroundWorker_DoWork; |
41 |
backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged; |
42 |
|
43 |
_fileExt = fileExt; |
44 |
_BaseUri = BaseUri; |
45 |
LocalStorage = localStoragePath; |
46 |
_TotalPages = totalPages; |
47 |
_TakeCount = takeCount; |
48 |
|
49 |
System.IO.DirectoryInfo info = System.IO.Directory.CreateDirectory(LocalStorage); |
50 |
|
51 |
//backgroundWorker.RunWorkerAsync(new int[] { 1, 10 }); |
52 |
} |
53 |
catch (Exception ex) |
54 |
{ |
55 |
throw new Exception("PageStorage", ex); |
56 |
} |
57 |
} |
58 |
|
59 |
private void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) |
60 |
{ |
61 |
System.Diagnostics.Debug.WriteLine(_fileExt + ":" + e.ProgressPercentage.ToString() + "%"); |
62 |
} |
63 |
|
64 |
private async void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e) |
65 |
{ |
66 |
|
67 |
while (WorkItems.Count > 0) |
68 |
{ |
69 |
if (backgroundWorker.CancellationPending) |
70 |
{ |
71 |
e.Cancel = true; |
72 |
return; |
73 |
} |
74 |
|
75 |
if (!IsBusy) |
76 |
{ |
77 |
int item = -1; |
78 |
try |
79 |
{ |
80 |
|
81 |
if (WorkItems.TryFrist(true, out item)) |
82 |
{ |
83 |
var result = await DownloadPageAsync(item, null); |
84 |
|
85 |
if (!result.IsDownLoad) |
86 |
{ |
87 |
System.Threading.Thread.Sleep(100); |
88 |
} |
89 |
await Task.Delay(100); |
90 |
//System.Threading.Thread.Sleep(10); |
91 |
//backgroundWorker.ReportProgress(fileItems.Count / _TotalPages * 100); |
92 |
} |
93 |
} |
94 |
catch (Exception ex) |
95 |
{ |
96 |
System.Diagnostics.Debug.WriteLine(ex.ToString()); |
97 |
} |
98 |
} |
99 |
} |
100 |
} |
101 |
|
102 |
public void ResetImage() |
103 |
{ |
104 |
//if (PageImage != null) |
105 |
//{ |
106 |
// PageImage = null; |
107 |
//} |
108 |
|
109 |
//PageImage.CreateOptions = BitmapCreateOptions.IgnoreImageCache; |
110 |
|
111 |
} |
112 |
|
113 |
public async Task<BitmapFrame> GetPageImageAsync(System.Threading.CancellationToken cts, int PageNo, bool IsRestart = false) |
114 |
{ |
115 |
try |
116 |
{ |
117 |
|
118 |
var localUri = await GetPageUriAsync(cts, PageNo); |
119 |
|
120 |
if (localUri != null) // || !cts.IsCancellationRequested |
121 |
{ |
122 |
PageImage = BitmapFrame.Create(localUri, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); |
123 |
} |
124 |
} |
125 |
catch (Exception ex) |
126 |
{ |
127 |
PageImage = BitmapFrame.Create(new Uri(_BaseUri.Replace("{PageNo}", PageNo.ToString())), BitmapCreateOptions.None, BitmapCacheOption.OnLoad); |
128 |
} |
129 |
finally |
130 |
{ |
131 |
} |
132 |
|
133 |
return PageImage; |
134 |
} |
135 |
|
136 |
private void DownloadWorkAsync(int startPage, int TakeCount) |
137 |
{ |
138 |
|
139 |
lock (WorkItems) |
140 |
{ |
141 |
WorkItems.AddRange(Enumerable.Range(startPage, TakeCount)); |
142 |
} |
143 |
|
144 |
if (TakeCount == _TotalPages) |
145 |
{ |
146 |
_TakeCount = 0; |
147 |
} |
148 |
|
149 |
// var files = fileItems.Select(x => x.PageNo); |
150 |
|
151 |
|
152 |
//for (int i = startPage; i < TakeCount + 1; i++) |
153 |
//{ |
154 |
// if (i < _TotalPages && !WorkItems.Contains(i) && !files.Contains(i)) |
155 |
// { |
156 |
// WorkItems.Add(i); |
157 |
// // System.Threading.Thread.Sleep(1); |
158 |
// } |
159 |
// else if(i == _TotalPages) |
160 |
// { |
161 |
// _TakeCount = 0; |
162 |
// } |
163 |
//} |
164 |
|
165 |
if (!backgroundWorker.IsBusy && WorkItems.Count() > 0) |
166 |
{ |
167 |
backgroundWorker.RunWorkerAsync(); |
168 |
} |
169 |
|
170 |
//await Task.Delay(10);// System.Threading.Thread.Sleep(10); |
171 |
//while (WorkItems.Count > 0) |
172 |
//{ |
173 |
// int item = -1; |
174 |
|
175 |
// if (WorkItems.TryDequeue(out item)) |
176 |
// { |
177 |
// var result = await DownloadPageAsync(item, null); |
178 |
// } |
179 |
|
180 |
//} |
181 |
|
182 |
} |
183 |
|
184 |
/// <summary> |
185 |
/// |
186 |
/// </summary> |
187 |
/// <param name="cts"></param> |
188 |
/// <param name="PageNo"></param> |
189 |
/// <param name="IsClone"></param> |
190 |
/// <param name="IsRestart"></param> |
191 |
/// <returns></returns> |
192 |
public async Task<Uri> GetPageUriAsync(System.Threading.CancellationToken? cts, int PageNo, bool IsRestart = false) |
193 |
{ |
194 |
Uri result = null; |
195 |
|
196 |
try |
197 |
{ |
198 |
System.Diagnostics.Debug.WriteLine("GetPageAsync"); |
199 |
|
200 |
var pageItem = await DownloadPageAsync(PageNo, cts); |
201 |
|
202 |
if (pageItem != null) |
203 |
{ |
204 |
result = pageItem.LocalUri; |
205 |
|
206 |
//if(PageNo + _TakeCount < _TotalPages) |
207 |
//{ |
208 |
// int takecount = 5; |
209 |
|
210 |
// if (_TotalPages < PageNo + takecount) |
211 |
// { |
212 |
// takecount = takecount - (PageNo + takecount - _TotalPages) - 1; |
213 |
// } |
214 |
|
215 |
// DownloadWorkAsync(PageNo + 1, takecount); |
216 |
//} |
217 |
//int takecount = _TakeCount; |
218 |
|
219 |
//if (_TotalPages < PageNo + takecount) |
220 |
//{ |
221 |
// takecount = takecount - (PageNo + takecount - _TotalPages) - 1; |
222 |
//} |
223 |
|
224 |
//DownloadWorkAsync(PageNo + 1, takecount); |
225 |
|
226 |
|
227 |
//var takePageNoList = Enumerable.Range(PageNo + 1, _TakeCount); |
228 |
} |
229 |
else |
230 |
{ |
231 |
|
232 |
} |
233 |
} |
234 |
catch (Exception ex) |
235 |
{ |
236 |
//if (cts != null) |
237 |
//{ |
238 |
// if (cts.Value.IsCancellationRequested) |
239 |
// { |
240 |
// return result; |
241 |
// } |
242 |
//} |
243 |
|
244 |
//if (!IsRestart) |
245 |
//{ |
246 |
// await Task.Delay(100); |
247 |
|
248 |
// result = await GetPageUriAsync(cts, PageNo, true); |
249 |
//} |
250 |
//throw new Exception("GetPageAsync(string BasePageUri,int PageNo)", ex); |
251 |
} |
252 |
finally |
253 |
{ |
254 |
} |
255 |
|
256 |
return result; |
257 |
} |
258 |
|
259 |
public async Task<PageItem> DownloadPageAsync(int PageNo, System.Threading.CancellationToken? cts) |
260 |
{ |
261 |
PageItem result = new PageItem { PageNo = PageNo }; |
262 |
|
263 |
try |
264 |
{ |
265 |
var page = fileItems.Where(x => x.PageNo == PageNo).ToList(); |
266 |
|
267 |
if (page.Count > 0) |
268 |
{ |
269 |
System.Diagnostics.Debug.WriteLine("DownloadPageAsync fileItems"); |
270 |
|
271 |
result = page.First(); |
272 |
|
273 |
/// 파일 체크 후 없으면 다시 다운로드 |
274 |
if (!System.IO.File.Exists(result.LocalFilePath)) |
275 |
{ |
276 |
//fileItems.(result); |
277 |
|
278 |
result = await DownloadPageAsync(PageNo, cts); |
279 |
} |
280 |
} |
281 |
else |
282 |
{ |
283 |
if (!System.IO.Directory.Exists(LocalStorage)) |
284 |
{ |
285 |
System.IO.Directory.CreateDirectory(LocalStorage); |
286 |
System.Threading.Thread.Sleep(50); |
287 |
} |
288 |
|
289 |
System.Diagnostics.Debug.WriteLine("DownloadPageAsync down"); |
290 |
|
291 |
string downloadFilePath = System.IO.Path.Combine(LocalStorage, System.IO.Path.GetRandomFileName()); /// PageNo.ToString() + "." + _fileExt); |
292 |
|
293 |
Uri originalUri = new Uri(_BaseUri.Replace("{PageNo}", PageNo.ToString())); |
294 |
|
295 |
result = new PageItem |
296 |
{ |
297 |
PageNo = PageNo, |
298 |
OriginalUri = originalUri, |
299 |
LocalUri = new Uri(downloadFilePath, UriKind.Absolute), |
300 |
LocalFilePath = downloadFilePath |
301 |
}; |
302 |
|
303 |
System.Net.WebClient client = new System.Net.WebClient(); |
304 |
|
305 |
System.Diagnostics.Debug.WriteLine("download start " + downloadFilePath); |
306 |
client.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore); |
307 |
client.Headers.Add("Cache-Control", "no-cache"); |
308 |
client.UseDefaultCredentials = true; |
309 |
System.Net.IWebProxy webProxy = client.Proxy; |
310 |
|
311 |
if (webProxy != null) |
312 |
{ |
313 |
// Use the default credentials of the logged on user. |
314 |
webProxy.Credentials = System.Net.CredentialCache.DefaultCredentials; |
315 |
} |
316 |
|
317 |
AsyncCompletedEventHandler downloadFileCompleteHandler = (snd, evt) => |
318 |
{ |
319 |
if (!evt.Cancelled) |
320 |
{ |
321 |
result.IsDownLoad = true; |
322 |
|
323 |
if (fileItems.Where(x => x.PageNo == PageNo).Count() == 0) |
324 |
{ |
325 |
fileItems.Add(result); |
326 |
} |
327 |
System.Diagnostics.Debug.WriteLine("Download completed finish : " + downloadFilePath); |
328 |
PageLoadCompleted?.Invoke(this, new PageLoadCompletedEventArgs(result)); |
329 |
} |
330 |
else |
331 |
{ |
332 |
//client.DownloadFileCompleted -= downloadFileCompleteHandler; |
333 |
//client.DownloadProgressChanged -= downloadProgressHandler; |
334 |
|
335 |
client.Dispose(); |
336 |
client = null; |
337 |
System.IO.File.Delete(downloadFilePath); |
338 |
|
339 |
Console.WriteLine("Request cancelled!"); |
340 |
result = null; |
341 |
System.Diagnostics.Debug.WriteLine("Download completed cancelled : " + downloadFilePath); |
342 |
} |
343 |
|
344 |
#if !DOWNLOAD_TEST |
345 |
KCOM.Common.ViewerDataModel.Instance.PagImageCancelDispose(); |
346 |
#endif |
347 |
}; |
348 |
|
349 |
|
350 |
if (cts != null) |
351 |
{ |
352 |
DownloadProgressChangedEventHandler downloadProgressHandler = (snd, ect) => |
353 |
{ |
354 |
IsBusy = client.IsBusy; |
355 |
}; |
356 |
|
357 |
cts.Value.Register(() => |
358 |
{ |
359 |
client.CancelAsync(); |
360 |
}); |
361 |
|
362 |
client.DownloadProgressChanged += downloadProgressHandler; |
363 |
} |
364 |
|
365 |
client.DownloadFileCompleted += downloadFileCompleteHandler; |
366 |
|
367 |
await client.DownloadFileTaskAsync(originalUri, downloadFilePath); |
368 |
|
369 |
} |
370 |
} |
371 |
catch (WebException ex) when (ex.Status == WebExceptionStatus.RequestCanceled) |
372 |
{ |
373 |
Console.WriteLine("Cancelled"); |
374 |
} |
375 |
catch (Exception ex) |
376 |
{ |
377 |
throw new Exception("DownloadPageAsync : ", ex); |
378 |
} |
379 |
finally |
380 |
{ |
381 |
IsBusy = false; |
382 |
} |
383 |
|
384 |
return result; |
385 |
} |
386 |
|
387 |
private void downloadFileCompleteHandler(object sender, AsyncCompletedEventArgs e) |
388 |
{ |
389 |
throw new NotImplementedException(); |
390 |
} |
391 |
|
392 |
public void Clear() |
393 |
{ |
394 |
try |
395 |
{ |
396 |
ResetImage(); |
397 |
} |
398 |
catch (Exception ex) |
399 |
{ |
400 |
System.Diagnostics.Debug.WriteLine(ex.ToString()); |
401 |
} |
402 |
|
403 |
try |
404 |
{ |
405 |
backgroundWorker.CancelAsync(); |
406 |
backgroundWorker.Dispose(); |
407 |
|
408 |
/// downloadmanager에서 삭제함 |
409 |
//foreach (var item in fileItems) |
410 |
//{ |
411 |
// System.IO.File.Delete(item.LocalFilePath); |
412 |
//} |
413 |
|
414 |
//System.IO.Directory.Delete(LocalStorage, true); |
415 |
} |
416 |
catch (Exception ex) |
417 |
{ |
418 |
System.Diagnostics.Debug.WriteLine(ex.ToString()); |
419 |
} |
420 |
} |
421 |
} |
422 |
} |