forked from V-Modder/SharpUpdate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSharpUpdateDownloadForm.cs
282 lines (250 loc) · 10.2 KB
/
SharpUpdateDownloadForm.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Net;
using System.Windows.Forms;
using System.Collections.Generic;
namespace SharpUpdate
{
/// <summary>
/// Form that download the update
/// </summary>
internal partial class SharpUpdateDownloadForm : Form
{
/// <summary>
/// The web client to download the update
/// </summary>
private WebClient webClient;
/// <summary>
/// The thread to hash the file on
/// </summary>
private BackgroundWorker bgWorker;
/// <summary>
/// Iterating variable in the events
/// </summary>
private int count = 0;
/// <summary>
/// Counting recieved bytes over multiple files
/// </summary>
private int bytesRecievedLastTime = 0;
/// <summary>
/// Gets the list of all temp file paths for the downloaded files
/// </summary>
internal List<SharpUpdateFileInfo> TempFilesPath
{
get { return this.files; }
}
/// <summary>
/// Holds all paths to the tempfiles
/// </summary>
private List<SharpUpdateFileInfo> files;
/// <summary>
/// Creates a new SharpUpdateDownloadForm
/// </summary>
internal SharpUpdateDownloadForm(List<SharpUpdateFileInfo> files, Icon programIcon)
{
InitializeComponent();
if (programIcon != null)
this.Icon = programIcon;
this.files = files;
this.lblDownloading.Text = SharpUpdate.LanguageFile._default.SharpUpdateDownloadForm_lblDownloading;
this.Text = SharpUpdate.LanguageFile._default.SharpUpdateDownloadForm_Title;
// Calculate the overall size and save it to progressBarAll
this.progressBarAll.Maximum = 0;
foreach (SharpUpdateFileInfo fi in this.files)
{
this.progressBarAll.Maximum += Convert.ToInt32(getSizeOfFile(fi.Url));
}
// Set the first file to download
files[count].TempFile = Path.GetTempFileName();
// Set up WebClient to download file
webClient = new WebClient();
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted);
// Set up backgroundworker to hash file
bgWorker = new BackgroundWorker();
bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
// Download file
try { webClient.DownloadFileAsync(new Uri(files[count].Url), files[count++].TempFile); }
catch { this.DialogResult = DialogResult.No; this.Close(); }
}
/// <summary>
/// Get the size of a file
/// </summary>
/// <param name="location">URL to the file</param>
/// <returns>Size of file in bytes</returns>
private static long getSizeOfFile(string location)
{
try
{
WebRequest req = HttpWebRequest.Create(location);
req.Method = "HEAD";
WebResponse resp = req.GetResponse();
long ContentLength;
if (long.TryParse(resp.Headers.Get("Content-Length"), out ContentLength))
{
resp.Close();
return ContentLength;
}
resp.Close();
return 0;
}
catch { return 0; }
}
/// <summary>
/// Downloads file from server
/// </summary>
private void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
// Update progressbars on download
this.progressBar.Value = e.ProgressPercentage;
this.progressBarAll.Value += (Convert.ToInt32(e.BytesReceived) - this.bytesRecievedLastTime);
this.bytesRecievedLastTime = Convert.ToInt32(e.BytesReceived);
this.lblProgress.Text = String.Format(SharpUpdate.LanguageFile._default.SharpUpdateDownloadForm_DownloadProgress, FormatBytes(progressBarAll.Value, 1, true), FormatBytes(progressBarAll.Maximum, 1, true));
}
/// <summary>
/// Setup webClient to download the next file or start hashing
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void webClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
this.DialogResult = DialogResult.No;
this.Close();
}
else if (e.Cancelled)
{
this.DialogResult = DialogResult.Abort;
this.Close();
}
else
{
this.progressBar.Value = 0;
this.bytesRecievedLastTime = 0;
if (this.count < files.Count)
{// Set the next file to download
// Set the temp file name and create new 0-byte file
files[count].TempFile = Path.GetTempFileName();
// Set up WebClient to download file
webClient = new WebClient();
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted);
// Set up backgroundworker to hash file
bgWorker = new BackgroundWorker();
bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
// Download file
try { webClient.DownloadFileAsync(new Uri(files[count].Url), files[count++].TempFile); }
catch { this.DialogResult = DialogResult.No; this.Close(); }
}
else
{// Set the first file to hash
// Show the "Hashing" label and set the progressbar to marquee
this.lblProgress.Text = SharpUpdate.LanguageFile._default.SharpUpdateDownloadForm_DownloadsFinished;
this.progressBar.Style = ProgressBarStyle.Marquee;
this.count = 0;
// Start the hashing
bgWorker.RunWorkerAsync(new string[] { this.files[count].TempFile, this.files[count++].Md5 });
}
}
}
/// <summary>
/// Formats the byte count to closest byte type
/// </summary>
/// <param name="bytes">The amount of bytes</param>
/// <param name="decimalPlaces">How many decimal places to show</param>
/// <param name="showByteType">Add the byte type on the end of the string</param>
/// <returns>The bytes formatted as specified</returns>
private string FormatBytes(long bytes, int decimalPlaces, bool showByteType)
{
double newBytes = bytes;
string formatString = "{0";
string byteType = "B";
// Check if best size in KB
if (newBytes > 1024 && newBytes < 1048576)
{
newBytes /= 1024;
byteType = "KB";
}
else if (newBytes > 1048576 && newBytes < 1073741824)
{
// Check if best size in MB
newBytes /= 1048576;
byteType = "MB";
}
else
{
// Best size in GB
newBytes /= 1073741824;
byteType = "GB";
}
// Show decimals
if (decimalPlaces > 0)
formatString += ":0.";
// Add decimals
for (int i = 0; i < decimalPlaces; i++)
formatString += "0";
// Close placeholder
formatString += "}";
// Add byte type
if (showByteType)
formatString += byteType;
return String.Format(formatString, newBytes);
}
/// <summary>
/// Hash file and compare
/// </summary>
/// <param name="sender"></param>
/// <param name="e">string[2] {FILENAME, MD5}</param>
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
string file = ((string[])e.Argument)[0];
string updateMD5 = ((string[])e.Argument)[1];
// Hash the file and compare to the hash in the update xml
if (Hasher.HashFile(file, HashType.MD5) != updateMD5)
e.Result = DialogResult.No;
else
e.Result = DialogResult.OK;
}
/// <summary>
/// Check if all files are ok and start next
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if ((DialogResult)e.Result != DialogResult.OK)
{
this.DialogResult = (DialogResult)e.Result;
this.Close();
}
else
{
if (count < files.Count)
bgWorker.RunWorkerAsync(new string[] { this.files[count].TempFile, this.files[count++].Md5 });
else
{
this.DialogResult = DialogResult.OK;
this.Close();
}
}
}
private void SharpUpdateDownloadForm_FormClosed(object sender, FormClosedEventArgs e)
{
if (webClient.IsBusy)
{
webClient.CancelAsync();
this.DialogResult = DialogResult.Abort;
}
if (bgWorker.IsBusy)
{
bgWorker.CancelAsync();
this.DialogResult = DialogResult.Abort;
}
}
}
}