프로젝트

일반

사용자정보

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

markus / KCOM / PageManager / PageStorage.cs @ 03960fa5

이력 | 보기 | 이력해설 | 다운로드 (11.3 KB)

1 d7e20d2d taeseongkim
using System;
2 2007ecaa taeseongkim
using System.Collections.Concurrent;
3 d7e20d2d taeseongkim
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 2007ecaa taeseongkim
16
        public event EventHandler<PageLoadCompletedEventArgs> PageLoadCompleted;
17
18
        List<int> WorkItems = new List<int>();
19
        ConcurrentBag<PageItem> fileItems = new ConcurrentBag<PageItem>();
20 d7e20d2d taeseongkim
        BackgroundWorker backgroundWorker;
21 2007ecaa taeseongkim
22
        //List<PageItem> fileItems = new List<PageItem>();
23 9d5b4bc2 taeseongkim
        public string LocalStorage;
24 54a28343 taeseongkim
        string _fileExt;
25 d7e20d2d taeseongkim
        string _BaseUri;
26
        int _TotalPages;
27 54a28343 taeseongkim
        int _TakeCount;
28 d7e20d2d taeseongkim
29 2007ecaa taeseongkim
        bool IsDownload = false;
30 d7e20d2d taeseongkim
31
        BitmapFrame PageImage;
32
33 2007ecaa taeseongkim
        public PageStorage(string BaseUri, string localStoragePath, string fileExt, int totalPages, int takeCount = 5)
34 d7e20d2d taeseongkim
        {
35
            try
36
            {
37 2007ecaa taeseongkim
                backgroundWorker = new BackgroundWorker { WorkerSupportsCancellation = true, WorkerReportsProgress = true };
38 d7e20d2d taeseongkim
                backgroundWorker.DoWork += BackgroundWorker_DoWork;
39 2007ecaa taeseongkim
                backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged;
40 54a28343 taeseongkim
                _fileExt = fileExt;
41 d7e20d2d taeseongkim
                _BaseUri = BaseUri;
42 9d5b4bc2 taeseongkim
                LocalStorage = localStoragePath;
43 d7e20d2d taeseongkim
                _TotalPages = totalPages;
44 54a28343 taeseongkim
                _TakeCount = takeCount;
45 d7e20d2d taeseongkim
46 9d5b4bc2 taeseongkim
                System.IO.Directory.CreateDirectory(LocalStorage);
47 d7e20d2d taeseongkim
48
                //backgroundWorker.RunWorkerAsync(new int[] { 1, 10 });
49
            }
50
            catch (Exception ex)
51
            {
52
                throw new Exception("PageStorage", ex);
53
            }
54
        }
55
56 2007ecaa taeseongkim
        private void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
57 d7e20d2d taeseongkim
        {
58 2007ecaa taeseongkim
            System.Diagnostics.Debug.WriteLine(_fileExt + ":" + e.ProgressPercentage.ToString() + "%");
59
        }
60 d7e20d2d taeseongkim
61 2007ecaa taeseongkim
        private async void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
62
        {
63 d7e20d2d taeseongkim
64 2007ecaa taeseongkim
            while (WorkItems.Count > 0)
65
            {
66
                if (!IsDownload)
67 d7e20d2d taeseongkim
                {
68 2007ecaa taeseongkim
                    int item = -1;
69
                    try
70
                    {
71 d7e20d2d taeseongkim
72 2007ecaa taeseongkim
                        if (WorkItems.TryFrist(true, out item))
73
                        {
74
                            var result = await DownloadPageAsync(item, null);
75 d7e20d2d taeseongkim
76 2007ecaa taeseongkim
                            if (!result.IsDownLoad)
77
                            {
78
                                System.Threading.Thread.Sleep(100);
79
                            }
80
                            await Task.Delay(100);
81
                            //System.Threading.Thread.Sleep(10);
82
                            //backgroundWorker.ReportProgress(fileItems.Count / _TotalPages * 100);
83
                        }
84
                    }
85
                    catch (Exception ex)
86
                    {
87
                        System.Diagnostics.Debug.WriteLine(ex.ToString());
88
                    }
89 d7e20d2d taeseongkim
                }
90
            }
91
        }
92
93
        public void ResetImage()
94
        {
95
            //if (PageImage != null)
96
            //{
97
            //    PageImage = null;
98
            //}
99
100
            //PageImage.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
101
102
        }
103
104 2007ecaa taeseongkim
        public async Task<BitmapFrame> GetPageImageAsync(System.Threading.CancellationToken cts, int PageNo, bool IsRestart = false)
