프로젝트

일반

사용자정보

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

markus / KCOM / PageManager / PageStorage.cs @ 54a28343

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

1
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
        bool IsRunWork = false;
15
        BackgroundWorker backgroundWorker;
16
        List<PageItem> fileItems = new List<PageItem>();
17
        string _localStorage;
18
        string _fileExt;
19
        string _BaseUri;
20
        int _TotalPages;
21
        int _TakeCount;
22

    
23

    
24
        BitmapFrame PageImage;
25

    
26
        public PageStorage(string BaseUri, string localStoragePath,string fileExt,int totalPages,int takeCount = 5)
27
        {
28
            try
29
            {
30
                backgroundWorker = new BackgroundWorker {WorkerSupportsCancellation = true };
31
                backgroundWorker.DoWork += BackgroundWorker_DoWork;
32

    
33
                _fileExt = fileExt;
34
                _BaseUri = BaseUri;
35
                _localStorage = localStoragePath;
36
                _TotalPages = totalPages;
37
                _TakeCount = takeCount;
38

    
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
                    DownloadPagesAsync(StartPageNo, TalkCount);
66
                }
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
        public async Task<BitmapFrame> GetPageImageAsync(int PageNo,bool IsRestart =false)
82
        {
83
            try
84
            {
85

    
86
                var localUri = await GetPageUriAsync(PageNo);
87

    
88
                PageImage = BitmapFrame.Create(localUri, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
89
            }
90
            catch (Exception ex)
91
            {
92
                throw new Exception("GetPageImageAsync(int PageNo,bool IsRestart =false)", ex);
93
            }
94
            finally
95
            {
96
            }
97

    
98
            return PageImage;
99
        }
100

    
101
        public async Task<Uri> GetPageUriAsync(int PageNo, bool IsRestart = false)
102
        {
103
            Uri result = null;
104

    
105
            try
106
            {
107
                System.Diagnostics.Debug.WriteLine("GetPageAsync");
108

    
109
                var pageItem = await DownloadPageAsync(PageNo);
110
                
111
                if (!IsRunWork && pageItem != null)
112
                {
113
                    var takePageNoList = Enumerable.Range(PageNo + 1, _TakeCount);
114

    
115
                    if (takePageNoList.Any(x => fileItems.Count(y => y.PageNo == x) == 0))
116
                    {
117
                        while (backgroundWorker.IsBusy)
118
                        {
119
                            if (backgroundWorker.IsBusy)
120
                            {
121
                                backgroundWorker.CancelAsync();
122
                            }
123

    
124
                            await Task.Delay(100);
125
                        }
126

    
127
                        backgroundWorker.RunWorkerAsync(new int[] { PageNo + 1, _TakeCount });
128

    
129
                        if (_TotalPages == _TakeCount)
130
                        {
131
                            IsRunWork = true;
132
                        }
133
                    }
134
                }
135

    
136
                result = pageItem.LocalUri;
137
            }
138
            catch (Exception ex)
139
            {
140
                if (!IsRestart)
141
                {
142
                    await Task.Delay(100);
143

    
144
                    result = await GetPageUriAsync(PageNo, true);
145
                }
146
                //throw new Exception("GetPageAsync(string BasePageUri,int PageNo)", ex);
147
            }
148
            finally
149
            {
150
            }
151

    
152
            return result;
153
        }
154

    
155
        public void DownloadPagesAsync(int StartPageNo, int TalkCount = 5)
156
        {
157
            try
158
            {
159
                if (StartPageNo + TalkCount > _TotalPages)
160
                {
161
                    TalkCount = _TotalPages - StartPageNo;
162
                }
163

    
164
                if (TalkCount > 0)
165
                {
166
                    for (int i = StartPageNo; i < StartPageNo + TalkCount; i++)
167
                    {
168
                        try
169
                        {
170
                            DownloadPageAsync(i).RunAndForget();
171
                            
172
                        }
173
                        catch (Exception ex)
174
                        {
175
                            System.Diagnostics.Debug.WriteLine("DownloadPagesAsync err", ex);
176
                        }
177
                        finally
178
                        {
179
                        }
180

    
181
                    }
182
                }
183
            }
184
            catch (Exception ex)
185
            {
186
                throw new Exception("DownloadPagesAsync : ", ex);
187
            }
188
            finally
189
            {
190
                GC.Collect(2);
191
                GC.Collect(2);
192
            }
193
        }
194

    
195
        public async Task<PageItem> DownloadPageAsync(int PageNo)
196
        {
197
            PageItem result = new PageItem { PageNo = PageNo };
198

    
199
            try
200
            {
201
                var page = fileItems.Where(x => x.PageNo == PageNo);
202

    
203
                if (page.Count() > 0)
204
                {
205
                    System.Diagnostics.Debug.WriteLine("DownloadPageAsync fileItems");
206

    
207
                    PageItem item = page.First();
208

    
209
                    /// 파일 체크 후 없으면 다시 다운로드
210
                    if (System.IO.File.Exists(item.LocalFilePath))
211
                    {
212
                        result = page.First();
213
                    }
214
                    else
215
                    {
216
                        fileItems.Remove(item);
217

    
218
                        result = await DownloadPageAsync(PageNo);
219
                    }
220
                }
221
                else
222
                {
223

    
224
                    System.Diagnostics.Debug.WriteLine("DownloadPageAsync down");
225

    
226
                    string downloadFilePath = System.IO.Path.Combine(_localStorage, PageNo.ToString() + "." + _fileExt);
227

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

    
230

    
231
                    System.Net.WebClient client = new System.Net.WebClient();
232

    
233
                    client.UseDefaultCredentials = true;
234
                    System.Net.IWebProxy webProxy = client.Proxy;
235

    
236
                    if (webProxy != null)
237
                    {
238
                        // Use the default credentials of the logged on user.
239
                        webProxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
240
                    }
241

    
242
                    client.DownloadFileCompleted += (snd, evt) =>
243
                    {
244
                        result = new PageItem
245
                        {
246
                            PageNo = PageNo,
247
                            OriginalUri = originalUri,
248
                            LocalUri = new Uri(downloadFilePath, UriKind.Absolute),
249
                            LocalFilePath = downloadFilePath
250
                        };
251

    
252
                        fileItems.Add(result);
253
                    };
254

    
255
                    System.Diagnostics.Debug.WriteLine("Download : " + downloadFilePath);
256

    
257
                    await client.DownloadFileTaskAsync(originalUri, downloadFilePath);
258

    
259
                    //System.Diagnostics.Debug.WriteLine("Download : " + result.LocalFilePath);
260
                }
261
            }
262
            catch (Exception ex)
263
            {
264
                throw new Exception("DownloadPageAsync : ", ex);
265
            }
266
            finally
267
            {
268
            }
269

    
270
            return result;
271
        }
272

    
273
        public void Clear()
274
        {
275
            try
276
            {
277
                ResetImage();
278
            }
279
            catch (Exception ex)
280
            {
281
                System.Diagnostics.Debug.WriteLine(ex.ToString());
282
            }
283

    
284
            try
285
            {
286
                backgroundWorker.CancelAsync();
287
                backgroundWorker.Dispose();
288

    
289
                fileItems.ForEach(x =>
290
                {
291
                    System.IO.File.Delete(x.LocalFilePath);
292
                });
293

    
294
                System.IO.Directory.Delete(_localStorage, true);
295
            }
296
            catch (Exception ex)
297
            {
298
                System.Diagnostics.Debug.WriteLine(ex.ToString());
299
            }
300
        }
301
    }
302
}
클립보드 이미지 추가 (최대 크기: 500 MB)