using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace EgwControlCenter.Core
{
public class UpdateMan
{
#region Public Fields
///
/// Init classe
///
public static UpdateMan obj = new UpdateMan();
#endregion Public Fields
#region Public Constructors
///
/// Init classe
///
public UpdateMan()
{ }
///
/// Init classe
///
///
///
public UpdateMan(string user, string pwd)
{
userName = user;
passwd = pwd;
doAuth = !string.IsNullOrEmpty($"{userName}{passwd}");
}
#endregion Public Constructors
#region Public Methods
///
/// Effettua download specifica versione applicativo per install locale
///
/// url del file (tipicamente *.zip) da scaricare
/// Cartella locale x salvataggio file
/// Nome applicativo con cui salvare
/// Versione applicativo (per salvataggio storico versioni)
public long DownloadApp(string downloadUrl, string localDir, string packName, string version)
{
long size = 0;
// verifico directory
if (!Directory.Exists(localDir))
{
Directory.CreateDirectory(localDir);
}
string localFile = "";
string localLast = "";
try
{
localFile = Path.Combine(localDir, $"{packName}_Build_{version}.zip");
localLast = Path.Combine(localDir, $"{packName}.zip");
// scarica file e salva in directory locale...
using (var http = new HttpClient())
{
if (doAuth)
{
//client.Credentials = new System.Net.NetworkCredential(userName, passwd);
http.DefaultRequestHeaders.Accept.Clear();
var byteArray = System.Text.ASCIIEncoding.UTF8.GetBytes($"{userName}:{passwd}");
http.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
}
// url da chiamare
http.BaseAddress = new Uri(downloadUrl);
// lettura
var data = http.GetAsync(downloadUrl).Result;
using (var myReader = data.Content.ReadAsStreamAsync())
{
//var myReader = data.Content.ReadAsStreamAsync();
if (data.StatusCode != HttpStatusCode.OK)
{
Log.Info($"Errore in chiamata DownloadApp per URL {downloadUrl}: status code: {data.StatusCode}");
}
else
{
using (Stream outStream = File.OpenWrite(localFile))
{
myReader.Result.CopyTo(outStream);
}
// ora lo copio come latest...
File.Copy(localFile, localLast, true);
// recupero dimensione file
var thisFile = new FileInfo(localLast);
size = thisFile.Length;
}
}
}
}
catch (Exception exc)
{
Log.Error($"Errore in fase di download installers | URL: {downloadUrl}{Environment.NewLine}{exc}");
}
return size;
}
#endregion Public Methods
#region Private Fields
private static Logger Log = LogManager.GetCurrentClassLogger();
private bool doAuth = false;
#endregion Private Fields
#region Private Properties
private string passwd { get; set; } = "";
private string userName { get; set; } = "";
#endregion Private Properties
}
}