OSDN Git Service

initial build for opensource
[applistation/AppliStation.git] / na-get-lib / NaGet.Net / Downloader.cs
1 using System;\r
2 using System.Net;\r
3 using System.IO;\r
4 using System.Collections;\r
5 using System.Threading;\r
6 using NaGet.SubCommands;\r
7 \r
8 namespace NaGet.Net\r
9 {\r
10 \r
11 /// <summary>\r
12 /// ダウンロードイベントオブジェクト\r
13 /// </summary>\r
14 public class DownloadEventArgs : NaGetEventArgs\r
15 {\r
16         /// <summary>\r
17         /// イベントの種類\r
18         /// </summary>\r
19         public DownloadEventType Type;\r
20 \r
21         /// <summary>\r
22         /// ダウンロード済みのバイト数\r
23         /// </summary>\r
24         public long DownloadSize;\r
25 \r
26         /// <summary>\r
27         /// ダウンロードする総バイト数\r
28         /// </summary>\r
29         public long MaxSize;\r
30         \r
31         /// <summary>\r
32         /// コンストラクタ\r
33         /// </summary>\r
34         /// <param name="type">イベントの種類</param>\r
35         /// <param name="msg">イベントメッセージ</param>\r
36         /// <param name="pos">ダウンロード済みのバイト数</param>\r
37         /// <param name="max">ダウンロードする総バイト数</param>\r
38         public DownloadEventArgs(DownloadEventType type, string msg, long pos, long max)\r
39         {\r
40                 Type = type;\r
41                 DownloadSize = pos;\r
42                 MaxSize = max;\r
43                 \r
44                 TaskMessage = msg;\r
45                 TaskProgressPercent = (max > 0)? (100.0f * pos / max) : -1;\r
46         }\r
47 }\r
48 \r
49 /// <summary>\r
50 /// DownloadEventArgsでのイベントの種類\r
51 /// </summary>\r
52 public enum DownloadEventType {\r
53         INITED,\r
54         CONNECTED,\r
55         STARTED,\r
56         DOWNLOADING,\r
57         ERROR,\r
58         COMPLETED\r
59 }\r
60 \r
61 /// <summary>\r
62 /// ダウンロード処理を行うクラス\r
63 /// </summary>\r
64 public class Downloader : NaGetTask\r
65 {\r
66         /// <summary>\r
67         /// デフォルトで使うプロキシ\r
68         /// </summary>\r
69         public static IWebProxy DefaultProxy = WebRequest.GetSystemWebProxy();\r
70         \r
71         /// <summary>\r
72         /// 通信に使うプロキシ\r
73         /// </summary>\r
74         public IWebProxy Proxy;\r
75         \r
76         /// <summary>\r
77         /// イベントハンドラ\r
78         /// </summary>\r
79         public event EventHandler<DownloadEventArgs> DownloadEventRaised;\r
80         \r
81         protected string url;\r
82         \r
83         protected string filepath;\r
84         \r
85         protected WebRequest request;\r
86         \r
87         protected WebResponse response;\r
88         \r
89         private bool cancelCalled = false;\r
90         \r
91         private bool done = false;\r
92         \r
93         /// <summary>\r
94         /// ダウンロード時にHTTPヘッダなどから取得した本来のファイル名\r
95         /// </summary>\r
96         private string downloadedFileName = null;\r
97         \r
98         /// <summary>\r
99         /// ダウンロード時にHTTPヘッダなどから取得した本来のファイル名\r
100         /// </summary>\r
101         public string DownloadedFileName {\r
102                 get { return downloadedFileName; }\r
103         }\r
104         \r
105         /* ダウンロードの処理時間計測器 */\r
106         private System.Diagnostics.Stopwatch stopwatch;\r
107 \r
108         /// <summary>\r
109         /// ダウンロードを行う\r
110         /// </summary>\r
111         /// <param name="url">ダウンロードするリソースのURL</param>\r
112         /// <param name="filepath">保存先ファイルパス</param>\r
113         public void Download(string url, string filepath)\r
114         {\r
115                 this.url = url;\r
116                 this.filepath = filepath;\r
117                 \r
118                 try {\r
119                         Run();\r
120                 } catch (NotSupportedException e) {\r
121                         throw new NotSupportedException("Not supported download location for downloader.", e);\r
122                 }\r
123         }\r
124         \r
125         public override bool Done {\r
126                 get { return done; }\r
127         }\r
128         \r
129         public override bool Running {\r
130                 get { return request != null && (!done); }\r
131         }\r
132 \r
133         public override void Run()\r
134         {\r
135                 RaiseDownloadEvent(DownloadEventType.INITED, 0, -1);\r
136                 \r
137                 try {\r
138                         request = WebRequest.Create(url);\r
139                         request.Proxy = (Proxy == null)? DefaultProxy : Proxy;    \r
140                         if (request is HttpWebRequest) {\r
141                                 request.CachePolicy = new System.Net.Cache.HttpRequestCachePolicy(\r
142                                         System.Net.Cache.HttpRequestCacheLevel.NoCacheNoStore);\r
143                         }\r
144                         \r
145                         if (cancelCalled) {\r
146                                 throw new NaGetTaskCanceledException(string.Empty);\r
147                         }\r
148                         \r
149                         try {\r
150                                 response = request.GetResponse();\r
151                         } catch (WebException e) {\r
152                                 if (cancelCalled) { // キャンセル時\r
153                                         throw new NaGetTaskCanceledException(string.Empty, e);\r
154                                 } else {\r
155                                         throw new WebException(e.Message, e);\r
156                                 }\r
157                         }\r
158                         \r
159                         if (cancelCalled) {\r
160                                 throw new NaGetTaskCanceledException(string.Empty);\r
161                         }\r
162                         \r
163                         try {\r
164                                 downloadedFileName = getFileNameFromWebResponse(response);\r
165                         } catch (Exception) {\r
166                         }\r
167                         \r
168                         if (File.Exists(filepath)) { // ファイルが存在するとき削除\r
169                                 File.Delete(filepath);\r
170                         }\r
171                         \r
172                         RaiseDownloadEvent(DownloadEventType.CONNECTED, 0, -1);\r
173                         \r
174                         using (Stream stream = response.GetResponseStream() )\r
175                         using (FileStream fs = new FileStream(filepath,\r
176                                                     FileMode.Create,\r
177                                                     FileAccess.Write) ) {\r
178                                 try {\r
179                                         File.SetAttributes(filepath, FileAttributes.Hidden);\r
180                                         long contentLength = response.ContentLength;\r
181         \r
182                                         RaiseDownloadEvent(DownloadEventType.STARTED, 0, contentLength);\r
183                                         \r
184                                         stopwatch = new System.Diagnostics.Stopwatch();\r
185                                         stopwatch.Start();\r
186         \r
187                                         Timer timer = new Timer(new TimerCallback(\r
188                                                 delegate(object obj) {\r
189                                                         try {\r
190                                                                 RaiseDownloadEvent(DownloadEventType.DOWNLOADING, fs.Position, contentLength);\r
191                                                         } catch (ObjectDisposedException) {\r
192                                                         }\r
193                                                 }), null, 0, 1000);\r
194                                         \r
195                                         try {\r
196                                                 byte[] data = new byte[4096];\r
197                                                 int size = 0;\r
198                                                 while ((size = stream.Read(data,0,data.Length)) > 0) {\r
199                                                         fs.Write(data, 0, size);\r
200                                                         \r
201                                                         bool hoge = cancelCalled;\r
202                                                         \r
203                                                         if (cancelCalled) {\r
204                                                                 throw new NaGetTaskCanceledException(string.Empty);\r
205                                                         }\r
206                                                 }\r
207                                         } finally {\r
208                                                 timer.Dispose();\r
209                                         }\r
210                                         \r
211                                         File.SetAttributes(filepath, FileAttributes.Normal);\r
212                                         \r
213                                         RaiseDownloadEvent(DownloadEventType.COMPLETED, fs.Position, contentLength);\r
214                                 } catch (IOException ex) {\r
215                                         if (cancelCalled) {\r
216                                                 throw new NaGetTaskCanceledException(string.Empty);\r
217                                         } else {\r
218                                                 RaiseDownloadEvent(DownloadEventType.ERROR, 0, 0);\r
219                                                 throw new IOException(ex.Message, ex);\r
220                                         }\r
221                                 } finally {\r
222                                         if (stopwatch != null) {\r
223                                                 stopwatch.Stop();\r
224                                                 stopwatch = null;\r
225                                         }\r
226                                 }\r
227                         }\r
228                 } finally {\r
229                         if (response != null) {\r
230                                 response.Close();\r
231                         }\r
232                         \r
233                         request = null;\r
234                         done = true;\r
235                 }\r
236         }\r
237         \r
238         protected void RaiseDownloadEvent(DownloadEventType type, long pos, long max)\r
239         {\r
240                 if (DownloadEventRaised != null) {\r
241                         DownloadEventArgs e = new DownloadEventArgs(type, string.Empty, pos, max);\r
242                         \r
243                         switch (e.Type) {\r
244                                 case DownloadEventType.CONNECTED:\r
245                                         e.TaskMessage = "接続しました";\r
246                                         break;\r
247                                 case DownloadEventType.STARTED:\r
248                                 case DownloadEventType.DOWNLOADING:\r
249                                 case DownloadEventType.COMPLETED:\r
250                                         try {\r
251                                                 e.TaskMessage = string.Format("{0} bytes ({1} %)", e.DownloadSize, (int) e.TaskProgressPercent);\r
252                                         } catch (DivideByZeroException) {\r
253                                                 e.TaskMessage = string.Format("{0} bytes", e.DownloadSize);\r
254                                         }\r
255                                         \r
256                                         \r
257                                         if (stopwatch != null && stopwatch.IsRunning && stopwatch.ElapsedMilliseconds > 3000) {\r
258                                                 long bpers = e.DownloadSize * 1000 / stopwatch.ElapsedMilliseconds;\r
259                                                 try {\r
260                                                         TimeSpan rest = TimeSpan.FromSeconds((max - e.DownloadSize) / bpers);\r
261                                                         e.TaskMessage += string.Format(" 推定残り時間:{0} ({1}/s)", rest, NaGet.Utils.FormatSize(bpers));\r
262                                                 } catch {\r
263                                                         e.TaskMessage += string.Format(" ({0}/s)", NaGet.Utils.FormatSize(bpers));\r
264                                                 }\r
265                                         }\r
266                                         \r
267                                         break;\r
268                         }\r
269                         \r
270                         DownloadEventRaised(this, e);\r
271                 }\r
272         }\r
273         \r
274         public override bool Cancelable {\r
275                 get { return !(this.Done || cancelCalled); }\r
276         }\r
277         \r
278         public override bool Cancel()\r
279         {\r
280                 if (this.Done || cancelCalled) {\r
281                         return false;\r
282                 }\r
283                 \r
284                 cancelCalled = true;\r
285                 if (request != null) {\r
286                         try {\r
287                                 request.Abort();\r
288                         } catch (WebException) {\r
289                         }\r
290                 }\r
291                 return true;\r
292         }\r
293         \r
294         /// <summary>\r
295         /// Webレスポンスからダウンロードしたファイルの名前を取得\r
296         /// </summary>\r
297         /// <param name="response"></param>\r
298         /// <returns></returns>\r
299         private string getFileNameFromWebResponse(WebResponse response)\r
300         {\r
301                 if (response is HttpWebResponse) {\r
302                         string contentDisposition = ((HttpWebResponse) response).Headers["Content-Disposition"];\r
303                         \r
304                         // TODO check license for http://www.atmarkit.co.jp/fdotnet/dotnettips/618downnoname/downnoname.html\r
305                         if (! string.IsNullOrEmpty(contentDisposition)) {\r
306                                 System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(\r
307                                         @"filename\s*=\s*(?:""(?<filename>[^""]*)""|(?<filename>[^;]*))",\r
308                                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);\r
309                                 \r
310                                 System.Text.RegularExpressions.Match m = re.Match(contentDisposition);\r
311                                 if (m.Success) {\r
312                                         return m.Groups["filename"].Value;\r
313                                 }\r
314                         }\r
315                 }\r
316                 \r
317                 return NaGet.Utils.Url2filename(response.ResponseUri.ToString());\r
318         }\r
319 }\r
320 \r
321 }\r
322 \r
323 \r