EZPPClient-Installer/EZPPClient Installer/DownloadUtil.cs

115 lines
3.2 KiB
C#

using ModernWpf.Controls;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EZPPClient_Installer
{
public class DownloadUtil
{
public static List<string> FilesToDownload(string pathToEZPP)
{
bool directoryExists = Directory.Exists(pathToEZPP);
List<string> downloadList = new List<string>();
List<MD5File> md5Files = new List<MD5File>();
try
{
using (WebClient wc = new WebClient())
{
var data = wc.DownloadString("https://new.ez-pp.farm/ezppclient?list");
string[] dataList = data.Split('\n');
foreach (string datastring in dataList)
{
if (string.IsNullOrWhiteSpace(datastring))
continue;
string[] se = datastring.Split('#');
string md5 = StripHTML(se[0]);
string name = StripHTML(se[1]);
md5Files.Add(new MD5File(name, md5));
}
}
}
catch (WebException error)
{
new ContentDialog()
{
Title = "Oops...",
Content = "A error occurred while trying to fetch all needed Files.\n" + error.Message,
PrimaryButtonText = "Okay"
}.ShowAsync();
}
if (!directoryExists)
{
foreach (MD5File md5File in md5Files)
downloadList.Add(md5File.getName());
}
else
{
foreach (MD5File md5file in md5Files)
{
string file = pathToEZPP + @"\" + md5file.getName();
bool doesExistOnPC = File.Exists(file);
if (!doesExistOnPC)
{
downloadList.Add(md5file.getName());
}
else
{
string onlineHash = md5file.getMD5();
string pcHash = MD5Util.CalculateMD5(file);
if (!string.Equals(onlineHash, pcHash))
{
downloadList.Add(md5file.getName());
}
}
}
}
#if DEBUG
MessageBox.Show(downloadList.Count + "/" + md5Files.Count + " Files need for update");
#endif
return downloadList;
}
public static async Task DownloadFiles(List<string> files, string path)
{
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
foreach(string filename in files)
{
await DownloadFile(filename, path);
}
}
private static async Task DownloadFile(string filename, string path)
{
try
{
using (WebClient wc = new WebClient())
{
wc.DownloadProgressChanged += (sender, value) => MainWindow.updateProgress(filename + " - " + value.ProgressPercentage + "% - " + Math.Round((value.BytesReceived / 1024000D), 2) + "MB/" + Math.Round((value.TotalBytesToReceive / 1024000D), 2) + "MB", value.ProgressPercentage);
await wc.DownloadFileTaskAsync(@"https://new.ez-pp.farm/ezppclient?file=" + filename, path + @"\" + filename);
}
}catch(WebException)
{
}
}
private static string StripHTML(string input)
{
return input.Replace("\r\n", "").Replace("\r", "").Replace("\n", "");
}
}
}