프로젝트

일반

사용자정보

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

markus / KCOM / PageManager / PageStorage.cs @ a7372e37

이력 | 보기 | 이력해설 | 다운로드 (7.31 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

    
15
        BackgroundWorker backgroundWorker;
16
        List<PageItem> fileItems = new List<PageItem>();
17
        string _localStorage;
18
        string _BaseUri;
19
        int _TotalPages;
20

    
21

    
22
        BitmapFrame PageImage;
23

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

    
31
                _BaseUri = BaseUri;
32
                _localStorage = localStoragePath;
33
                _TotalPages = totalPages;
34

    
35
                System.IO.Directory.CreateDirectory(_localStorage);
36

    
37
                //backgroundWorker.RunWorkerAsync(new int[] { 1, 10 });
38
            }
39
            catch (Exception ex)
40
            {
41
                throw new Exception("PageStorage", ex);
42
            }
43
        }
44

    
45
        private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
46
        {
47
            int StartPageNo = -1;
48
            int TalkCount = -1;
49

    
50
            if (e.Argument != null)
51
            {
52

    
53
                var values = (e.Argument as int[]);
54

    
55
                if (values.Count() == 2)
56
                {
57

    
58
                    StartPageNo = values[0];
59
                    TalkCount = values[1];
60

    
61
                    DownloadPagesAsync(StartPageNo, TalkCount);
62
                }
63
            }
64
        }
65

    
66
        public void ResetImage()
67
        {
68
            //if (PageImage != null)
69
            //{
70
            //    PageImage = null;
71
            //}
72

    
73
            //PageImage.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
74

    
75
        }
76

    
77
        public async Task<BitmapFrame> GetPageAsync(int PageNo)
78
        {
79
            try
80
            {
81
                System.Diagnostics.Debug.WriteLine("GetPageAsync");
82
                
83
                while (backgroundWorker.IsBusy)
84
                {
85
                    await Task.Delay(100);
86

    
87
                    if (backgroundWorker.IsBusy)
88
                    {
89
                        backgroundWorker.CancelAsync();
90
                    }
91

    
92
                }
93

    
94
                var pageItem = await DownloadPageAsync(PageNo);
95

    
96
                backgroundWorker.RunWorkerAsync(new int[] { PageNo + 1, 5 });
97
        
98
                PageImage = BitmapFrame.Create(pageItem.LocalUri, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
99
            }
100
            catch (Exception)
101
            {
102
                PageImage = await GetPageAsync(PageNo);
103
                //throw new Exception("GetPageAsync(string BasePageUri,int PageNo)", ex);
104
            }
105
            finally
106
            {
107
            }
108

    
109
            return PageImage;
110
        }
111

    
112
        public void DownloadPagesAsync(int StartPageNo, int TalkCount = 5)
113
        {
114
            try
115
            {
116
                if (StartPageNo + TalkCount > _TotalPages)
117
                {
118
                    TalkCount = _TotalPages - StartPageNo;
119
                }
120

    
121
                if (TalkCount > 0)
122
                {
123
                    for (int i = StartPageNo; i < StartPageNo + TalkCount; i++)
124
                    {
125
                        try
126
                        {
127
                            DownloadPageAsync(i).RunAndForget();
128
                        }
129
                        catch (Exception ex)
130
                        {
131
                            System.Diagnostics.Debug.WriteLine("DownloadPagesAsync err", ex);
132
                        }
133
                        finally
134
                        {
135
                        }
136

    
137

    
138
                    }
139
                }
140
            }
141
            catch (Exception ex)
142
            {
143
                throw new Exception("DownloadPagesAsync : ", ex);
144
            }
145
            finally
146
            {
147
            
148
            }
149
        }
150

    
151
        public async Task<PageItem> DownloadPageAsync(int PageNo)
152
        {
153
            PageItem result = new PageItem { PageNo = PageNo };
154

    
155
            try
156
            {
157
                var page = fileItems.Where(x => x.PageNo == PageNo);
158

    
159
                if (page.Count() > 0)
160
                {
161
                    System.Diagnostics.Debug.WriteLine("DownloadPageAsync fileItems");
162

    
163
                    PageItem item = page.First();
164

    
165
                    /// 파일 체크 후 없으면 다시 다운로드
166
                    if (System.IO.File.Exists(item.LocalFilePath))
167
                    {
168
                        result = page.First();
169
                    }
170
                    else
171
                    {
172
                        fileItems.Remove(item);
173

    
174
                        result = await DownloadPageAsync(PageNo);
175
                    }
176
                }
177
                else
178
                {
179

    
180
                    System.Diagnostics.Debug.WriteLine("DownloadPageAsync down");
181

    
182
                    string downloadFilePath = System.IO.Path.Combine(_localStorage, PageNo.ToString() + ".png");
183

    
184
                    result = new PageItem
185
                    {
186
                        PageNo = PageNo,
187
                        OriginalUri = new Uri(_BaseUri.Replace("{PageNo}", PageNo.ToString())),
188
                        LocalUri = new Uri(downloadFilePath, UriKind.Absolute),
189
                        LocalFilePath = downloadFilePath
190
                    };
191

    
192
                    System.Net.WebClient client = new System.Net.WebClient();
193

    
194
                    client.UseDefaultCredentials = true;
195
                    System.Net.IWebProxy webProxy = client.Proxy;
196

    
197
                    if (webProxy != null)
198
                    {
199
                        // Use the default credentials of the logged on user.
200
                        webProxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
201
                    }
202

    
203
                    client.DownloadFileCompleted += (snd, evt) =>
204
                    {
205
                        fileItems.Add(result);
206
                    };
207

    
208
                    await client.DownloadFileTaskAsync(result.OriginalUri, downloadFilePath);
209

    
210
                    GC.Collect();
211
                    GC.WaitForPendingFinalizers();
212
                    GC.Collect();
213

    
214
                    System.Diagnostics.Debug.WriteLine("Download : " + result.LocalFilePath);
215
                }
216
            }
217
            catch (Exception ex)
218
            {
219
                throw new Exception("DownloadPageAsync : ", ex);
220
            }
221
            finally
222
            {
223
            }
224

    
225
            return result;
226
        }
227

    
228
        public void Clear()
229
        {
230
            try
231
            {
232
                ResetImage();
233
            }
234
            catch (Exception ex)
235
            {
236
                System.Diagnostics.Debug.WriteLine(ex.ToString());
237
            }
238

    
239
            try
240
            {
241
                backgroundWorker.CancelAsync();
242
                backgroundWorker.Dispose();
243

    
244
                fileItems.ForEach(x =>
245
                {
246
                    System.IO.File.Delete(x.LocalFilePath);
247
                });
248

    
249
                System.IO.Directory.Delete(_localStorage, true);
250
            }
251
            catch (Exception ex)
252
            {
253
                System.Diagnostics.Debug.WriteLine(ex.ToString());
254
            }
255
        }
256
    }
257
}
클립보드 이미지 추가 (최대 크기: 500 MB)