OSDN Git Service

na-get,NaGetInstall(Update)のDownloderを外部から書き込みできないように(これに伴うAppliStation-GUI,all-getの変...
[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         /// <summary>\r
82         /// アクセスURL\r
83         /// </summary>\r
84         protected string url;\r
85         \r
86         /// <summary>\r
87         /// 保存先\r
88         /// </summary>\r
89         protected string filepath;\r
90         \r
91         /// <summary>\r
92         /// リクエストオブジェクト\r
93         /// </summary>\r
94         protected WebRequest request;\r
95         \r
96         /// <summary>\r
97         /// レスポンスオブジェクト。応答がくるまではnullである。\r
98         /// </summary>\r
99         protected WebResponse response;\r
100         \r
101         /// <summary>\r
102         /// ダウンロード要求時のキャッシュレベル。デフォルトではキャッシュ無視\r
103         /// </summary>\r
104         public System.Net.Cache.RequestCacheLevel CacheLevel = System.Net.Cache.RequestCacheLevel.NoCacheNoStore;\r
105         \r
106         private bool cancelCalled = false;\r
107         \r
108         private bool done = false;\r
109         \r
110         /// <summary>\r
111         /// ダウンロード時にHTTPヘッダなどから取得した本来のファイル名\r
112         /// </summary>\r
113         private string downloadedFileName = null;\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 = 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         public override bool Done {\r
143                 get { return done; }\r
144         }\r
145         \r
146         public override bool Running {\r
147                 get { return request != null && (!done); }\r
148         }\r
149 \r
150         public override void Run()\r
151         {\r
152                 RaiseDownloadEvent(DownloadEventType.INITED, 0, -1);\r
153                 \r
154                 try {\r
155                         request = WebRequest.Create(url);\r
156                         request.Proxy = (Proxy == null)? DefaultProxy : Proxy;\r
157                         request.CachePolicy = new System.Net.Cache.RequestCachePolicy(CacheLevel);\r
158                         \r
159                         if (cancelCalled) {\r
160                                 throw new NaGetTaskCanceledException(string.Empty);\r
161                         }\r
162                         \r
163                         try {\r
164                                 response = request.GetResponse();\r
165                         } catch (WebException e) {\r
166                                 if (cancelCalled) { // キャンセル時\r
167                                         throw new NaGetTaskCanceledException(string.Empty, e);\r
168                                 } else {\r
169                                         throw new WebException(e.Message, e);\r
170                                 }\r
171                         }\r
172                         \r
173                         if (cancelCalled) {\r
174                                 throw new NaGetTaskCanceledException(string.Empty);\r
175                         }\r
176                         \r
177                         try {\r
178                                 downloadedFileName = getFileNameFromWebResponse(response);\r
179                         } catch (Exception) {\r
180                         }\r
181                         \r
182                         if (File.Exists(filepath)) { // ファイルが存在するとき削除\r
183                                 File.Delete(filepath);\r
184                         }\r
185                         \r
186                         RaiseDownloadEvent(DownloadEventType.CONNECTED, 0, -1);\r
187                         \r
188                         using (Stream stream = response.GetResponseStream() )\r
189                         using (FileStream fs = new FileStream(filepath,\r
190                                                     FileMode.Create,\r
191                                                     FileAccess.Write) ) {\r
192                                 try {\r
193                                         File.SetAttributes(filepath, FileAttributes.Hidden);\r
194                                         long contentLength = response.ContentLength;\r
195         \r
196                                         RaiseDownloadEvent(DownloadEventType.STARTED, 0, contentLength);\r
197                                         \r
198                                         stopwatch = new System.Diagnostics.Stopwatch();\r
199                                         stopwatch.Start();\r
200         \r
201                                         Timer timer = new Timer(new TimerCallback(\r
202                                                 delegate(object obj) {\r
203                                                         try {\r
204                                                                 RaiseDownloadEvent(DownloadEventType.DOWNLOADING, fs.Position, contentLength);\r
205                                                         } catch (ObjectDisposedException) {\r
206                                                         }\r
207                                                 }), null, 0, 1000);\r
208                                         \r
209                                         try {\r
210                                                 byte[] data = new byte[4096];\r
211                                                 int size = 0;\r
212                                                 while ((size = stream.Read(data,0,data.Length)) > 0) {\r
213                                                         fs.Write(data, 0, size);\r
214                                                         \r
215                                                         if (cancelCalled) {\r
216                                                                 throw new NaGetTaskCanceledException(string.Empty);\r
217                                                         }\r
218                                                 }\r
219                                         } finally {\r
220                                                 timer.Dispose();\r
221                                         }\r
222                                         \r
223                                         File.SetAttributes(filepath, FileAttributes.Normal);\r
224                                         \r
225                                         RaiseDownloadEvent(DownloadEventType.COMPLETED, fs.Position, contentLength);\r
226                                 } catch (IOException ex) {\r
227                                         if (cancelCalled) {\r
228                                                 throw new NaGetTaskCanceledException(string.Empty);\r
229                                         } else {\r
230                                                 RaiseDownloadEvent(DownloadEventType.ERROR, 0, 0);\r
231                                                 throw new IOException(ex.Message, ex);\r
232                                         }\r
233                                 } finally {\r
234                                         if (stopwatch != null) {\r
235                                                 stopwatch.Stop();\r
236                                                 stopwatch = null;\r
237                                         }\r
238                                 }\r
239                         }\r
240                         \r
241                         // 更新日を補完\r
242                         if (File.Exists(filepath)) {\r
243                                 if (response is HttpWebResponse) {\r
244                                         File.SetLastWriteTime(filepath, ((HttpWebResponse) response).LastModified);\r
245                                 } else if (response is FtpWebResponse) {\r
246                                         File.SetLastWriteTime(filepath, ((FtpWebResponse) response).LastModified);\r
247                                 }\r
248                         }\r
249                 } finally {\r
250                         if (response != null) {\r
251                                 response.Close();\r
252                         }\r
253                         \r
254                         request = null;\r
255                         done = true;\r
256                 }\r
257         }\r
258         \r
259         protected void RaiseDownloadEvent(DownloadEventType type, long pos, long max)\r
260         {\r
261                 if (DownloadEventRaised != null) {\r
262                         DownloadEventArgs e = new DownloadEventArgs(type, string.Empty, pos, max);\r
263                         \r
264                         switch (e.Type) {\r
265                                 case DownloadEventType.CONNECTED:\r
266                                         e.TaskMessage = "接続しました";\r
267                                         break;\r
268                                 case DownloadEventType.STARTED:\r
269                                 case DownloadEventType.DOWNLOADING:\r
270                                 case DownloadEventType.COMPLETED:\r
271                                         try {\r
272                                                 e.TaskMessage = string.Format("{0} bytes ({1} %)", e.DownloadSize, (int) e.TaskProgressPercent);\r
273                                         } catch (DivideByZeroException) {\r
274                                                 e.TaskMessage = string.Format("{0} bytes", e.DownloadSize);\r
275                                         }\r
276                                         \r
277                                         \r
278                                         if (stopwatch != null && stopwatch.IsRunning && stopwatch.ElapsedMilliseconds > 3000) {\r
279                                                 long bpers = e.DownloadSize * 1000 / stopwatch.ElapsedMilliseconds;\r
280                                                 try {\r
281                                                         TimeSpan rest = TimeSpan.FromSeconds((max - e.DownloadSize) / bpers);\r
282                                                         e.TaskMessage += string.Format(" 推定残り時間:{0} ({1}/s)", rest, NaGet.Utils.FormatSize(bpers));\r
283                                                 } catch {\r
284                                                         e.TaskMessage += string.Format(" ({0}/s)", NaGet.Utils.FormatSize(bpers));\r
285                                                 }\r
286                                         }\r
287                                         \r
288                                         break;\r
289                         }\r
290                         \r
291                         DownloadEventRaised(this, e);\r
292                 }\r
293         }\r
294         \r
295         public override bool Cancelable {\r
296                 get { return !(this.Done || cancelCalled); }\r
297         }\r
298         \r
299         public override bool Cancel()\r
300         {\r
301                 if (this.Done || cancelCalled) {\r
302                         return false;\r
303                 }\r
304                 \r
305                 cancelCalled = true;\r
306                 if (request != null) {\r
307                         try {\r
308                                 request.Abort();\r
309                         } catch (WebException) {\r
310                         }\r
311                 }\r
312                 return true;\r
313         }\r
314         \r
315         /// <summary>\r
316         /// Webレスポンスからダウンロードしたファイルの名前を取得\r
317         /// </summary>\r
318         /// <param name="response"></param>\r
319         /// <returns></returns>\r
320         private string getFileNameFromWebResponse(WebResponse response)\r
321         {\r
322                 if (response is HttpWebResponse) {\r
323                         string contentDisposition = ((HttpWebResponse) response).Headers["Content-Disposition"];\r
324                         \r
325                         // TODO check license for http://www.atmarkit.co.jp/fdotnet/dotnettips/618downnoname/downnoname.html\r
326                         if (! string.IsNullOrEmpty(contentDisposition)) {\r
327                                 System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(\r
328                                         @"filename\s*=\s*(?:""(?<filename>[^""]*)""|(?<filename>[^;]*))",\r
329                                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);\r
330                                 \r
331                                 System.Text.RegularExpressions.Match m = re.Match(contentDisposition);\r
332                                 if (m.Success) {\r
333                                         return m.Groups["filename"].Value;\r
334                                 }\r
335                         }\r
336                 }\r
337                 \r
338                 return NaGet.Utils.Url2filename(response.ResponseUri.ToString());\r
339         }\r
340 }\r
341 \r
342 }\r
343 \r
344 \r