프로젝트

일반

사용자정보

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

markus / FileDownloader / PageStorage.cs @ 0cda2a88

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

1 0cda2a88 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 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();
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
                while(backgroundWorker.IsBusy)
82
                {
83
                    await Task.Delay(1000);
84
85
                    if(backgroundWorker.IsBusy)
86
                    {
87
                        backgroundWorker.CancelAsync();
88
                    }
89
                }
90
91
                System.Diagnostics.Debug.WriteLine("GetPageAsync");
92
                
93
                var pageItem = await DownloadPageAsync(PageNo);
94
95
                backgroundWorker.RunWorkerAsync(new int[] { PageNo + 1, 10 });
96
        
97
                PageImage = BitmapFrame.Create(pageItem.LocalUri, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
98
            }
99
            catch (Exception ex)
100
            {
101
                throw new Exception("GetPageAsync(string BasePageUri,int PageNo)", ex);
102
            }
103
            finally
104
            {
105
            }
106
107
            return PageImage;
108
        }
109
110
        public void DownloadPagesAsync(int StartPageNo, int TalkCount = 5)
111
        {
112
            if (StartPageNo + TalkCount > _TotalPages)
113
            {
114
                TalkCount = _TotalPages - StartPageNo;
115
            }
116
117
            if (TalkCount > 0)
118
            {
119
                for (int i = StartPageNo; i < StartPageNo + TalkCount; i++)
120
                {
121
                    try
122
                    {
123
                        DownloadPageAsync(i).RunAndForget();
124
                    }
125
                    catch (Exception ex)
126
                    {
127
                        System.Diagnostics.Debug.WriteLine("DownloadPagesAsync err", ex);
128
                    }
129
                }
130
            }
131
        }
132
133
        public async Task<PageItem> DownloadPageAsync(int PageNo)
134
        {
135
            PageItem result = new PageItem { PageNo = PageNo };
136
137
            try
138
            {
139
                var page = fileItems.Where(x => x.PageNo == PageNo);
140
141
                if (page.Count() > 0)
142
                {
143
                    System.Diagnostics.Debug.WriteLine("DownloadPageAsync fileItems");
144
145
                    PageItem item = page.First();
146
147
                    /// 파일 체크 후 없으면 다시 다운로드
148
                    if (System.IO.File.Exists(item.LocalFilePath))
149
                    {
150
                        result = page.First();
151
                    }
152
                    else
153
                    {
154
                        fileItems.Remove(item);
155
156
                        result = await DownloadPageAsync(PageNo);
157
                    }
158
                }
159
                else
160
                {
161
162
                    System.Diagnostics.Debug.WriteLine("DownloadPageAsync down");
163
164
                    string downloadFilePath = System.IO.Path.Combine(_localStorage, PageNo.ToString() + ".png");
165
166
                    PageItem item = new PageItem
167
                    {
168
                        PageNo = PageNo,
169
                        OriginalUri = new Uri(_BaseUri.Replace("{PageNo}", PageNo.ToString())),
170
                        LocalUri = new Uri(downloadFilePath, UriKind.Absolute),
171
                        LocalFilePath = downloadFilePath
172
                    };
173
174
                    using (System.Net.WebClient client = new System.Net.WebClient())
175
                    {
176
                        client.UseDefaultCredentials = true;
177
                        System.Net.IWebProxy webProxy = client.Proxy;
178
179
                        if (webProxy != null)
180
                        {
181
                            // Use the default credentials of the logged on user.
182
                            webProxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
183
                        }
184
185
                        var task = client.DownloadFileTaskAsync(item.OriginalUri, downloadFilePath);
186
187
                        client.DownloadFileCompleted += (snd, evt) =>
188
                        {
189
                            fileItems.Add(item);
190
                        };
191
192
                        await task;
193
                        System.Diagnostics.Debug.WriteLine("Download : " + item.LocalFilePath);
194
                        result = item;
195
                    }
196
                }
197
            }
198
            catch (Exception ex)
199
            {
200
                throw new Exception("DownloadPageAsync : ", ex);
201
            }
202
            finally
203
            {
204
            }
205
206
            return result;
207
        }
208
209
        public void Clear()
210
        {
211
            try
212
            {
213
                ResetImage();
214
            }
215
            catch (Exception ex)
216
            {
217
                System.Diagnostics.Debug.WriteLine(ex.ToString());
218
            }
219
220
            try
221
            {
222
                backgroundWorker.CancelAsync();
223
                backgroundWorker.Dispose();
224
225
                fileItems.ForEach(x =>
226
                {
227
                    System.IO.File.Delete(x.LocalFilePath);
228
                });
229
230
                System.IO.Directory.Delete(_localStorage, true);
231
            }
232
            catch (Exception ex)
233
            {
234
                System.Diagnostics.Debug.WriteLine(ex.ToString());
235
            }
236
        }
237
    }
238
}
클립보드 이미지 추가 (최대 크기: 500 MB)