프로젝트

일반

사용자정보

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

markus / KCOM / PageManager / PageStorage.cs @ 8fb54282

이력 | 보기 | 이력해설 | 다운로드 (6.89 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 ex)
101
            {
102
                throw new Exception("GetPageAsync(string BasePageUri,int PageNo)", ex);
103
            }
104
            finally
105
            {
106
                GC.Collect(2);
107
            }
108

    
109
            return PageImage;
110
        }
111

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

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

    
135
        public async Task<PageItem> DownloadPageAsync(int PageNo)
136
        {
137
            PageItem result = new PageItem { PageNo = PageNo };
138

    
139
            try
140
            {
141
                var page = fileItems.Where(x => x.PageNo == PageNo);
142

    
143
                if (page.Count() > 0)
144
                {
145
                    System.Diagnostics.Debug.WriteLine("DownloadPageAsync fileItems");
146

    
147
                    PageItem item = page.First();
148

    
149
                    /// 파일 체크 후 없으면 다시 다운로드
150
                    if (System.IO.File.Exists(item.LocalFilePath))
151
                    {
152
                        result = page.First();
153
                    }
154
                    else
155
                    {
156
                        fileItems.Remove(item);
157

    
158
                        result = await DownloadPageAsync(PageNo);
159
                    }
160
                }
161
                else
162
                {
163

    
164
                    System.Diagnostics.Debug.WriteLine("DownloadPageAsync down");
165

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

    
168
                    result = new PageItem
169
                    {
170
                        PageNo = PageNo,
171
                        OriginalUri = new Uri(_BaseUri.Replace("{PageNo}", PageNo.ToString())),
172
                        LocalUri = new Uri(downloadFilePath, UriKind.Absolute),
173
                        LocalFilePath = downloadFilePath
174
                    };
175

    
176
                    using (System.Net.WebClient client = new System.Net.WebClient())
177
                    {
178
                        client.UseDefaultCredentials = true;
179
                        System.Net.IWebProxy webProxy = client.Proxy;
180

    
181
                        if (webProxy != null)
182
                        {
183
                            // Use the default credentials of the logged on user.
184
                            webProxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
185
                        }
186

    
187
                        client.DownloadFileCompleted += (snd, evt) =>
188
                        {
189
                            fileItems.Add(result);
190
                        };
191

    
192
                        await client.DownloadFileTaskAsync(result.OriginalUri, downloadFilePath);
193

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