OSDN Git Service

bd74468c0fc303c213d744679b83cd064beaadd1
[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                         if (cancelCalled) {\r
169                                 throw new NaGetTaskCanceledException(string.Empty);\r
170                         }\r
171                         \r
172                         try {\r
173                                 response = request.GetResponse();\r
174                         } catch (WebException e) {\r
175                                 if (cancelCalled) { // キャンセル時\r
176                                         throw new NaGetTaskCanceledException(string.Empty, e);\r
177                                 } else {\r
178                                         throw new WebException(e.Message, e);\r
179                                 }\r
180                         }\r
181                         \r
182                         if (cancelCalled) {\r
183                                 throw new NaGetTaskCanceledException(string.Empty);\r
184                         }\r
185                         \r
186                         try {\r
187                                 downloadedFileName = getFileNameFromWebResponse(response);\r
188                         } catch (Exception) {\r
189                         }\r
190                         \r
191                         if (File.Exists(filepath)) { // ファイルが存在するとき削除\r
192                                 File.Delete(filepath);\r
193                         }\r
194                         \r
195                         RaiseDownloadEvent(DownloadEventType.CONNECTED, 0, -1);\r
196                         \r
197                         using (Stream stream = response.GetResponseStream() )\r
198                         using (FileStream fs = new FileStream(filepath,\r
199                                                     FileMode.Create,\r
200                                                     FileAccess.Write) ) {\r
201                                 try {\r
202                                         File.SetAttributes(filepath, FileAttributes.Hidden);\r
203                                         long contentLength = response.ContentLength;\r
204         \r
205                                         RaiseDownloadEvent(DownloadEventType.STARTED, 0, contentLength);\r
206                                         \r
207                                         stopwatch = new System.Diagnostics.Stopwatch();\r
208                                         stopwatch.Start();\r
209         \r
210                                         Timer timer = new Timer(new TimerCallback(\r
211                                                 delegate(object obj) {\r
212                                                         try {\r
213                                                                 RaiseDownloadEvent(DownloadEventType.DOWNLOADING, fs.Position, contentLength);\r
214                                                         } catch (ObjectDisposedException) {\r
215                                                         }\r
216                                                 }), null, 0, 1000);\r
217                                         \r
218                                         try {\r
219                                                 byte[] data = new byte[4096];\r
220                                                 int size = 0;\r
221                                                 while ((size = stream.Read(data,0,data.Length)) > 0) {\r
222                                                         fs.Write(data, 0, size);\r
223                                                         \r
224                                                         if (cancelCalled) {\r
225                                                                 throw new NaGetTaskCanceledException(string.Empty);\r
226                                                         }\r
227                                                 }\r
228                                         } finally {\r
229                                                 timer.Dispose();\r
230                                         }\r
231                                         \r
232                                         File.SetAttributes(filepath, FileAttributes.Normal);\r
233                                         \r
234                                         RaiseDownloadEvent(DownloadEventType.COMPLETED, fs.Position, contentLength);\r
235                                 } catch (IOException ex) {\r
236                                         if (cancelCalled) {\r
237                                                 throw new NaGetTaskCanceledException(string.Empty);\r
238                                         } else {\r
239                                                 RaiseDownloadEvent(DownloadEventType.ERROR, 0, 0);\r
240                                                 throw new IOException(ex.Message, ex);\r
241                                         }\r
242                                 } finally {\r
243                                         if (stopwatch != null) {\r
244                                                 stopwatch.Stop();\r
245                                                 stopwatch = null;\r
246                                         }\r
247                                 }\r
248                         }\r
249                         \r
250                         // 更新日を補完\r
251                         if (File.Exists(filepath)) {\r
252                                 if (response is HttpWebResponse) {\r
253                                         File.SetLastWriteTime(filepath, ((HttpWebResponse) response).LastModified);\r
254                                 } else if (response is FtpWebResponse) {\r
255                                         File.SetLastWriteTime(filepath, ((FtpWebResponse) response).LastModified);\r
256                                 }\r
257                         }\r
258                 } finally {\r
259                         if (response != null) {\r
260                                 response.Close();\r
261                         }\r
262                         \r
263                         request = null;\r
264                         done = true;\r
265                 }\r
266         }\r
267         \r
268         protected void RaiseDownloadEvent(DownloadEventType type, long pos, long max)\r
269         {\r
270                 if (DownloadEventRaised != null) {\r
271                         DownloadEventArgs e = new DownloadEventArgs(type, string.Empty, pos, max);\r
272                         \r
273                         switch (e.Type) {\r
274                                 case DownloadEventType.CONNECTED:\r
275                                         e.TaskMessage = "接続しました";\r
276                                         break;\r
277                                 case DownloadEventType.STARTED:\r
278                                 case DownloadEventType.DOWNLOADING:\r
279                                 case DownloadEventType.COMPLETED:\r
280                                         if (e.TaskProgressPercent >= 0) {\r
281                                                 e.TaskMessage = string.Format("{0} bytes ({1} %)", e.DownloadSize, (int) e.TaskProgressPercent);\r
282                                         } else {\r
283                                                 e.TaskMessage = string.Format("{0} bytes", e.DownloadSize);\r
284                                         }\r
285                                         \r
286                                         \r
287                                         if (stopwatch != null && stopwatch.IsRunning && stopwatch.ElapsedMilliseconds > 3000) {\r
288                                                 long bpers = e.DownloadSize * 1000 / stopwatch.ElapsedMilliseconds;\r
289                                                 if ((e.TaskProgressPercent >= 0) && (bpers > 0)) {\r
290                                                         TimeSpan rest = TimeSpan.FromSeconds((max - e.DownloadSize) / bpers);\r
291                                                         e.TaskMessage += string.Format(" 推定残り時間:{0} ({1}/s)", rest, NaGet.Utils.FormatSize(bpers));\r
292                                                 } else {\r
293                                                         e.TaskMessage += string.Format(" ({0}/s)", NaGet.Utils.FormatSize(bpers));\r
294                                                 }\r
295                                         }\r
296                                         \r
297                                         break;\r
298                         }\r
299                         \r
300                         DownloadEventRaised(this, e);\r
301                 }\r
302         }\r
303         \r
304         /// <summary>\r
305         /// キャンセル可能かを返す\r
306         /// </summary>\r
307         public override bool Cancelable {\r
308                 get { return !(this.Done || cancelCalled); }\r
309         }\r
310         \r
311         /// <summary>\r
312         /// ダウンロード処理をキャンセルする\r
313         /// </summary>\r
314         /// <returns>キャンセルに成功したときtrue</returns>\r
315         public override bool Cancel()\r
316         {\r
317                 if (this.Done || cancelCalled) {\r
318                         return false;\r
319                 }\r
320                 \r
321                 cancelCalled = true;\r
322                 if (request != null) {\r
323                         try {\r
324                                 request.Abort();\r
325                         } catch (WebException) {\r
326                         }\r
327                 }\r
328                 return true;\r
329         }\r
330         \r
331         /// <summary>\r
332         /// Webレスポンスからダウンロードしたファイルの名前を取得\r
333         /// </summary>\r
334         /// <remarks>Content-Dispositionヘッダから取得あるいはURLの末尾から推定します</remarks>\r
335         /// <param name="response">レスポンスオブジェクト</param>\r
336         /// <returns>取得したファイル名</returns>\r
337         private static string getFileNameFromWebResponse(WebResponse response)\r
338         {\r
339                 HttpWebResponse httpresp = response as HttpWebResponse;\r
340                 if (httpresp != null) {\r
341                         string contentDisposition = httpresp.Headers["Content-Disposition"];\r
342                         \r
343                         if (! string.IsNullOrEmpty(contentDisposition)) {\r
344                                 try {\r
345                                         ContentDisposition parser = new ContentDisposition(contentDisposition);\r
346                                         if (! string.IsNullOrEmpty(parser.FileName)) {\r
347                                                 return parser.FileName;\r
348                                         }\r
349                                 } catch (FormatException) {\r
350                                 }\r
351                         }\r
352                 }\r
353                 \r
354                 return NaGet.Utils.Url2filename(response.ResponseUri);\r
355         }\r
356 }\r
357 \r
358 }\r
359 \r
360 \r