OSDN Git Service

e54bfe8ce58815dcded59dffe10bdfe0ea93bd7c
[applistation/AppliStation.git] / na-get-lib / NaGet.Net / Downloader.cs
1 using System;\r
2 using System.Net;\r
3 using System.Net.Mime;\r
4 using System.IO;\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         public IWebProxy proxy;\r
67         \r
68         /// <summary>\r
69         /// イベントハンドラ\r
70         /// </summary>\r
71         public event EventHandler<DownloadEventArgs> DownloadEventRaised;\r
72         \r
73         /// <summary>\r
74         /// アクセスURL\r
75         /// </summary>\r
76         protected Uri url;\r
77         \r
78         /// <summary>\r
79         /// 保存先\r
80         /// </summary>\r
81         protected string filepath;\r
82         \r
83         /// <summary>\r
84         /// リクエストオブジェクト\r
85         /// </summary>\r
86         protected WebRequest request;\r
87         \r
88         /// <summary>\r
89         /// レスポンスオブジェクト。応答がくるまではnullである。\r
90         /// </summary>\r
91         protected WebResponse response;\r
92         \r
93         /// <summary>\r
94         /// ダウンロード要求時のキャッシュレベル。デフォルトではキャッシュ無視\r
95         /// </summary>\r
96         public System.Net.Cache.RequestCacheLevel CacheLevel = System.Net.Cache.RequestCacheLevel.NoCacheNoStore;\r
97         \r
98         private bool cancelCalled = false;\r
99         \r
100         private bool done = false;\r
101         \r
102         /// <summary>\r
103         /// ダウンロード時にHTTPヘッダなどから取得した本来のファイル名\r
104         /// </summary>\r
105         private string downloadedFileName = null;\r
106         \r
107         /// <summary>\r
108         /// ウェブアクセスに使うプロキシ\r
109         /// </summary>\r
110         public IWebProxy Proxy {\r
111                 get { return proxy ?? NaGet.Env.WebProxy; }\r
112                 set { proxy = value; }\r
113         }\r
114         \r
115         /// <summary>\r
116         /// ダウンロード時にHTTPヘッダなどから取得した本来のファイル名\r
117         /// </summary>\r
118         public string DownloadedFileName {\r
119                 get { return downloadedFileName; }\r
120         }\r
121         \r
122         /* ダウンロードの処理時間計測器 */\r
123         private System.Diagnostics.Stopwatch stopwatch;\r
124 \r
125         /// <summary>\r
126         /// ダウンロードを行う\r
127         /// </summary>\r
128         /// <param name="url">ダウンロードするリソースのURL</param>\r
129         /// <param name="filepath">保存先ファイルパス</param>\r
130         public void Download(string url, string filepath)\r
131         {\r
132                 this.url = new Uri(url);\r
133                 this.filepath = filepath;\r
134                 \r
135                 try {\r
136                         Run();\r
137                 } catch (NotSupportedException e) {\r
138                         throw new NotSupportedException("Not supported download location for downloader.", e);\r
139                 }\r
140         }\r
141         \r
142         /// <summary>\r
143         /// 処理が終了したか否かのフラグ\r
144         /// </summary>\r
145         public override bool Done {\r
146                 get { return done; }\r
147         }\r
148         \r
149         /// <summary>\r
150         /// 現在ダウンロード処理実行中であるかのフラグ\r
151         /// </summary>\r
152         public override bool Running {\r
153                 get { return request != null && (!done); }\r
154         }\r
155 \r
156         /// <summary>\r
157         /// ダウンロード処理を実行する\r
158         /// </summary>\r
159         public override void Run()\r
160         {\r
161                 RaiseDownloadEvent(DownloadEventType.INITED, 0, -1);\r
162                 \r
163                 try {\r
164                         request = WebRequest.Create(url);\r
165                         request.Proxy = this.Proxy;\r
166                         request.CachePolicy = new System.Net.Cache.RequestCachePolicy(CacheLevel);\r
167                         \r
168                         HttpWebRequest httpRequest = request as HttpWebRequest;\r
169                         if (httpRequest != null) {\r
170                                 httpRequest.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;  \r
171                                 httpRequest.UserAgent = "AppliStation/1.3";\r
172                         }\r
173                         \r
174                         if (cancelCalled) {\r
175                                 throw new NaGetTaskCanceledException(string.Empty);\r
176                         }\r
177                         \r
178                         try {\r
179                                 response = request.GetResponse();\r
180                         } catch (WebException e) {\r
181                                 if (cancelCalled) { // キャンセル時\r
182                                         throw new NaGetTaskCanceledException(string.Empty, e);\r
183                                 } else {\r
184                                         throw new WebException(e.Message, e);\r
185                                 }\r
186                         }\r
187                         \r
188                         if (cancelCalled) {\r
189                                 throw new NaGetTaskCanceledException(string.Empty);\r
190                         }\r
191                         \r
192                         try {\r
193                                 downloadedFileName = getFileNameFromWebResponse(response);\r
194                         } catch (Exception) {\r
195                         }\r
196                         \r
197                         if (File.Exists(filepath)) { // ファイルが存在するとき削除\r
198                                 File.Delete(filepath);\r
199                         }\r
200                         \r
201                         RaiseDownloadEvent(DownloadEventType.CONNECTED, 0, -1);\r
202                         \r
203                         using (Stream stream = response.GetResponseStream() )\r
204                         using (FileStream fs = new FileStream(filepath,\r
205                                                     FileMode.Create,\r
206                                                     FileAccess.Write) ) {\r
207                                 try {\r
208                                         File.SetAttributes(filepath, FileAttributes.Hidden);\r
209                                         long contentLength = response.ContentLength;\r
210         \r
211                                         RaiseDownloadEvent(DownloadEventType.STARTED, 0, contentLength);\r
212                                         \r
213                                         stopwatch = new System.Diagnostics.Stopwatch();\r
214                                         stopwatch.Start();\r
215         \r
216                                         Timer timer = new Timer(new TimerCallback(\r
217                                                 delegate(object obj) {\r
218                                                         try {\r
219                                                                 RaiseDownloadEvent(DownloadEventType.DOWNLOADING, fs.Position, contentLength);\r
220                                                         } catch (ObjectDisposedException) {\r
221                                                         }\r
222                                                 }), null, 0, 1000);\r
223                                         \r
224                                         try {\r
225                                                 byte[] data = new byte[4096];\r
226                                                 int size = 0;\r
227                                                 while ((size = stream.Read(data,0,data.Length)) > 0) {\r
228                                                         fs.Write(data, 0, size);\r
229                                                         \r
230                                                         if (cancelCalled) {\r
231                                                                 throw new NaGetTaskCanceledException(string.Empty);\r
232                                                         }\r
233                                                 }\r
234                                         } finally {\r
235                                                 timer.Dispose();\r
236                                         }\r
237                                         \r
238                                         File.SetAttributes(filepath, FileAttributes.Normal);\r
239                                         \r
240                                         RaiseDownloadEvent(DownloadEventType.COMPLETED, fs.Position, contentLength);\r
241                                 } catch (IOException ex) {\r
242                                         if (cancelCalled) {\r
243                                                 throw new NaGetTaskCanceledException(string.Empty);\r
244                                         } else {\r
245                                                 RaiseDownloadEvent(DownloadEventType.ERROR, 0, 0);\r
246                                                 throw new IOException(ex.Message, ex);\r
247                                         }\r
248                                 } finally {\r
249                                         if (stopwatch != null) {\r
250                                                 stopwatch.Stop();\r
251                                                 stopwatch = null;\r
252                                         }\r
253                                 }\r
254                         }\r
255                         \r
256                         // 更新日を補完\r
257                         if (File.Exists(filepath)) {\r
258                                 HttpWebResponse httpResponse = response as HttpWebResponse;\r
259                                 FtpWebResponse  ftpResponse      = response as FtpWebResponse;\r
260                                 \r
261                                 if (httpResponse != null) {\r
262                                         File.SetLastWriteTime(filepath, httpResponse.LastModified);\r
263                                 } else if (ftpResponse != null) {\r
264                                         File.SetLastWriteTime(filepath, ftpResponse.LastModified);\r
265                                 }\r
266                         }\r
267                 } finally {\r
268                         if (response != null) {\r
269                                 response.Close();\r
270                         }\r
271                         \r
272                         request = null;\r
273                         done = true;\r
274                 }\r
275         }\r
276         \r
277         protected void RaiseDownloadEvent(DownloadEventType type, long pos, long max)\r
278         {\r
279                 if (DownloadEventRaised != null) {\r
280                         DownloadEventArgs e = new DownloadEventArgs(type, string.Empty, pos, max);\r
281                         \r
282                         switch (e.Type) {\r
283                                 case DownloadEventType.CONNECTED:\r
284                                         e.TaskMessage = "接続しました";\r
285                                         break;\r
286                                 case DownloadEventType.STARTED:\r
287                                 case DownloadEventType.DOWNLOADING:\r
288                                 case DownloadEventType.COMPLETED:\r
289                                         if (e.TaskProgressPercent >= 0) {\r
290                                                 e.TaskMessage = string.Format("{0} bytes ({1} %)", e.DownloadSize, (int) e.TaskProgressPercent);\r
291                                         } else {\r
292                                                 e.TaskMessage = string.Format("{0} bytes", e.DownloadSize);\r
293                                         }\r
294                                         \r
295                                         \r
296                                         if (stopwatch != null && stopwatch.IsRunning && stopwatch.ElapsedMilliseconds > 3000) {\r
297                                                 long bpers = e.DownloadSize * 1000 / stopwatch.ElapsedMilliseconds;\r
298                                                 if ((e.TaskProgressPercent >= 0) && (bpers > 0)) {\r
299                                                         TimeSpan rest = TimeSpan.FromSeconds((max - e.DownloadSize) / bpers);\r
300                                                         e.TaskMessage += string.Format(" 推定残り時間:{0} ({1}/s)", rest, NaGet.Utils.FormatSize(bpers));\r
301                                                 } else {\r
302                                                         e.TaskMessage += string.Format(" ({0}/s)", NaGet.Utils.FormatSize(bpers));\r
303                                                 }\r
304                                         }\r
305                                         \r
306                                         break;\r
307                         }\r
308                         \r
309                         DownloadEventRaised(this, e);\r
310                 }\r
311         }\r
312         \r
313         /// <summary>\r
314         /// キャンセル可能かを返す\r
315         /// </summary>\r
316         public override bool Cancelable {\r
317                 get { return !(this.Done || cancelCalled); }\r
318         }\r
319         \r
320         /// <summary>\r
321         /// ダウンロード処理をキャンセルする\r
322         /// </summary>\r
323         /// <returns>キャンセルに成功したときtrue</returns>\r
324         public override bool Cancel()\r
325         {\r
326                 if (this.Done || cancelCalled) {\r
327                         return false;\r
328                 }\r
329                 \r
330                 cancelCalled = true;\r
331                 if (request != null) {\r
332                         try {\r
333                                 request.Abort();\r
334                         } catch (WebException) {\r
335                         }\r
336                 }\r
337                 return true;\r
338         }\r
339         \r
340         /// <summary>\r
341         /// Webレスポンスからダウンロードしたファイルの名前を取得\r
342         /// </summary>\r
343         /// <remarks>Content-Dispositionヘッダから取得あるいはURLの末尾から推定します</remarks>\r
344         /// <param name="response">レスポンスオブジェクト</param>\r
345         /// <returns>取得したファイル名</returns>\r
346         private static string getFileNameFromWebResponse(WebResponse response)\r
347         {\r
348                 HttpWebResponse httpresp = response as HttpWebResponse;\r
349                 if (httpresp != null) {\r
350                         string contentDisposition = httpresp.Headers["Content-Disposition"];\r
351                         \r
352                         if (! string.IsNullOrEmpty(contentDisposition)) {\r
353                                 try {\r
354                                         ContentDisposition parser = new ContentDisposition(contentDisposition);\r
355                                         if (! string.IsNullOrEmpty(parser.FileName)) {\r
356                                                 return parser.FileName;\r
357                                         }\r
358                                 } catch (FormatException) {\r
359                                 }\r
360                         }\r
361                 }\r
362                 \r
363                 return NaGet.Utils.Url2filename(response.ResponseUri);\r
364         }\r
365 }\r
366 \r
367 }\r
368 \r
369 \r