프로젝트

일반

사용자정보

통계
| 브랜치(Branch): | 개정판:

markus / KCOM / PageManager / PageStorage.cs @ 66bd3240

이력 | 보기 | 이력해설 | 다운로드 (14.6 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
        string _token;
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
                //_token = Authenticate();
50

    
51
                System.IO.DirectoryInfo info = System.IO.Directory.CreateDirectory(LocalStorage);
52

    
53
                //backgroundWorker.RunWorkerAsync(new int[] { 1, 10 });
54
            }
55
            catch (Exception ex)
56
            {
57
                throw new Exception("PageStorage", ex);
58
            }
59
        }
60

    
61
        private void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
62
        {
63
            System.Diagnostics.Debug.WriteLine(_fileExt + ":" + e.ProgressPercentage.ToString() + "%");
64
        }
65

    
66
        private async void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
67
        {
68

    
69
            while (WorkItems.Count > 0)
70
            {
71
                if (backgroundWorker.CancellationPending)
72
                {
73
                    e.Cancel = true;
74
                    return;
75
                }
76

    
77
                if (!IsBusy)
78
                {
79
                    int item = -1;
80
                    try
81
                    {
82

    
83
                        if (WorkItems.TryFrist(true, out item))
84
                        { 
85
                            var result = await DownloadPageAsync(item, null);
86

    
87
                            if (!result.IsDownLoad)
88
                            {
89
                                System.Threading.Thread.Sleep(100);
90
                            }
91
                            await Task.Delay(100);
92
                            //System.Threading.Thread.Sleep(10);
93
                            //backgroundWorker.ReportProgress(fileItems.Count / _TotalPages * 100);
94
                        }
95
                    }
96
                    catch (Exception ex)
97
                    {
98
                        System.Diagnostics.Debug.WriteLine(ex.ToString());
99
                    }
100
                }
101
            }
102
        }
103

    
104
        public void ResetImage()
105
        {
106
            //if (PageImage != null)
107
            //{
108
            //    PageImage = null;
109
            //}
110

    
111
            //PageImage.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
112

    
113
        }
114

    
115
        public async Task<BitmapFrame> GetPageImageAsync(System.Threading.CancellationToken cts, int PageNo, bool IsRestart = false)