105 d7e20d2d taeseongkim
        {
106
            try
107
            {
108 54a28343 taeseongkim
109 2007ecaa taeseongkim
                var localUri = await GetPageUriAsync(null, PageNo);
110 54a28343 taeseongkim
111 24c5e56c taeseongkim
                if (localUri != null || !cts.IsCancellationRequested)
112
                {
113
                    PageImage = BitmapFrame.Create(localUri, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
114
                }
115 54a28343 taeseongkim
            }
116
            catch (Exception ex)
117
            {
118 04d21859 taeseongkim
                PageImage = BitmapFrame.Create(new Uri(_BaseUri.Replace("{PageNo}", PageNo.ToString())), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
119 54a28343 taeseongkim
            }
120
            finally
121
            {
122
            }
123
124
            return PageImage;
125
        }
126
127 2007ecaa taeseongkim
        private void DownloadWorkAsync(int startPage, int TakeCount)
128
        {
129
130
            lock (WorkItems)
131
            {
132
                WorkItems.AddRange(Enumerable.Range(startPage, TakeCount));
133
            }
134
135
            if (TakeCount == _TotalPages)
136
            {
137
                _TakeCount = 0;
138
            }
139
140
            // var files = fileItems.Select(x => x.PageNo);
141
142
143
            //for (int i = startPage; i < TakeCount + 1; i++)
144
            //{
145
            //    if (i < _TotalPages && !WorkItems.Contains(i) && !files.Contains(i))
146
            //    {
147
            //        WorkItems.Add(i);
148
            //       // System.Threading.Thread.Sleep(1);
149
            //    }
150
            //    else if(i == _TotalPages)
151
            //    {
152
            //        _TakeCount = 0;
153
            //    }
154
            //}
155
156
            if (!backgroundWorker.IsBusy && WorkItems.Count() > 0)
157
            {
158
                backgroundWorker.RunWorkerAsync();
159
            }
160
161
            //await Task.Delay(10);//  System.Threading.Thread.Sleep(10);
162
            //while (WorkItems.Count > 0)
163
            //{
164
            //    int item = -1;
165
166
            //    if (WorkItems.TryDequeue(out item))
167
            //    {
168
            //        var result = await DownloadPageAsync(item, null);
169
            //    }
170
171
            //}
172
173
        }
174
175
        public async Task<Uri> GetPageUriAsync(System.Threading.CancellationToken? cts, int PageNo, bool IsRestart = false)
176 54a28343 taeseongkim
        {
177
            Uri result = null;
178
179
            try
180
            {
181 d7e20d2d taeseongkim
                System.Diagnostics.Debug.WriteLine("GetPageAsync");
182 54a28343 taeseongkim
183 2007ecaa taeseongkim
                var pageItem = await DownloadPageAsync(PageNo, cts);
184
185
                if (pageItem != null && 0 < _TakeCount && PageNo + 1 < _TotalPages)
186 d7e20d2d taeseongkim
                {
187 2007ecaa taeseongkim
                    int takecount = _TakeCount;
188 d7e20d2d taeseongkim
189 2007ecaa taeseongkim
                    if (_TotalPages < PageNo + 1 + takecount)
190 d7e20d2d taeseongkim
                    {
191 2007ecaa taeseongkim
                        takecount = takecount - (PageNo + 1 + takecount - _TotalPages) - 1;
192
                    }
193 d7e20d2d taeseongkim
194 2007ecaa taeseongkim
                    DownloadWorkAsync(PageNo + 1, takecount);
195
                    //var takePageNoList = Enumerable.Range(PageNo + 1, _TakeCount);
196 d7e20d2d taeseongkim
197 54a28343 taeseongkim
198 e13b43de taeseongkim
199 54a28343 taeseongkim
                }
200 d7e20d2d taeseongkim
201 54a28343 taeseongkim
                result = pageItem.LocalUri;
202 d7e20d2d taeseongkim
            }
203 54a28343 taeseongkim
            catch (Exception ex)
204 d7e20d2d taeseongkim
            {
205 2007ecaa taeseongkim
                if (cts != null)
206
                {
207
                    if (cts.Value.IsCancellationRequested)
208
                    {
209
                        return result;
210
                    }
211
                }
212
213
                if (!IsRestart)
214 96bc6e8e taeseongkim
                {
215
                    await Task.Delay(100);
216 54a28343 taeseongkim
217 2007ecaa taeseongkim
                    result = await GetPageUriAsync(cts, PageNo, true);
218 96bc6e8e taeseongkim
                }
219 a7372e37 taeseongkim
                //throw new Exception("GetPageAsync(string BasePageUri,int PageNo)", ex);
220 d7e20d2d taeseongkim
            }
221
            finally
222
            {
223
            }
224
225 54a28343 taeseongkim
            return result;
226 d7e20d2d taeseongkim
        }
227
228 2007ecaa taeseongkim
        public async Task<PageItem> DownloadPageAsync(int PageNo, System.Threading.CancellationToken? cts)
229 d7e20d2d taeseongkim
        {
230
            PageItem result = new PageItem { PageNo = PageNo };
231
232
            try
233
            {
234 2007ecaa taeseongkim
                var page = fileItems.Where(x => x.PageNo == PageNo).ToList();
235 d7e20d2d taeseongkim
236 2007ecaa taeseongkim
                if (page.Count > 0)
237 d7e20d2d taeseongkim
                {
238
                    System.Diagnostics.Debug.WriteLine("DownloadPageAsync fileItems");
239
240 2007ecaa taeseongkim
                    result = page.First();
241 d7e20d2d taeseongkim
242
                    /// 파일 체크 후 없으면 다시 다운로드
243 2007ecaa taeseongkim
                    if (!System.IO.File.Exists(result.LocalFilePath))
244 d7e20d2d taeseongkim
                    {
245 2007ecaa taeseongkim
                        //fileItems.(result);
246 d7e20d2d taeseongkim
247 2007ecaa taeseongkim
                        result = await DownloadPageAsync(PageNo, cts);
248 d7e20d2d taeseongkim
                    }
249
                }
250
                else
251
                {
252 2007ecaa taeseongkim
253 d7e20d2d taeseongkim
                    System.Diagnostics.Debug.WriteLine("DownloadPageAsync down");
254
255 9d5b4bc2 taeseongkim
                    string downloadFilePath = System.IO.Path.Combine(LocalStorage, PageNo.ToString() + "." + _fileExt);
256 d7e20d2d taeseongkim
257 96bc6e8e taeseongkim
                    Uri originalUri = new Uri(_BaseUri.Replace("{PageNo}", PageNo.ToString()));
258
259 2007ecaa taeseongkim
                    result = new PageItem
260
                    {
261
                        PageNo = PageNo,
262
                        OriginalUri = originalUri,
263
                        LocalUri = new Uri(downloadFilePath, UriKind.Absolute),
264
                        LocalFilePath = downloadFilePath
265
                    };
266
267
                    if (fileItems.Where(x => x.PageNo == PageNo).Count() == 0)
268
                    {
269
                        fileItems.Add(result);
270
                    }
271 d7e20d2d taeseongkim
272 448c5399 taeseongkim
                    using (System.Net.WebClient client = new System.Net.WebClient())
273 24c5e56c taeseongkim
                    {
274 448c5399 taeseongkim
                        client.UseDefaultCredentials = true;
275
                        System.Net.IWebProxy webProxy = client.Proxy;
276 d7e20d2d taeseongkim
277 448c5399 taeseongkim
                        if (webProxy != null)
278 d97dbc7f taeseongkim
                        {
279 448c5399 taeseongkim
                            // Use the default credentials of the logged on user.
280
                            webProxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
281 d97dbc7f taeseongkim
                        }
282
283 448c5399 taeseongkim
                        //client.DownloadFileCompleted += (snd, evt) =>
284
                        //{
285 24c5e56c taeseongkim
286 d7e20d2d taeseongkim
287 448c5399 taeseongkim
                        //    //(snd as System.Net.WebClient).Dispose();
288
                        //};
289 d7e20d2d taeseongkim
290 2007ecaa taeseongkim
                        if (cts != null)
291
                        {
292 24c5e56c taeseongkim
                            client.DownloadProgressChanged += (snd, ect) =>
293
                            {
294 2007ecaa taeseongkim
                                IsDownload = client.IsBusy;
295
296
                                if (cts.Value.IsCancellationRequested)
297 24c5e56c taeseongkim
                                {
298
                                    client.CancelAsync();
299
                                }
300
                            };
301 2007ecaa taeseongkim
                        }
302
303
                        client.DownloadFileCompleted += (snd, evt) =>
304
                        {
305
                            result.IsDownLoad = true;
306
                            System.Diagnostics.Debug.WriteLine("Download : " + downloadFilePath);
307 24c5e56c taeseongkim
308 2007ecaa taeseongkim
                            PageLoadCompleted?.Invoke(this, new PageLoadCompletedEventArgs(result));
309
                        };
310 72424099 taeseongkim
311 448c5399 taeseongkim
                        await client.DownloadFileTaskAsync(originalUri, downloadFilePath);
312
313
                    }
314 2007ecaa taeseongkim
315
                    //}
316 54a28343 taeseongkim
                    //System.Diagnostics.Debug.WriteLine("Download : " + result.LocalFilePath);
317 d7e20d2d taeseongkim
                }
318
            }
319
            catch (Exception ex)
320
            {
321
                throw new Exception("DownloadPageAsync : ", ex);
322
            }
323
            finally
324
            {
325 2007ecaa taeseongkim
                IsDownload = false;
326 d7e20d2d taeseongkim
            }
327
328
            return result;
329
        }
330
331
        public void Clear()
332
        {
333
            try
334
            {
335
                ResetImage();
336
            }
337
            catch (Exception ex)
338
            {
339
                System.Diagnostics.Debug.WriteLine(ex.ToString());
340
            }
341
342
            try
343
            {
344
                backgroundWorker.CancelAsync();
345
                backgroundWorker.Dispose();
346
347 03960fa5 taeseongkim
                /// downloadmanager에서 삭제함
348
                //foreach (var item in fileItems)
349
                //{
350
                //    System.IO.File.Delete(item.LocalFilePath);
351
                //}
352 d7e20d2d taeseongkim
353 03960fa5 taeseongkim
                //System.IO.Directory.Delete(LocalStorage, true);
354 d7e20d2d taeseongkim
            }
355
            catch (Exception ex)
356
            {
357
                System.Diagnostics.Debug.WriteLine(ex.ToString());
358
            }
359
        }
360
    }
361
}
클립보드 이미지 추가 (최대 크기: 500 MB)