프로젝트

일반

사용자정보

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

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

이력 | 보기 | 이력해설 | 다운로드 (9.7 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(System.Threading.CancellationToken cts,int PageNo,bool IsRestart =false)
82
        {
83
            try
84
            {
85

    
86
                var localUri = await GetPageUriAsync(cts,PageNo);
87

    
88
                if (localUri != null || !cts.IsCancellationRequested)
89
                {
90
                    PageImage = BitmapFrame.Create(localUri, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
91
                }
92
            }
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
        public async Task<Uri> GetPageUriAsync( System.Threading.CancellationToken cts, int PageNo, bool IsRestart = false)
105
        {
106
            Uri result = null;
107

    
108
            try
109
            {
110
                System.Diagnostics.Debug.WriteLine("GetPageAsync");
111

    
112
                var pageItem = await DownloadPageAsync(PageNo,cts);
113
                
114
                if (!IsRunWork && pageItem != null)
115
                {
116
                    var takePageNoList = Enumerable.Range(PageNo + 1, _TakeCount);
117

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

    
127
                            await Task.Delay(100);
128
                        }
129

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

    
132
                        if (_TotalPages == _TakeCount)
133
                        {
134
                            IsRunWork = true;
135
                        }
136
                    }
137
                }
138

    
139
                result = pageItem.LocalUri;
140
            }
141
            catch (Exception ex)
142
            {
143
                if (!IsRestart || !cts.IsCancellationRequested)
144
                {
145
                    await Task.Delay(100);
146

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

    
155
            return result;
156
        }
157

    
158
        public async void DownloadPagesAsync(int StartPageNo, int TalkCount = 5)
159
        {
160
            try
161
            {
162
                if (StartPageNo + TalkCount > _TotalPages)
163
                {
164
                    TalkCount = _TotalPages - StartPageNo;
165
                }
166

    
167
                if (TalkCount > 0)
168
                {
169
                    for (int i = StartPageNo; i < StartPageNo + TalkCount; i++)
170
                    {
171
                        try
172
                        {
173
                            await DownloadPageAsync(i,null);
174
                            System.Threading.Thread.Sleep(200);
175
                        }
176
                        catch (Exception ex)
177
                        {
178
                            System.Diagnostics.Debug.WriteLine("DownloadPagesAsync err", ex);
179
                        }
180
                        finally
181
                        {
182
                        }
183

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

    
198
        public async Task<PageItem> DownloadPageAsync(int PageNo,System.Threading.CancellationToken? cts)
199
        {
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
                        result = await DownloadPageAsync(PageNo,cts);
222
                    }
223
                }
224
                else
225
                {
226
                    System.Diagnostics.Debug.WriteLine("DownloadPageAsync down");
227

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

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

    
232

    
233
                    using (System.Net.WebClient client = new System.Net.WebClient())
234
                    {
235
                        client.UseDefaultCredentials = true;
236
                        System.Net.IWebProxy webProxy = client.Proxy;
237

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

    
244
                        //client.DownloadFileCompleted += (snd, evt) =>
245
                        //{
246

    
247

    
248
                        //    //(snd as System.Net.WebClient).Dispose();
249
                        //};
250

    
251
                        if(cts != null)
252
                            client.DownloadProgressChanged += (snd, ect) =>
253
                            {
254
                                if(cts.Value.IsCancellationRequested)
255
                                {
256
                                    client.CancelAsync();
257
                                }
258
                            };
259

    
260
                        System.Diagnostics.Debug.WriteLine("Download : " + downloadFilePath);
261

    
262
                        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
                    //System.Diagnostics.Debug.WriteLine("Download : " + result.LocalFilePath);
278
                }
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)