116
        {
117
            try
118
            {
119

    
120
                var localUri = await GetPageUriAsync(cts, PageNo);
121

    
122
                if (localUri != null) // || !cts.IsCancellationRequested
123
                {
124
                    PageImage = BitmapFrame.Create(localUri, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
125
                }
126
            }
127
            catch (Exception ex)
128
            {
129
                PageImage = BitmapFrame.Create(new Uri(_BaseUri.Replace("{PageNo}", PageNo.ToString())), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
130
            }
131
            finally
132
            {
133
            }
134

    
135
            return PageImage;
136
        }
137

    
138
        private void DownloadWorkAsync(int startPage, int TakeCount)
139
        {
140

    
141
            lock (WorkItems)
142
            {
143
                WorkItems.AddRange(Enumerable.Range(startPage, TakeCount));
144
            }
145

    
146
            if (TakeCount == _TotalPages)
147
            {
148
                _TakeCount = 0;
149
            }
150

    
151
            // var files = fileItems.Select(x => x.PageNo);
152

    
153

    
154
            //for (int i = startPage; i < TakeCount + 1; i++)
155
            //{
156
            //    if (i < _TotalPages && !WorkItems.Contains(i) && !files.Contains(i))
157
            //    {
158
            //        WorkItems.Add(i);
159
            //       // System.Threading.Thread.Sleep(1);
160
            //    }
161
            //    else if(i == _TotalPages)
162
            //    {
163
            //        _TakeCount = 0;
164
            //    }
165
            //}
166

    
167
            if (!backgroundWorker.IsBusy && WorkItems.Count() > 0)
168
            {
169
                backgroundWorker.RunWorkerAsync();
170
            }
171

    
172
            //await Task.Delay(10);//  System.Threading.Thread.Sleep(10);
173
            //while (WorkItems.Count > 0)
174
            //{
175
            //    int item = -1;
176

    
177
            //    if (WorkItems.TryDequeue(out item))
178
            //    {
179
            //        var result = await DownloadPageAsync(item, null);
180
            //    }
181

    
182
            //}
183

    
184
        }
185

    
186
        /// <summary>
187
        /// 
188
        /// </summary>
189
        /// <param name="cts"></param>
190
        /// <param name="PageNo"></param>
191
        /// <param name="IsClone"></param>
192
        /// <param name="IsRestart"></param>
193
        /// <returns></returns>
194
        public async Task<Uri> GetPageUriAsync(System.Threading.CancellationToken? cts, int PageNo, bool IsRestart = false)
195
        {
196
            Uri result = null;
197

    
198
            try
199
            {
200
                System.Diagnostics.Debug.WriteLine("GetPageAsync");
201

    
202
                var pageItem = await DownloadPageAsync(PageNo, cts);
203

    
204
                if (pageItem != null)
205
                {
206
                    result = pageItem.LocalUri;
207

    
208
                    //if(PageNo + _TakeCount < _TotalPages)
209
                    //{
210
                    //    int takecount = 5;
211

    
212
                    //    if (_TotalPages < PageNo + takecount)
213
                    //    {
214
                    //        takecount = takecount - (PageNo + takecount - _TotalPages) - 1;
215
                    //    }
216

    
217
                    //    DownloadWorkAsync(PageNo + 1, takecount);
218
                    //}
219
                    //int takecount = _TakeCount;
220

    
221
                    //if (_TotalPages < PageNo + takecount)
222
                    //{
223
                    //    takecount = takecount - (PageNo + takecount - _TotalPages) - 1;
224
                    //}
225

    
226
                    //DownloadWorkAsync(PageNo + 1, takecount);
227

    
228

    
229
                    //var takePageNoList = Enumerable.Range(PageNo + 1, _TakeCount);
230
                }
231
                else
232
                {
233

    
234
                }
235
            }
236
            catch (Exception ex)
237
            {
238
                //if (cts != null)
239
                //{
240
                //    if (cts.Value.IsCancellationRequested)
241
                //    {
242
                //        return result;
243
                //    }
244
                //}
245

    
246
                //if (!IsRestart)
247
                //{
248
                //    await Task.Delay(100);
249

    
250
                //    result = await GetPageUriAsync(cts, PageNo, true);
251
                //}
252
                //throw new Exception("GetPageAsync(string BasePageUri,int PageNo)", ex);
253
            }
254
            finally
255
            {
256
            }
257

    
258
            return result;
259
        }
260

    
261
        public string Authenticate()
262
        {
263
            string result = null;
264

    
265
            try
266
            {
267
                using (System.Net.WebClient client = new System.Net.WebClient())
268
                {
269
                    client.Headers.Add(HttpRequestHeader.Authorization, "!dsfadsfa@@~");
270
                    var response = client.DownloadString(App.BaseAddress + "/Authenticate");
271

    
272
                    if (response != null)
273
                    {
274
                        result = response;
275
                    }
276
                }
277
            }
278
            catch (Exception ex)
279
            {
280
                throw ex;
281
            }
282

    
283
            return result;
284
        }
285

    
286
        public async Task<PageItem> DownloadPageAsync(int PageNo, System.Threading.CancellationToken? cts)
287
        {
288
            PageItem result = new PageItem { PageNo = PageNo };
289

    
290
            try
291
            {
292
                var page = fileItems.Where(x => x.PageNo == PageNo).ToList();
293

    
294
                if (page.Count > 0)
295
                {
296
                    System.Diagnostics.Debug.WriteLine("DownloadPageAsync fileItems");
297

    
298
                    result = page.First();
299

    
300
                    /// 파일 체크 후 없으면 다시 다운로드
301
                    if (!System.IO.File.Exists(result.LocalFilePath))
302
                    {
303
                        //fileItems.(result);
304

    
305
                        result = await DownloadPageAsync(PageNo, cts);
306
                    }
307
                }
308
                else
309
                {
310
                    if (!System.IO.Directory.Exists(LocalStorage))
311
                    {
312
                        System.IO.Directory.CreateDirectory(LocalStorage);
313
                        System.Threading.Thread.Sleep(50);
314
                    }
315

    
316
                    System.Diagnostics.Debug.WriteLine("DownloadPageAsync down");
317

    
318
                    string downloadFilePath = System.IO.Path.Combine(LocalStorage, System.IO.Path.GetRandomFileName()); /// PageNo.ToString() + "." + _fileExt);
319

    
320
                    Uri originalUri = new Uri(_BaseUri.Replace("{PageNo}", PageNo.ToString()));
321

    
322
                    result = new PageItem
323
                    {
324
                        PageNo = PageNo,
325
                        OriginalUri = originalUri,
326
                        LocalUri = new Uri(downloadFilePath, UriKind.Absolute),
327
                        LocalFilePath = downloadFilePath
328
                    };
329

    
330
                    System.Net.WebClient client = new System.Net.WebClient();
331
                     
332
                    System.Diagnostics.Debug.WriteLine("download start " + downloadFilePath);
333
                    client.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
334
                    client.Headers.Add("Cache-Control", "no-cache");
335
                    //client.Headers.Add(HttpRequestHeader.Authorization, _token);
336

    
337
                    //client.ResponseHeaders.Add(HttpRequestHeader.Authorization,)
338
                    client.UseDefaultCredentials = true;
339
                    System.Net.IWebProxy webProxy = client.Proxy;
340

    
341
                    if (webProxy != null)
342
                    {
343
                        // Use the default credentials of the logged on user.
344
                        webProxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
345
                    }
346

    
347
                    AsyncCompletedEventHandler downloadFileCompleteHandler = (snd, evt) =>
348
                    {
349
                        if (!evt.Cancelled)
350
                        {
351
                            result.IsDownLoad = true;
352

    
353
                            if (fileItems.Where(x => x.PageNo == PageNo).Count() == 0)
354
                            {
355
                                fileItems.Add(result);
356
                            }
357
                            System.Diagnostics.Debug.WriteLine("Download completed finish : " + downloadFilePath);
358
                            PageLoadCompleted?.Invoke(this, new PageLoadCompletedEventArgs(result));
359
                        }
360
                        else
361
                        {
362
                            //client.DownloadFileCompleted -= downloadFileCompleteHandler;
363
                            //client.DownloadProgressChanged -= downloadProgressHandler;
364

    
365
                            client.Dispose();
366
                            client = null;
367
                            System.IO.File.Delete(downloadFilePath);
368

    
369
                            Console.WriteLine("Request cancelled!");
370
                            result = null;
371
                            System.Diagnostics.Debug.WriteLine("Download completed cancelled : " + downloadFilePath);
372
                        }
373

    
374
#if !DOWNLOAD_TEST
375
                        KCOM.Common.ViewerDataModel.Instance.PagImageCancelDispose();
376
#endif
377
                    };
378

    
379

    
380
                    if (cts != null)
381
                    {
382
                        DownloadProgressChangedEventHandler downloadProgressHandler = (snd, ect) =>
383
                        {
384
                              IsBusy = client.IsBusy;
385
                        };
386

    
387
                        cts.Value.Register(() =>
388
                        {
389
                            client.CancelAsync();
390
                        });
391

    
392
                        client.DownloadProgressChanged += downloadProgressHandler;
393
                    }
394

    
395
                    client.DownloadFileCompleted += downloadFileCompleteHandler;
396

    
397
                    await client.DownloadFileTaskAsync(originalUri, downloadFilePath); 
398

    
399
                }
400
            }
401
            catch (WebException ex) when (ex.Status == WebExceptionStatus.RequestCanceled)
402
            {
403
                Console.WriteLine("Cancelled");
404
            }
405
            catch (Exception ex)
406
            {
407
                throw new Exception("DownloadPageAsync : ", ex);
408
            }
409
            finally
410
            {
411
                IsBusy = false;
412
            }
413

    
414
            return result;
415
        }
416

    
417
        private void downloadFileCompleteHandler(object sender, AsyncCompletedEventArgs e)
418
        {
419
            throw new NotImplementedException();
420
        }
421

    
422
        public void Clear()
423
        {
424
            try
425
            {
426
                ResetImage();
427
            }
428
            catch (Exception ex)
429
            {
430
                System.Diagnostics.Debug.WriteLine(ex.ToString());
431
            }
432

    
433
            try
434
            {
435
                backgroundWorker.CancelAsync();
436
                backgroundWorker.Dispose();
437

    
438
                /// downloadmanager에서 삭제함
439
                //foreach (var item in fileItems)
440
                //{
441
                //    System.IO.File.Delete(item.LocalFilePath);
442
                //}
443

    
444
                //System.IO.Directory.Delete(LocalStorage, true);
445
            }
446
            catch (Exception ex)
447
            {
448
                System.Diagnostics.Debug.WriteLine(ex.ToString());
449
            }
450
        }
451
    }
452
}
클립보드 이미지 추가 (최대 크기: 500 MB)