프로젝트

일반

사용자정보

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

markus / KCOM / PageManager / PageStorage.cs @ master

이력 | 보기 | 이력해설 | 다운로드 (14.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
        bool IsBusy = false;
30

    
31
        BitmapFrame PageImage;
32

    
33
        public PageStorage(string BaseUri, string localStoragePath, string fileExt, int totalPages, int takeCount = 5)
34
        {
35
            try
36
            {
37
                backgroundWorker = new BackgroundWorker { WorkerSupportsCancellation = true, WorkerReportsProgress = true };
38
                
39
                backgroundWorker.DoWork += BackgroundWorker_DoWork;
40
                backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged;
41

    
42
                _fileExt = fileExt;
43
                _BaseUri = BaseUri;
44
                LocalStorage = localStoragePath;
45
                _TotalPages = totalPages;
46
                _TakeCount = takeCount;
47

    
48
                //_token = Authenticate();
49

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

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

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

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

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

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

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

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

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

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

    
112
        }
113

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

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

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

    
134
            return PageImage;
135
        }
136

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

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

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

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

    
152

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

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

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

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

    
181
            //}
182

    
183
        }
184

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

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

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

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

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

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

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

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

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

    
227

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

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

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

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

    
257
            return result;
258
        }
259

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

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

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

    
282
            return result;
283
        }
284

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

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

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

    
297
                    result = page.First();
298

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
380

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

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

    
393
                        client.DownloadProgressChanged += downloadProgressHandler;
394
                    }
395

    
396
                    client.DownloadFileCompleted += downloadFileCompleteHandler;
397

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

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

    
415
            return result;
416
        }
417

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

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

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

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

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