프로젝트

일반

사용자정보

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

markus / KCOM / PageManager / PageStorage.cs @ 6a19b48d

이력 | 보기 | 이력해설 | 다운로드 (13.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.Text;
7
using System.Threading.Tasks;
8
using System.Windows.Media.Imaging;
9

    
10
namespace KCOM.PageManager
11
{
12
    public class PageStorage
13
    {
14
        private const int DEFUALT_TALK_PAGE_COUNT = 10;
15

    
16
        public event EventHandler<PageLoadCompletedEventArgs> PageLoadCompleted;
17

    
18
        List<int> WorkItems = new List<int>();
19
        ConcurrentBag<PageItem> fileItems = new ConcurrentBag<PageItem>();
20
        BackgroundWorker backgroundWorker;
21

    
22
        //List<PageItem> fileItems = new List<PageItem>();
23
        public string LocalStorage;
24
        string _fileExt;
25
        string _BaseUri;
26
        int _TotalPages;
27
        int _TakeCount;
28

    
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
                backgroundWorker.DoWork += BackgroundWorker_DoWork;
39
                backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged;
40
                
41
                _fileExt = fileExt;
42
                _BaseUri = BaseUri;
43
                LocalStorage = localStoragePath;
44
                _TotalPages = totalPages;
45
                _TakeCount = takeCount;
46

    
47
                System.IO.DirectoryInfo info = System.IO.Directory.CreateDirectory(LocalStorage);
48

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

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

    
62
        private async void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
63
        {
64

    
65
            while (WorkItems.Count > 0)
66
            {
67
                if (!IsBusy)
68
                {
69
                    int item = -1;
70
                    try
71
                    {
72

    
73
                        if (WorkItems.TryFrist(true, out item))
74
                        {
75
                            var result = await DownloadPageAsync(item, null);
76

    
77
                            if (!result.IsDownLoad)
78
                            {
79
                                System.Threading.Thread.Sleep(100);
80
                            }
81
                            await Task.Delay(100);
82
                            //System.Threading.Thread.Sleep(10);
83
                            //backgroundWorker.ReportProgress(fileItems.Count / _TotalPages * 100);
84
                        }
85
                    }
86
                    catch (Exception ex)
87
                    {
88
                        System.Diagnostics.Debug.WriteLine(ex.ToString());
89
                    }
90
                }
91
            }
92
        }
93

    
94
        public void ResetImage()
95
        {
96
            //if (PageImage != null)
97
            //{
98
            //    PageImage = null;
99
            //}
100

    
101
            //PageImage.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
102

    
103
        }
104

    
105
        public async Task<BitmapFrame> GetPageImageAsync(System.Threading.CancellationToken cts, int PageNo, bool IsRestart = false)
106
        {
107
            try
108
            {
109

    
110
                var localUri = await GetPageUriAsync(cts, PageNo);
111

    
112
                if (localUri != null) // || !cts.IsCancellationRequested
113
                {
114
                    PageImage = BitmapFrame.Create(localUri, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
115
                }
116
            }
117
            catch (Exception ex)
118
            {
119
                PageImage = BitmapFrame.Create(new Uri(_BaseUri.Replace("{PageNo}", PageNo.ToString())), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
120
            }
121
            finally
122
            {
123
            }
124

    
125
            return PageImage;
126
        }
127

    
128
        private void DownloadWorkAsync(int startPage, int TakeCount)
129
        {
130

    
131
            lock (WorkItems)
132
            {
133
                WorkItems.AddRange(Enumerable.Range(startPage, TakeCount));
134
            }
135

    
136
            if (TakeCount == _TotalPages)
137
            {
138
                _TakeCount = 0;
139
            }
140

    
141
            // var files = fileItems.Select(x => x.PageNo);
142

    
143

    
144
            //for (int i = startPage; i < TakeCount + 1; i++)
145
            //{
146
            //    if (i < _TotalPages && !WorkItems.Contains(i) && !files.Contains(i))
147
            //    {
148
            //        WorkItems.Add(i);
149
            //       // System.Threading.Thread.Sleep(1);
150
            //    }
151
            //    else if(i == _TotalPages)
152
            //    {
153
            //        _TakeCount = 0;
154
            //    }
155
            //}
156

    
157
            if (!backgroundWorker.IsBusy && WorkItems.Count() > 0)
158
            {
159
                backgroundWorker.RunWorkerAsync();
160
            }
161

    
162
            //await Task.Delay(10);//  System.Threading.Thread.Sleep(10);
163
            //while (WorkItems.Count > 0)
164
            //{
165
            //    int item = -1;
166

    
167
            //    if (WorkItems.TryDequeue(out item))
168
            //    {
169
            //        var result = await DownloadPageAsync(item, null);
170
            //    }
171

    
172
            //}
173

    
174
        }
175

    
176
        /// <summary>
177
        /// 
178
        /// </summary>
179
        /// <param name="cts"></param>
180
        /// <param name="PageNo"></param>
181
        /// <param name="IsClone"></param>
182
        /// <param name="IsRestart"></param>
183
        /// <returns></returns>
184
        public async Task<Uri> GetPageUriAsync(System.Threading.CancellationToken? cts, int PageNo, bool IsRestart = false)
185
        {
186
            Uri result = null;
187

    
188
            try
189
            {
190
                System.Diagnostics.Debug.WriteLine("GetPageAsync");
191

    
192
                var pageItem = await DownloadPageAsync(PageNo, cts);
193

    
194
                if (pageItem != null)
195
                {
196
                    result = pageItem.LocalUri;
197

    
198
                    if(PageNo + _TakeCount < _TotalPages)
199
                    {
200
                        int takecount = 5;
201

    
202
                        if (_TotalPages < PageNo + takecount)
203
                        {
204
                            takecount = takecount - (PageNo + takecount - _TotalPages) - 1;
205
                        }
206

    
207
                        DownloadWorkAsync(PageNo + 1, takecount);
208
                    }
209
                    //int takecount = _TakeCount;
210

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

    
216
                    //DownloadWorkAsync(PageNo + 1, takecount);
217

    
218

    
219
                    //var takePageNoList = Enumerable.Range(PageNo + 1, _TakeCount);
220
                }
221
                else
222
                {
223

    
224
                }
225
            }
226
            catch (Exception ex)
227
            {
228
                //if (cts != null)
229
                //{
230
                //    if (cts.Value.IsCancellationRequested)
231
                //    {
232
                //        return result;
233
                //    }
234
                //}
235

    
236
                //if (!IsRestart)
237
                //{
238
                //    await Task.Delay(100);
239

    
240
                //    result = await GetPageUriAsync(cts, PageNo, true);
241
                //}
242
                //throw new Exception("GetPageAsync(string BasePageUri,int PageNo)", ex);
243
            }
244
            finally
245
            {
246
            }
247

    
248
            return result;
249
        }
250

    
251
        public async Task<PageItem> DownloadPageAsync(int PageNo, System.Threading.CancellationToken? cts)
252
        {
253
            PageItem result = new PageItem { PageNo = PageNo };
254

    
255
            try
256
            {
257
                var page = fileItems.Where(x => x.PageNo == PageNo).ToList();
258

    
259
                if (page.Count > 0)
260
                {
261
                    System.Diagnostics.Debug.WriteLine("DownloadPageAsync fileItems");
262

    
263
                    result = page.First();
264

    
265
                    /// 파일 체크 후 없으면 다시 다운로드
266
                    if (!System.IO.File.Exists(result.LocalFilePath))
267
                    {
268
                        //fileItems.(result);
269

    
270
                        result = await DownloadPageAsync(PageNo, cts);
271
                    }
272
                }
273
                else
274
                {
275
                    
276

    
277
                    if (!System.IO.Directory.Exists(LocalStorage))
278
                    {
279
                        System.IO.Directory.CreateDirectory(LocalStorage);
280
                        System.Threading.Thread.Sleep(50);
281
                    }
282

    
283
                    System.Diagnostics.Debug.WriteLine("DownloadPageAsync down");
284

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

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

    
289
                    result = new PageItem
290
                    {
291
                        PageNo = PageNo,
292
                        OriginalUri = originalUri,
293
                        LocalUri = new Uri(downloadFilePath, UriKind.Absolute),
294
                        LocalFilePath = downloadFilePath
295
                    };
296

    
297
                    using (System.Net.WebClient client = new System.Net.WebClient())
298
                    {
299
                        System.Diagnostics.Debug.WriteLine("download start " + downloadFilePath);
300
                        client.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
301
                        client.Headers.Add("Cache-Control", "no-cache");
302
                        client.UseDefaultCredentials = true;
303
                        System.Net.IWebProxy webProxy = client.Proxy;
304

    
305
                        if (webProxy != null)
306
                        {
307
                            // Use the default credentials of the logged on user.
308
                            webProxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
309
                        }
310

    
311
                        //client.DownloadFileCompleted += (snd, evt) =>
312
                        //{
313

    
314

    
315
                        //    //(snd as System.Net.WebClient).Dispose();
316
                        //};
317

    
318
                        if (cts != null)
319
                        {
320
                            cts.Value.Register(() =>
321
                            {
322
                                client.CancelAsync();
323
                                Console.WriteLine("Request cancelled!");
324
                                result = null;
325
                            });
326

    
327
                            client.DownloadProgressChanged += (snd, ect) =>
328
                            {
329
                                IsBusy = client.IsBusy;
330

    
331
                                //if(cts.Value.IsCancellationRequested)
332
                                //{
333
                                //    System.Diagnostics.Debug.WriteLine("download cancel " + downloadFilePath);
334
                                //    client.CancelAsync();
335
                                //    client.Dispose();
336
                                //}
337
                            };
338
                        }
339

    
340
                        client.DownloadFileCompleted += (snd, evt) =>
341
                        {
342
                            if (!evt.Cancelled)
343
                            {
344
                                result.IsDownLoad = true;
345

    
346
                                if (fileItems.Where(x => x.PageNo == PageNo).Count() == 0)
347
                                {
348
                                    fileItems.Add(result);
349
                                }
350

    
351
                                System.Diagnostics.Debug.WriteLine("Download completed finish : " + downloadFilePath);
352

    
353
                                PageLoadCompleted?.Invoke(this, new PageLoadCompletedEventArgs(result));
354

    
355
                                client.Dispose();
356
                            }
357
                            else
358
                            {
359
                                System.Diagnostics.Debug.WriteLine("Download completed cancelled : " + downloadFilePath);
360

    
361
                                client.Dispose();
362
                                System.IO.File.Delete(downloadFilePath);
363
                            }
364
                        };
365

    
366
                        await client.DownloadFileTaskAsync(originalUri, downloadFilePath);
367

    
368
                    }
369

    
370
                    //}
371
                    //System.Diagnostics.Debug.WriteLine("Download : " + result.LocalFilePath);
372
                }
373
            }
374
            catch (Exception ex)
375
            {
376
                throw new Exception("DownloadPageAsync : ", ex);
377
            }
378
            finally
379
            {
380
                IsBusy = false;
381
            }
382

    
383
            return result;
384
        }
385

    
386
        public void Clear()
387
        {
388
            try
389
            {
390
                ResetImage();
391
            }
392
            catch (Exception ex)
393
            {
394
                System.Diagnostics.Debug.WriteLine(ex.ToString());
395
            }
396

    
397
            try
398
            {
399
                backgroundWorker.CancelAsync();
400
                backgroundWorker.Dispose();
401

    
402
                /// downloadmanager에서 삭제함
403
                //foreach (var item in fileItems)
404
                //{
405
                //    System.IO.File.Delete(item.LocalFilePath);
406
                //}
407

    
408
                //System.IO.Directory.Delete(LocalStorage, true);
409
            }
410
            catch (Exception ex)
411
            {
412
                System.Diagnostics.Debug.WriteLine(ex.ToString());
413
            }
414
        }
415
    }
416
}
클립보드 이미지 추가 (최대 크기: 500 MB)