프로젝트

일반

사용자정보

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

markus / KCOM / PageManager / PageStorage.cs @ 24c5e56c

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

1 d7e20d2d taeseongkim
using System;
2
using System.Collections.Generic;
3
using System.ComponentModel;
4
using System.Linq;
5
using System.Text;
6
using System.Threading.Tasks;
7
using System.Windows.Media.Imaging;
8
9
namespace KCOM.PageManager
10
{
11
    public class PageStorage
12
    {
13
        private const int DEFUALT_TALK_PAGE_COUNT = 10;
14 54a28343 taeseongkim
        bool IsRunWork = false;
15 d7e20d2d taeseongkim
        BackgroundWorker backgroundWorker;
16
        List<PageItem> fileItems = new List<PageItem>();
17
        string _localStorage;
18 54a28343 taeseongkim
        string _fileExt;
19 d7e20d2d taeseongkim
        string _BaseUri;
20
        int _TotalPages;
21 54a28343 taeseongkim
        int _TakeCount;
22 d7e20d2d taeseongkim
23
24
        BitmapFrame PageImage;
25
26 54a28343 taeseongkim
        public PageStorage(string BaseUri, string localStoragePath,string fileExt,int totalPages,int takeCount = 5)
27 d7e20d2d taeseongkim
        {
28
            try
29
            {
30
                backgroundWorker = new BackgroundWorker {WorkerSupportsCancellation = true };
31
                backgroundWorker.DoWork += BackgroundWorker_DoWork;
32
33 54a28343 taeseongkim
                _fileExt = fileExt;
34 d7e20d2d taeseongkim
                _BaseUri = BaseUri;
35
                _localStorage = localStoragePath;
36
                _TotalPages = totalPages;
37 54a28343 taeseongkim
                _TakeCount = takeCount;
38 d7e20d2d taeseongkim
39
                System.IO.Directory.CreateDirectory(_localStorage);
40
41
                //backgroundWorker.RunWorkerAsync(new int[] { 1, 10 });
42
            }
43
            catch (Exception ex)
44
            {
45
                throw new Exception("PageStorage", ex);
46
            }
47
        }
48
49
        private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
50
        {
51
            int StartPageNo = -1;
52
            int TalkCount = -1;
53
54
            if (e.Argument != null)
55
            {
56
57
                var values = (e.Argument as int[]);
58
59
                if (values.Count() == 2)
60
                {
61
62
                    StartPageNo = values[0];
63
                    TalkCount = values[1];
64
65 24c5e56c taeseongkim
                    DownloadPagesAsync( StartPageNo, TalkCount);
66 d7e20d2d taeseongkim
                }
67
            }
68
        }
69
70
        public void ResetImage()
71
        {
72
            //if (PageImage != null)
73
            //{
74
            //    PageImage = null;
75
            //}
76
77
            //PageImage.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
78
79
        }
80
81 24c5e56c taeseongkim
        public async Task<BitmapFrame> GetPageImageAsync(System.Threading.CancellationToken cts,int PageNo,bool IsRestart =false)
82 d7e20d2d taeseongkim
        {
83
            try
84
            {
85 54a28343 taeseongkim
86 24c5e56c taeseongkim
                var localUri = await GetPageUriAsync(cts,PageNo);
87 54a28343 taeseongkim
88 24c5e56c taeseongkim
                if (localUri != null || !cts.IsCancellationRequested)
89
                {
90
                    PageImage = BitmapFrame.Create(localUri, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
91
                }
92 54a28343 taeseongkim
            }
93
            catch (Exception ex)
94
            {
95
                throw new Exception("GetPageImageAsync(int PageNo,bool IsRestart =false)", ex);
96
            }
97
            finally
98
            {
99
            }
100
101
            return PageImage;
102
        }
103
104 24c5e56c taeseongkim
        public async Task<Uri> GetPageUriAsync( System.Threading.CancellationToken cts, int PageNo, bool IsRestart = false)
105 54a28343 taeseongkim
        {
106
            Uri result = null;
107
108
            try
109
            {
110 d7e20d2d taeseongkim
                System.Diagnostics.Debug.WriteLine("GetPageAsync");
111 54a28343 taeseongkim
112 24c5e56c taeseongkim
                var pageItem = await DownloadPageAsync(PageNo,cts);
113 d7e20d2d taeseongkim
                
114 54a28343 taeseongkim
                if (!IsRunWork && pageItem != null)
115 d7e20d2d taeseongkim
                {
116 54a28343 taeseongkim
                    var takePageNoList = Enumerable.Range(PageNo + 1, _TakeCount);
117 d7e20d2d taeseongkim
118 54a28343 taeseongkim
                    if (takePageNoList.Any(x => fileItems.Count(y => y.PageNo == x) == 0))
119 d7e20d2d taeseongkim
                    {
120 54a28343 taeseongkim
                        while (backgroundWorker.IsBusy)
121
                        {
122
                            if (backgroundWorker.IsBusy)
123
                            {
124
                                backgroundWorker.CancelAsync();
125
                            }
126 d7e20d2d taeseongkim
127 54a28343 taeseongkim
                            await Task.Delay(100);
128
                        }
129 d7e20d2d taeseongkim
130 54a28343 taeseongkim
                        backgroundWorker.RunWorkerAsync(new int[] { PageNo + 1, _TakeCount });
131
132
                        if (_TotalPages == _TakeCount)
133
                        {
134
                            IsRunWork = true;
135
                        }
136
                    }
137
                }
138 d7e20d2d taeseongkim
139 54a28343 taeseongkim
                result = pageItem.LocalUri;
140 d7e20d2d taeseongkim
            }
141 54a28343 taeseongkim
            catch (Exception ex)
142 d7e20d2d taeseongkim
            {
143 24c5e56c taeseongkim
                if (!IsRestart || !cts.IsCancellationRequested)
144 96bc6e8e taeseongkim
                {
145
                    await Task.Delay(100);
146 54a28343 taeseongkim
147 24c5e56c taeseongkim
                    result = await GetPageUriAsync(cts,PageNo, true);
148 96bc6e8e taeseongkim
                }
149 a7372e37 taeseongkim
                //throw new Exception("GetPageAsync(string BasePageUri,int PageNo)", ex);
150 d7e20d2d taeseongkim
            }
151
            finally
152
            {
153
            }
154
155 54a28343 taeseongkim
            return result;
156 d7e20d2d taeseongkim
        }
157
158 448c5399 taeseongkim
        public async void DownloadPagesAsync(int StartPageNo, int TalkCount = 5)
159 d7e20d2d taeseongkim
        {
160 e8557bd7 taeseongkim
            try
161 d7e20d2d taeseongkim
            {
162 e8557bd7 taeseongkim
                if (StartPageNo + TalkCount > _TotalPages)
163
                {
164
                    TalkCount = _TotalPages - StartPageNo;
165
                }
166 d7e20d2d taeseongkim
167 e8557bd7 taeseongkim
                if (TalkCount > 0)
168 d7e20d2d taeseongkim
                {
169 e8557bd7 taeseongkim
                    for (int i = StartPageNo; i < StartPageNo + TalkCount; i++)
170 d7e20d2d taeseongkim
                    {
171 e8557bd7 taeseongkim
                        try
172
                        {
173 24c5e56c taeseongkim
                            await DownloadPageAsync(i,null);
174 448c5399 taeseongkim
                            System.Threading.Thread.Sleep(200);
175 e8557bd7 taeseongkim
                        }
176
                        catch (Exception ex)
177
                        {
178
                            System.Diagnostics.Debug.WriteLine("DownloadPagesAsync err", ex);
179
                        }
180 72424099 taeseongkim
                        finally
181
                        {
182
                        }
183
184 d7e20d2d taeseongkim
                    }
185
                }
186
            }
187 e8557bd7 taeseongkim
            catch (Exception ex)
188
            {
189
                throw new Exception("DownloadPagesAsync : ", ex);
190
            }
191
            finally
192
            {
193 54a28343 taeseongkim
                GC.Collect(2);
194
                GC.Collect(2);
195 e8557bd7 taeseongkim
            }
196 d7e20d2d taeseongkim
        }
197
198 24c5e56c taeseongkim
        public async Task<PageItem> DownloadPageAsync(int PageNo,System.Threading.CancellationToken? cts)
199 d7e20d2d taeseongkim
        {
200
            PageItem result = new PageItem { PageNo = PageNo };
201
202
            try
203
            {
204
                var page = fileItems.Where(x => x.PageNo == PageNo);
205
206
                if (page.Count() > 0)
207
                {
208
                    System.Diagnostics.Debug.WriteLine("DownloadPageAsync fileItems");
209
210
                    PageItem item = page.First();
211
212
                    /// 파일 체크 후 없으면 다시 다운로드
213
                    if (System.IO.File.Exists(item.LocalFilePath))
214
                    {
215
                        result = page.First();
216
                    }
217
                    else
218
                    {
219
                        fileItems.Remove(item);
220
221 24c5e56c taeseongkim
                        result = await DownloadPageAsync(PageNo,cts);
222 d7e20d2d taeseongkim
                    }
223
                }
224
                else
225
                {
226
                    System.Diagnostics.Debug.WriteLine("DownloadPageAsync down");
227
228 54a28343 taeseongkim
                    string downloadFilePath = System.IO.Path.Combine(_localStorage, PageNo.ToString() + "." + _fileExt);
229 d7e20d2d taeseongkim
230 96bc6e8e taeseongkim
                    Uri originalUri = new Uri(_BaseUri.Replace("{PageNo}", PageNo.ToString()));
231
232 d7e20d2d taeseongkim
233 448c5399 taeseongkim
                    using (System.Net.WebClient client = new System.Net.WebClient())
234 24c5e56c taeseongkim
                    {
235 448c5399 taeseongkim
                        client.UseDefaultCredentials = true;
236
                        System.Net.IWebProxy webProxy = client.Proxy;
237 d7e20d2d taeseongkim
238 448c5399 taeseongkim
                        if (webProxy != null)
239 d97dbc7f taeseongkim
                        {
240 448c5399 taeseongkim
                            // Use the default credentials of the logged on user.
241
                            webProxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
242 d97dbc7f taeseongkim
                        }
243
244 448c5399 taeseongkim
                        //client.DownloadFileCompleted += (snd, evt) =>
245
                        //{
246 24c5e56c taeseongkim
247 d7e20d2d taeseongkim
248 448c5399 taeseongkim
                        //    //(snd as System.Net.WebClient).Dispose();
249
                        //};
250 d7e20d2d taeseongkim
251 24c5e56c taeseongkim
                        if(cts != null)
252
                            client.DownloadProgressChanged += (snd, ect) =>
253
                            {
254
                                if(cts.Value.IsCancellationRequested)
255
                                {
256
                                    client.CancelAsync();
257
                                }
258
                            };
259
260 448c5399 taeseongkim
                        System.Diagnostics.Debug.WriteLine("Download : " + downloadFilePath);
261 72424099 taeseongkim
262 448c5399 taeseongkim
                        await client.DownloadFileTaskAsync(originalUri, downloadFilePath);
263
                    }
264
265
                    result = new PageItem
266
                    {
267
                        PageNo = PageNo,
268
                        OriginalUri = originalUri,
269
                        LocalUri = new Uri(downloadFilePath, UriKind.Absolute),
270
                        LocalFilePath = downloadFilePath
271
                    };
272
273
                    lock (fileItems)
274
                    {
275
                        fileItems.Add(result);
276
                    }
277 54a28343 taeseongkim
                    //System.Diagnostics.Debug.WriteLine("Download : " + result.LocalFilePath);
278 d7e20d2d taeseongkim
                }
279
            }
280
            catch (Exception ex)
281
            {
282
                throw new Exception("DownloadPageAsync : ", ex);
283
            }
284
            finally
285
            {
286
            }
287
288
            return result;
289
        }
290
291
        public void Clear()
292
        {
293
            try
294
            {
295
                ResetImage();
296
            }
297
            catch (Exception ex)
298
            {
299
                System.Diagnostics.Debug.WriteLine(ex.ToString());
300
            }
301
302
            try
303
            {
304
                backgroundWorker.CancelAsync();
305
                backgroundWorker.Dispose();
306
307
                fileItems.ForEach(x =>
308
                {
309
                    System.IO.File.Delete(x.LocalFilePath);
310
                });
311
312
                System.IO.Directory.Delete(_localStorage, true);
313
            }
314
            catch (Exception ex)
315
            {
316
                System.Diagnostics.Debug.WriteLine(ex.ToString());
317
            }
318
        }
319
    }
320
}
클립보드 이미지 추가 (최대 크기: 500 MB)