using NLog; using System.Net; using System.Xml; namespace EgwCoreLib.Utils { /// /// Gestione update applicazioni /// 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; } /// /// Effettua download ultima versione applicativo partendo da info del maniifest.xml /// /// url del file manifest.xml con info version, url, changelog, mandatory /// /// public long DownloadLatest(string manifestRemoteUrl, string localDir, string packName) { long size = 0; // verifico directory if (!Directory.Exists(localDir)) { Directory.CreateDirectory(localDir); } string localFile = ""; string localLast = ""; string DownloadURL = ""; try { // in primis scarico update info... UpdateInfoEventArgs updateData = GetUpdateInfo(manifestRemoteUrl); if (updateData.IsUpdateAvailable) { DownloadURL = updateData.DownloadURL; localFile = string.Format(@"{0}\{1}_Build_{2}.zip", localDir, packName, updateData.CurrentVersion); localLast = string.Format(@"{0}\{1}.zip", localDir, packName); // scarica file e salva in directory locale... using (var http = new HttpClient()) { //var client = new WebClient(); //bool doAuth = !string.IsNullOrEmpty($"{userName}{passwd}"); 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)); } //client.DownloadFile(updateData.DownloadURL, localFile); // 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 DownloadLatest per URL {manifestRemoteUrl}: 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); // indico come fatto! var thisFile = new FileInfo(localLast); size = thisFile.Length; } } } } else { Log.Error($"ATTENZIONE! Installer NON disponibile | {manifestRemoteUrl}"); } } catch (Exception exc) { Log.Error($"Errore in fase di download installers | XML: {manifestRemoteUrl} | URL: {DownloadURL}{Environment.NewLine}{exc}"); } return size; } /// /// Recupera l'ultima versione disponibile /// /// URL remoto del file manifest.xml /// public UpdateInfoEventArgs GetUpdateInfo(string manifestRemoteUrl) { //bool doAuth = !string.IsNullOrEmpty($"{userName}{passwd}"); UpdateInfoEventArgs args = new UpdateInfoEventArgs(); Version CurrentVersion; bool Mandatory; XmlDocument recXml = new XmlDocument(); try { // recupero dati using (var http = new HttpClient()) { if (doAuth) { 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(manifestRemoteUrl); // lettura var data = http.GetAsync(manifestRemoteUrl).Result; var myReader = data.Content.ReadAsStreamAsync(); if (data.StatusCode != HttpStatusCode.OK) { Log.Info($"Errore in chiamata GetUpdateInfo per URL {manifestRemoteUrl}: status code: {data.StatusCode}"); } else { recXml.Load(myReader.Result); XmlNodeList recData = recXml.SelectNodes("item"); if (recData != null) { foreach (XmlNode item in recData) { XmlNode appCastVersion = item.SelectSingleNode("version"); Version.TryParse(appCastVersion?.InnerText, out CurrentVersion); args.CurrentVersion = CurrentVersion; XmlNode appCastChangeLog = item.SelectSingleNode("changelog"); args.ChangelogURL = appCastChangeLog?.InnerText; XmlNode appCastUrl = item.SelectSingleNode("url"); args.DownloadURL = appCastUrl?.InnerText; XmlNode mandatory = item.SelectSingleNode("mandatory"); Boolean.TryParse(mandatory?.InnerText, out Mandatory); args.Mandatory = Mandatory; args.IsUpdateAvailable = true; } } } } } catch (Exception exc) { Log.Info($"Eccezione in GetUpdateInfo:{Environment.NewLine}{exc}"); // metto versione = 0 + errore... args.IsUpdateAvailable = false; args.CurrentVersion = new Version("0.0.0.0"); } return args; } #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 } }