DownloadCommand = new Command( execute: async () => { try { IsBusyBusyIndicator = true; await Task.Delay(1000); IsEnabledDownloadCommand = false; var checkedFiles = FilesSource.Where(x => x.IsChecked == true && x.IsFolder != null).ToList(); if (checkedFiles.Count == 0) { IsOpenPopup = true; PopupBorderColor = Color.FromRgb(255, 0, 0); ErrorMessage = $"No files or folder checked to download."; _logger.Error(ErrorMessage); IsBusyBusyIndicator = false; return; } if (SelectedItem == null) { IsOpenPopup = true; PopupBorderColor = Color.FromRgb(255, 0, 0); ErrorMessage = $"Please choose missing destinations directory to download at destination tree."; _logger.Error(ErrorMessage); IsBusyBusyIndicator = false; return; } if (SelectedItem != null && SelectedItem.Name == "C:\\") { IsOpenPopup = true; PopupBorderColor = Color.FromRgb(255, 0, 0); ErrorMessage = $"Can't choose C root drive as destination directory. Please choose missing destinations directory to download at destination tree."; _logger.Error(ErrorMessage); IsBusyBusyIndicator = false; return; } // Check the session token var container = new Bootstrapper().Bootstrap(); IAutomationApiClient automationApiClient = container.Resolve(); Constants.RequestBaseAddress = LoginConfigurations.GetInstance().Portal; ISessionToken sessionTokenHandeler = container.Resolve(); var isTokenActive = await automationApiClient.GetTokenActive($"{LoginConfigurations.GetInstance().Portal}/api/GSPortal/GetTokenActive", LoginConfigurations.GetInstance().SessionToken); if (!isTokenActive) { var sessionToken = await sessionTokenHandeler.GetSessionToken(LoginConfigurations.GetInstance().DevelopmentApiKey); if (string.IsNullOrEmpty(sessionToken) || sessionToken.Contains("token not available")) { await Task.Delay(1000); sessionToken = await sessionTokenHandeler.GetSessionToken(LoginConfigurations.GetInstance().DevelopmentApiKey); if (string.IsNullOrEmpty(sessionToken) || sessionToken.Contains("token not available")) { IsOpenPopup = true; PopupBorderColor = Color.FromRgb(255, 0, 0); ErrorMessage = "Session token not available , try again"; _logger.Error(ErrorMessage); return; } else { LoginConfigurations.GetInstance().SessionToken = sessionToken; } } else { LoginConfigurations.GetInstance().SessionToken = sessionToken; } } // Read rules from client configuration in DOME var desktopClientConfigurationResults = await automationApiClient.GetDesktopClientConfiguration($"{LoginConfigurations.GetInstance().Portal}/api/desktop/getDesktopConfiguartion", LoginConfigurations.GetInstance().SessionToken); if (string.IsNullOrEmpty(desktopClientConfigurationResults)) { ErrorMessage = "Get client configuration from DOME failed , please contact your system administrator for further details."; _logger.Error(ErrorMessage); return; } var desktopConfigurationFromDomeEncriptedObj = JsonConvert.DeserializeObject(desktopClientConfigurationResults); LoginConfigurations.GetInstance().DownloadExtractFileType = desktopConfigurationFromDomeEncriptedObj.DownloadExtractFileType; LoginConfigurations.GetInstance().IsDeleteFromDome = desktopConfigurationFromDomeEncriptedObj.isDeleteFromDome; if (SelectedDriveItem?.DriveInfoValue.DriveType == DriveType.Fixed || SelectedDriveItem?.DriveInfoValue.DriveType == DriveType.Network) { try { IsVisibleDownloadProgressBar = true; IsIndeterminateProgress = true; StringBuilder sbFilesIdentifiers = new StringBuilder(); foreach (var checkFile in checkedFiles) { if (checkFile.IsFolder.HasValue && checkFile.IsFolder.Value == true)//Folder { var root = PathText != SelectedPathItem.Value ? PathText.Replace(SelectedPathItem.Value, string.Empty).TrimStart('/') : string.Empty; if (root == string.Empty) { if (string.IsNullOrEmpty(sbFilesIdentifiers.ToString())) { sbFilesIdentifiers.Append(checkFile.Name); } else { sbFilesIdentifiers.Append("*gssd*" + checkFile.Name); } } else { if (string.IsNullOrEmpty(sbFilesIdentifiers.ToString())) { sbFilesIdentifiers.Append(root + "/" + checkFile.Name); } else { sbFilesIdentifiers.Append("*gssd*" + root + "/" + checkFile.Name); } } } else if (checkFile.IsFolder.HasValue && checkFile.IsFolder.Value == false)//File { if (string.IsNullOrEmpty(sbFilesIdentifiers.ToString())) { sbFilesIdentifiers.Append(checkFile.FileIdentifier); } else { sbFilesIdentifiers.Append("*gssd*" + checkFile.FileIdentifier); } } } if(string.IsNullOrEmpty(sbFilesIdentifiers.ToString())) { IsOpenPopup = true; PopupBorderColor = Color.FromRgb(255, 0, 0); ErrorMessage = $"There are no files to download"; _logger.Error(ErrorMessage); IsBusyBusyIndicator = false; return; } if (!string.IsNullOrEmpty(sbFilesIdentifiers.ToString())) { var zipPathForFolderOrPathForFile = string.Empty; await Task.Run(async () => { (Stream, string) resultsFromApi = (null, null); var container = new Bootstrapper().Bootstrap(); Constants.RequestBaseAddress = LoginConfigurations.GetInstance().Portal; IAutomationApiClient automationApiClient = container.Resolve(); resultsFromApi = await automationApiClient.PostDownloadFiles($"{LoginConfigurations.GetInstance().Portal}/api/HandleFiles/PostDownloadFiles", SelectedPathItem.Value, sbFilesIdentifiers.ToString(), true, LoginConfigurations.GetInstance().SessionToken); return Task.FromResult(resultsFromApi); }).ContinueWith(async task1 => { var results = await task1.Result; var contentStream = results.Item1; // no data return if (contentStream == null || string.IsNullOrEmpty(results.Item2)) { _logger.Error($"No data return from download for identiffiers:{sbFilesIdentifiers}"); return; } string fileNameResults = results.Item2; zipPathForFolderOrPathForFile = Path.Combine(SelectedItem.Path == null ? SelectedItem.Name.TrimEnd('\\').TrimEnd('\\') : SelectedItem.Path, fileNameResults); //Create the file from stream in destination var fileStream = File.Create(zipPathForFolderOrPathForFile); contentStream.CopyTo(fileStream); fileStream.Dispose(); contentStream.Dispose(); if (LoginConfigurations.GetInstance().DownloadExtractFileType == "zip") { // Do nothing } else if (LoginConfigurations.GetInstance().DownloadExtractFileType == "tree") { Task.Run(() => { string zipFilePath = zipPathForFolderOrPathForFile; string extractionPath = SelectedItem.Path; System.IO.Compression.ZipFile.ExtractToDirectory(zipFilePath, zipFilePath.Replace(new FileInfo(zipFilePath).Extension, string.Empty), true); if (File.Exists(zipPathForFolderOrPathForFile)) { File.Delete(zipPathForFolderOrPathForFile); } }).Wait(); } else if (LoginConfigurations.GetInstance().DownloadExtractFileType == "flatten") { string zipFilePath = zipPathForFolderOrPathForFile; string extractionPath = SelectedItem.Path == null ? SelectedItem.Name.TrimEnd('\\').TrimEnd('\\') : SelectedItem.Path;//SelectedItem.Path; using ZipArchive archive = ZipFile.OpenRead(zipFilePath); foreach (ZipArchiveEntry entry in archive.Entries) { if (entry.FullName.EndsWith('/'))//Library { continue; } string entryFileName = Path.GetFileName(entry.FullName); // Handle duplicated file names by adding a unique suffix string destFileName = Path.Combine(extractionPath, entryFileName); int count = 1; while (File.Exists(destFileName)) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(entryFileName); string fileExtension = Path.GetExtension(entryFileName); destFileName = Path.Combine(extractionPath, $"{fileNameWithoutExtension}-Copy{count}{fileExtension}"); count++; } // Extract the entry while preserving the file name entry.ExtractToFile(destFileName, overwrite: true); } } }).ContinueWith(async task2 => { if (LoginConfigurations.GetInstance().DownloadExtractFileType == "flatten") { if (File.Exists(zipPathForFolderOrPathForFile)) { File.Delete(zipPathForFolderOrPathForFile); } } if (LoginConfigurations.GetInstance().IsDeleteFromDome == "true") { var container = new Bootstrapper().Bootstrap(); Constants.RequestBaseAddress = LoginConfigurations.GetInstance().Portal; IAutomationApiClient automationApiClient = container.Resolve(); foreach (var checkedFile in checkedFiles) { if (checkedFile.IsFolder.HasValue && checkedFile.IsFolder.Value == true)//Folder { await automationApiClient.PostDeleteFolder($"{LoginConfigurations.GetInstance().Portal}/api/HandleFiles/PostDeleteFolder", SelectedPathItem.Value, checkedFile.Name, LoginConfigurations.GetInstance().SessionToken); } else if (checkedFile.IsFolder.HasValue && checkedFile.IsFolder.Value == false)//File { await automationApiClient.PostDeleteFile($"{LoginConfigurations.GetInstance().Portal}/api/HandleFiles/PostDeleteFile", SelectedPathItem.Value, checkedFile.FileIdentifier, LoginConfigurations.GetInstance().SessionToken); } } } MainThread.BeginInvokeOnMainThread( () => { IsOpenPopup = true; ErrorMessage = $"Download operation done successfully."; PopupBorderColor = Color.FromRgb(0, 255, 0); _logger.Info("Download operation done successfully."); SuccessPopupMessage = true; }); }).ConfigureAwait(false); } } catch (Exception ex) { IsOpenPopup = true; PopupBorderColor = Color.FromRgb(255, 0, 0); ErrorMessage = $"Download operation does not succeeded."; _logger.Error("DownloadCommand", ex); } finally { IsIndeterminateProgress = false; } } else if (LoginConfigurations.GetInstance().IsUserDeviceControl && SelectedDriveItem?.DriveInfoValue.DriveType == DriveType.Removable) { #if WINDOWS WindowsIdentity.RunImpersonatedAsync( ImpersonationHelper.Token, async () => { try { IsVisibleDownloadProgressBar = true; IsIndeterminateProgress = true; StringBuilder sbFilesIdentifiers = new StringBuilder(); foreach (var checkFile in checkedFiles) { if (checkFile.IsFolder.HasValue && checkFile.IsFolder.Value == true)//Folder { var root = PathText != SelectedPathItem.Value ? PathText.Replace(SelectedPathItem.Value, string.Empty).TrimStart('/') : string.Empty; if (root == string.Empty) { if (string.IsNullOrEmpty(sbFilesIdentifiers.ToString())) { sbFilesIdentifiers.Append(checkFile.Name); } else { sbFilesIdentifiers.Append("*gssd*" + checkFile.Name); } } else { if (string.IsNullOrEmpty(sbFilesIdentifiers.ToString())) { sbFilesIdentifiers.Append(root + "/" + checkFile.Name); } else { sbFilesIdentifiers.Append("*gssd*" + root + "/" + checkFile.Name); } } } else if (checkFile.IsFolder.HasValue && checkFile.IsFolder.Value == false)//File { if (string.IsNullOrEmpty(sbFilesIdentifiers.ToString())) { sbFilesIdentifiers.Append(checkFile.FileIdentifier); } else { sbFilesIdentifiers.Append("*gssd*" + checkFile.FileIdentifier); } } } if(string.IsNullOrEmpty(sbFilesIdentifiers.ToString())) { IsOpenPopup = true; PopupBorderColor = Color.FromRgb(255, 0, 0); ErrorMessage = $"There are no files to download"; _logger.Error(ErrorMessage); IsBusyBusyIndicator = false; return; } if (!string.IsNullOrEmpty(sbFilesIdentifiers.ToString())) { string zipPathForFolderOrPathForFile = string.Empty; await Task.Run(async () => { (Stream, string) resultsFromApi = (null, null); WindowsIdentity.RunImpersonatedAsync( ImpersonationHelper.Token, async () => { var container = new Bootstrapper().Bootstrap(); Constants.RequestBaseAddress = LoginConfigurations.GetInstance().Portal; IAutomationApiClient automationApiClient = container.Resolve(); resultsFromApi = await automationApiClient.PostDownloadFiles($"{LoginConfigurations.GetInstance().Portal}/api/HandleFiles/PostDownloadFiles", SelectedPathItem.Value, sbFilesIdentifiers.ToString(), true, LoginConfigurations.GetInstance().SessionToken); }); return Task.FromResult(resultsFromApi); }).ContinueWith(async task1 => { var results = await task1.Result; var contentStream = results.Item1; // no data return if (contentStream == null || string.IsNullOrEmpty(results.Item2)) { _logger.Error($"No data return from download for identiffiers:{sbFilesIdentifiers}"); return; } string fileNameResults = results.Item2; zipPathForFolderOrPathForFile = Path.Combine(SelectedItem.Path== null? SelectedItem.Name.TrimEnd('\\').TrimEnd('\\') : SelectedItem.Path, fileNameResults); //Create the file from stream in destination var fileStream = File.Create(zipPathForFolderOrPathForFile); contentStream.CopyTo(fileStream); fileStream.Dispose(); contentStream.Dispose(); if(LoginConfigurations.GetInstance().DownloadExtractFileType == "zip") { // Do nothing } else if (LoginConfigurations.GetInstance().DownloadExtractFileType == "tree") { Task.Run(() => { string zipFilePath = zipPathForFolderOrPathForFile; string extractionPath = SelectedItem.Path; System.IO.Compression.ZipFile.ExtractToDirectory(zipFilePath, zipFilePath.Replace(new FileInfo(zipFilePath).Extension, string.Empty), true); if (File.Exists(zipPathForFolderOrPathForFile)) { File.Delete(zipPathForFolderOrPathForFile); } }).Wait(); } else if (LoginConfigurations.GetInstance().DownloadExtractFileType == "flatten") { string zipFilePath = zipPathForFolderOrPathForFile; string extractionPath = SelectedItem.Path == null ? SelectedItem.Name.TrimEnd('\\').TrimEnd('\\'):SelectedItem.Path;//SelectedItem.Path; using ZipArchive archive = ZipFile.OpenRead(zipFilePath); foreach (ZipArchiveEntry entry in archive.Entries) { if (entry.FullName.EndsWith('/'))//Library { continue; } string entryFileName = Path.GetFileName(entry.FullName); // Handle duplicated file names by adding a unique suffix string destFileName = Path.Combine(extractionPath, entryFileName); int count = 1; while (File.Exists(destFileName)) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(entryFileName); string fileExtension = Path.GetExtension(entryFileName); destFileName = Path.Combine(extractionPath, $"{fileNameWithoutExtension}-Copy{count}{fileExtension}"); count++; } // Extract the entry while preserving the file name entry.ExtractToFile(destFileName, overwrite: true); } } }).ContinueWith(async task2 => { if (LoginConfigurations.GetInstance().DownloadExtractFileType == "flatten") { if (File.Exists(zipPathForFolderOrPathForFile)) { File.Delete(zipPathForFolderOrPathForFile); } } if(LoginConfigurations.GetInstance().IsDeleteFromDome == "true") { var container = new Bootstrapper().Bootstrap(); Constants.RequestBaseAddress = LoginConfigurations.GetInstance().Portal; IAutomationApiClient automationApiClient = container.Resolve(); foreach (var checkedFile in checkedFiles) { if (checkedFile.IsFolder.HasValue && checkedFile.IsFolder.Value == true)//Folder { await automationApiClient.PostDeleteFolder($"{LoginConfigurations.GetInstance().Portal}/api/HandleFiles/PostDeleteFolder", SelectedPathItem.Value, checkedFile.Name, LoginConfigurations.GetInstance().SessionToken); } else if (checkedFile.IsFolder.HasValue && checkedFile.IsFolder.Value == false)//File { await automationApiClient.PostDeleteFile($"{LoginConfigurations.GetInstance().Portal}/api/HandleFiles/PostDeleteFile", SelectedPathItem.Value, checkedFile.FileIdentifier, LoginConfigurations.GetInstance().SessionToken); } } } MainThread.BeginInvokeOnMainThread( () => { IsOpenPopup = true; ErrorMessage = $"Download operation done successfully."; PopupBorderColor = Color.FromRgb(0, 255, 0); _logger.Info("Download operation done successfully."); SuccessPopupMessage = true; }); }).ConfigureAwait(false); } } catch (Exception ex) { IsOpenPopup = true; PopupBorderColor = Color.FromRgb(255, 0, 0); ErrorMessage = $"Download operation does not succeeded."; _logger.Error("DownloadCommand", ex); } finally { IsIndeterminateProgress = false; } }); #endif } //Only zip else if (LoginConfigurations.GetInstance().IsUserDeviceControl && SelectedDriveItem?.DriveInfoValue.DriveType == DriveType.CDRom) { try { IsVisibleDownloadProgressBar = true; IsIndeterminateProgress = true; StringBuilder sbFilesIdentifiers = new StringBuilder(); foreach (var checkFile in checkedFiles) { if (checkFile.IsFolder.HasValue && checkFile.IsFolder.Value == true)//Folder { var root = PathText != SelectedPathItem.Value ? PathText.Replace(SelectedPathItem.Value, string.Empty).TrimStart('/') : string.Empty; if (root == string.Empty) { if (string.IsNullOrEmpty(sbFilesIdentifiers.ToString())) { sbFilesIdentifiers.Append(checkFile.Name); } else { sbFilesIdentifiers.Append("*gssd*" + checkFile.Name); } } else { if (string.IsNullOrEmpty(sbFilesIdentifiers.ToString())) { sbFilesIdentifiers.Append(root + "/" + checkFile.Name); } else { sbFilesIdentifiers.Append("*gssd*" + root + "/" + checkFile.Name); } } } else if (checkFile.IsFolder.HasValue && checkFile.IsFolder.Value == false)//File { if (string.IsNullOrEmpty(sbFilesIdentifiers.ToString())) { sbFilesIdentifiers.Append(checkFile.FileIdentifier); } else { sbFilesIdentifiers.Append("*gssd*" + checkFile.FileIdentifier); } } } if (string.IsNullOrEmpty(sbFilesIdentifiers.ToString())) { IsOpenPopup = true; PopupBorderColor = Color.FromRgb(255, 0, 0); ErrorMessage = $"There are no files to download"; _logger.Error(ErrorMessage); IsBusyBusyIndicator = false; return; } string zipPathForFolderOrPathForFile = string.Empty; if (!string.IsNullOrEmpty(sbFilesIdentifiers.ToString())) { await Task.Run(async () => { (Stream, string) resultsFromApi = (null, null); var container = new Bootstrapper().Bootstrap(); Constants.RequestBaseAddress = LoginConfigurations.GetInstance().Portal; IAutomationApiClient automationApiClient = container.Resolve(); resultsFromApi = await automationApiClient.PostDownloadFiles($"{LoginConfigurations.GetInstance().Portal}/api/HandleFiles/PostDownloadFiles", SelectedPathItem.Value, sbFilesIdentifiers.ToString(), true, LoginConfigurations.GetInstance().SessionToken); return Task.FromResult(resultsFromApi); }).ContinueWith(async task1 => { var results = await task1.Result; var contentStream = results.Item1; // no data return if (contentStream == null || string.IsNullOrEmpty(results.Item2)) { _logger.Error($"No data return from download for identifiers:{sbFilesIdentifiers}"); return; } string fileNameResults = results.Item2; string tempFolder = string.Empty; #if DEBUG await using var stream = await FileSystem.OpenAppPackageFileAsync("externalApplications.xml"); var serializer = new System.Xml.Serialization.XmlSerializer(typeof(ExternalAppsXmlData)); var result = (ExternalAppsXmlData)serializer.Deserialize(stream); tempFolder = result.ExternalApps?[2].FullPath; #else // tempFolder = Path.Combine(AppContext.BaseDirectory,"ExternalApps\\DownloadTempFolder"); tempFolder = @"C:\ProgramData\Sasa-Software\DesktopClient\ExternalApps\DownloadTempFolder"; if(!Directory.Exists(tempFolder)) { Directory.CreateDirectory(tempFolder); } #endif zipPathForFolderOrPathForFile = Path.Combine(tempFolder, fileNameResults); //Create the file from stream in destination var fileStream = File.Create(zipPathForFolderOrPathForFile); contentStream.CopyTo(fileStream); fileStream.Dispose(); contentStream.Dispose(); }).Result; IsIndeterminateProgress = false; IsBusyBusyIndicator = false; string fileArgument; if (File.Exists(zipPathForFolderOrPathForFile)) { fileArgument = zipPathForFolderOrPathForFile; string fileToExecutePath = string.Empty; #if DEBUG await using var stream = await FileSystem.OpenAppPackageFileAsync("externalApplications.xml"); var serializer = new System.Xml.Serialization.XmlSerializer(typeof(ExternalAppsXmlData)); var result = (ExternalAppsXmlData)serializer.Deserialize(stream); fileToExecutePath = result.ExternalApps?[1].FullPath; #else fileToExecutePath = Path.Combine(AppContext.BaseDirectory, "ExternalApps\\BurnMedia\\BurnMedia.exe"); #endif if (System.IO.File.Exists(fileToExecutePath)) { SecureString secureString = new SecureString(); foreach (char ch in LoginConfigurations.GetInstance().UserDeviceControlPassword) { secureString.AppendChar(ch); } ProcessStartInfo psi = new ProcessStartInfo(fileToExecutePath); psi.UseShellExecute = false; psi.CreateNoWindow = true; psi.ArgumentList.Add(fileArgument); psi.Domain = LoginConfigurations.GetInstance().UserDeviceControlDomainName; psi.UserName = LoginConfigurations.GetInstance().UserDeviceControlUserName; psi.Password = secureString; using (Process proc = Process.Start(psi)) { proc.WaitForExit(); var exitCode = proc.ExitCode; if (File.Exists(fileArgument)) { File.Delete(fileArgument); } if (exitCode == 0) { if (LoginConfigurations.GetInstance().IsDeleteFromDome == "true") { container = new Bootstrapper().Bootstrap(); Constants.RequestBaseAddress = LoginConfigurations.GetInstance().Portal; automationApiClient = container.Resolve(); foreach (var checkedFile in checkedFiles) { if (checkedFile.IsFolder.HasValue && checkedFile.IsFolder.Value == true)//Folder { await automationApiClient.PostDeleteFolder($"{LoginConfigurations.GetInstance().Portal}/api/HandleFiles/PostDeleteFolder", SelectedPathItem.Value, checkedFile.Name, LoginConfigurations.GetInstance().SessionToken); } else if (checkedFile.IsFolder.HasValue && checkedFile.IsFolder.Value == false)//File { await automationApiClient.PostDeleteFile($"{LoginConfigurations.GetInstance().Portal}/api/HandleFiles/PostDeleteFile", SelectedPathItem.Value, checkedFile.FileIdentifier, LoginConfigurations.GetInstance().SessionToken); } } } MainThread.BeginInvokeOnMainThread( () => { IsOpenPopup = true; ErrorMessage = $"Download operation done successfully."; PopupBorderColor = Color.FromRgb(0, 255, 0); _logger.Info("Download operation done successfully."); SuccessPopupMessage = true; }); } }; } else { _logger.Error("There is no executable to run."); } } } } catch (Exception ex) { IsOpenPopup = true; PopupBorderColor = Color.FromRgb(255, 0, 0); ErrorMessage = $"Download operation does not succeeded."; _logger.Error("DownloadCommand", ex); } } else if (!LoginConfigurations.GetInstance().IsUserDeviceControl && SelectedDriveItem?.DriveInfoValue.DriveType == DriveType.Removable) { try { IsVisibleDownloadProgressBar = true; IsIndeterminateProgress = true; StringBuilder sbFilesIdentifiers = new StringBuilder(); foreach (var checkFile in checkedFiles) { if (checkFile.IsFolder.HasValue && checkFile.IsFolder.Value == true)//Folder { var root = PathText != SelectedPathItem.Value ? PathText.Replace(SelectedPathItem.Value, string.Empty).TrimStart('/') : string.Empty; if (root == string.Empty) { if (string.IsNullOrEmpty(sbFilesIdentifiers.ToString())) { sbFilesIdentifiers.Append(checkFile.Name); } else { sbFilesIdentifiers.Append("*gssd*" + checkFile.Name); } } else { if (string.IsNullOrEmpty(sbFilesIdentifiers.ToString())) { sbFilesIdentifiers.Append(root + "/" + checkFile.Name); } else { sbFilesIdentifiers.Append("*gssd*" + root + "/" + checkFile.Name); } } } else if (checkFile.IsFolder.HasValue && checkFile.IsFolder.Value == false)//File { if (string.IsNullOrEmpty(sbFilesIdentifiers.ToString())) { sbFilesIdentifiers.Append(checkFile.FileIdentifier); } else { sbFilesIdentifiers.Append("*gssd*" + checkFile.FileIdentifier); } } } if (string.IsNullOrEmpty(sbFilesIdentifiers.ToString())) { IsOpenPopup = true; PopupBorderColor = Color.FromRgb(255, 0, 0); ErrorMessage = $"There are no files to download"; _logger.Error(ErrorMessage); IsBusyBusyIndicator = false; return; } if (!string.IsNullOrEmpty(sbFilesIdentifiers.ToString())) { var zipPathForFolderOrPathForFile = string.Empty; await Task.Run(async () => { (Stream, string) resultsFromApi = (null, null); var container = new Bootstrapper().Bootstrap(); Constants.RequestBaseAddress = LoginConfigurations.GetInstance().Portal; IAutomationApiClient automationApiClient = container.Resolve(); resultsFromApi = await automationApiClient.PostDownloadFiles($"{LoginConfigurations.GetInstance().Portal}/api/HandleFiles/PostDownloadFiles", SelectedPathItem.Value, sbFilesIdentifiers.ToString(), true, LoginConfigurations.GetInstance().SessionToken); return Task.FromResult(resultsFromApi); }).ContinueWith(async task1 => { var results = await task1.Result; var contentStream = results.Item1; // no data return if (contentStream == null || string.IsNullOrEmpty(results.Item2)) { _logger.Error($"No data return from download for identifiers:{sbFilesIdentifiers}"); return; } string fileNameResults = results.Item2; zipPathForFolderOrPathForFile = Path.Combine(SelectedItem.Path == null ? SelectedItem.Name.TrimEnd('\\').TrimEnd('\\') : SelectedItem.Path, fileNameResults); //Create the file from stream in destination var fileStream = File.Create(zipPathForFolderOrPathForFile); contentStream.CopyTo(fileStream); fileStream.Dispose(); contentStream.Dispose(); if (LoginConfigurations.GetInstance().DownloadExtractFileType == "zip") { // Do nothing } else if (LoginConfigurations.GetInstance().DownloadExtractFileType == "tree") { Task.Run(() => { string zipFilePath = zipPathForFolderOrPathForFile; string extractionPath = SelectedItem.Path; System.IO.Compression.ZipFile.ExtractToDirectory(zipFilePath, zipFilePath.Replace(new FileInfo(zipFilePath).Extension, string.Empty), true); if (File.Exists(zipPathForFolderOrPathForFile)) { File.Delete(zipPathForFolderOrPathForFile); } }).Wait(); } else if (LoginConfigurations.GetInstance().DownloadExtractFileType == "flatten") { string zipFilePath = zipPathForFolderOrPathForFile; string extractionPath = SelectedItem.Path == null ? SelectedItem.Name.TrimEnd('\\').TrimEnd('\\') : SelectedItem.Path;//SelectedItem.Path; using ZipArchive archive = ZipFile.OpenRead(zipFilePath); foreach (ZipArchiveEntry entry in archive.Entries) { if (entry.FullName.EndsWith('/'))//Library { continue; } string entryFileName = Path.GetFileName(entry.FullName); // Handle duplicated file names by adding a unique suffix string destFileName = Path.Combine(extractionPath, entryFileName); int count = 1; while (File.Exists(destFileName)) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(entryFileName); string fileExtension = Path.GetExtension(entryFileName); destFileName = Path.Combine(extractionPath, $"{fileNameWithoutExtension}-Copy{count}{fileExtension}"); count++; } // Extract the entry while preserving the file name entry.ExtractToFile(destFileName, overwrite: true); } } }).ContinueWith(async task2 => { if (LoginConfigurations.GetInstance().DownloadExtractFileType == "flatten") { if (File.Exists(zipPathForFolderOrPathForFile)) { File.Delete(zipPathForFolderOrPathForFile); } } if (LoginConfigurations.GetInstance().IsDeleteFromDome == "true") { var container = new Bootstrapper().Bootstrap(); Constants.RequestBaseAddress = LoginConfigurations.GetInstance().Portal; var automationApiClient = container.Resolve(); foreach (var checkedFile in checkedFiles) { if (checkedFile.IsFolder.HasValue && checkedFile.IsFolder.Value == true)//Folder { await automationApiClient.PostDeleteFolder($"{LoginConfigurations.GetInstance().Portal}/api/HandleFiles/PostDeleteFolder", SelectedPathItem.Value, checkedFile.Name, LoginConfigurations.GetInstance().SessionToken); } else if (checkedFile.IsFolder.HasValue && checkedFile.IsFolder.Value == false)//File { await automationApiClient.PostDeleteFile($"{LoginConfigurations.GetInstance().Portal}/api/HandleFiles/PostDeleteFile", SelectedPathItem.Value, checkedFile.FileIdentifier, LoginConfigurations.GetInstance().SessionToken); } } } MainThread.BeginInvokeOnMainThread( () => { IsOpenPopup = true; ErrorMessage = $"Download operation done successfully."; PopupBorderColor = Color.FromRgb(0, 255, 0); _logger.Info("Download operation done successfully."); SuccessPopupMessage = true; }); }).ConfigureAwait(false); } } catch (Exception ex) { IsOpenPopup = true; PopupBorderColor = Color.FromRgb(255, 0, 0); ErrorMessage = $"Download operation does not succeeded."; _logger.Error("DownloadCommand", ex); } finally { IsIndeterminateProgress = false; } } //Only zip without impersonation else if (!LoginConfigurations.GetInstance().IsUserDeviceControl && SelectedDriveItem?.DriveInfoValue.DriveType == DriveType.CDRom) { try { IsVisibleDownloadProgressBar = true; IsIndeterminateProgress = true; StringBuilder sbFilesIdentifiers = new StringBuilder(); foreach (var checkFile in checkedFiles) { if (checkFile.IsFolder.HasValue && checkFile.IsFolder.Value == true)//Folder { var folder = PathText.Contains('/') ? PathText.Substring(PathText.IndexOf('/'), PathText.Length - SelectedPathItem.Value.Length).TrimStart('/') : string.Empty; if (folder == checkFile.Name) { sbFilesIdentifiers.Append(checkFile.Name + "*gssd*"); } else { if (folder == string.Empty) { sbFilesIdentifiers.Append(checkFile.Name + "*gssd*"); } else { sbFilesIdentifiers.Append(folder + "/" + checkFile.Name + "*gssd*"); } } } else if (checkFile.IsFolder.HasValue && checkFile.IsFolder.Value == false)//File { sbFilesIdentifiers.Append(checkFile.FileIdentifier + "*gssd*"); } } if (string.IsNullOrEmpty(sbFilesIdentifiers.ToString())) { IsOpenPopup = true; PopupBorderColor = Color.FromRgb(255, 0, 0); ErrorMessage = $"There are no files to download"; _logger.Error(ErrorMessage); IsBusyBusyIndicator = false; return; } string zipPathForFolderOrPathForFile = string.Empty; if (!string.IsNullOrEmpty(sbFilesIdentifiers.ToString())) { await Task.Run(async () => { (Stream, string) resultsFromApi = (null, null); var container = new Bootstrapper().Bootstrap(); IAutomationApiClient automationApiClient = container.Resolve(); resultsFromApi = await automationApiClient.PostDownloadFiles($"{LoginConfigurations.GetInstance().Portal}/api/HandleFiles/PostDownloadFiles", SelectedPathItem.Value, sbFilesIdentifiers.ToString(), true, LoginConfigurations.GetInstance().SessionToken); return Task.FromResult(resultsFromApi); }).ContinueWith(async task1 => { var results = await task1.Result; var contentStream = results.Item1; // no data return if (contentStream == null || string.IsNullOrEmpty(results.Item2)) { _logger.Error($"No data return from download for identifiers:{sbFilesIdentifiers}"); return; } string fileNameResults = results.Item2; string tempFolder = string.Empty; #if DEBUG await using var stream = await FileSystem.OpenAppPackageFileAsync("externalApplications.xml"); var serializer = new System.Xml.Serialization.XmlSerializer(typeof(ExternalAppsXmlData)); var result = (ExternalAppsXmlData)serializer.Deserialize(stream); tempFolder = result.ExternalApps?[2].FullPath; #else // tempFolder = Path.Combine(AppContext.BaseDirectory, "ExternalApps\\DownloadTempFolder"); tempFolder = @"C:\ProgramData\Sasa-Software\DesktopClient\ExternalApps\DownloadTempFolder"; if(!Directory.Exists(tempFolder)) { Directory.CreateDirectory(tempFolder); } #endif zipPathForFolderOrPathForFile = Path.Combine(tempFolder, fileNameResults); //Create the file from stream in destination var fileStream = File.Create(zipPathForFolderOrPathForFile); contentStream.CopyTo(fileStream); fileStream.Dispose(); contentStream.Dispose(); if (LoginConfigurations.GetInstance().DownloadExtractFileType == "zip") { // Do nothing } else if (LoginConfigurations.GetInstance().DownloadExtractFileType == "tree") { // Do nothing } else if (LoginConfigurations.GetInstance().DownloadExtractFileType == "flatten") { // Do nothing } }).Result; IsIndeterminateProgress = false; IsBusyBusyIndicator = false; string fileArgument; if (File.Exists(zipPathForFolderOrPathForFile)) { fileArgument = zipPathForFolderOrPathForFile; string fileToExecutePath = string.Empty; #if DEBUG await using var stream = await FileSystem.OpenAppPackageFileAsync("externalApplications.xml"); var serializer = new System.Xml.Serialization.XmlSerializer(typeof(ExternalAppsXmlData)); var result = (ExternalAppsXmlData)serializer.Deserialize(stream); fileToExecutePath = result.ExternalApps?[1].FullPath; #else fileToExecutePath = Path.Combine(AppContext.BaseDirectory, "ExternalApps\\BurnMedia\\BurnMedia.exe"); #endif if (System.IO.File.Exists(fileToExecutePath)) { ProcessStartInfo psi = new ProcessStartInfo(fileToExecutePath); psi.UseShellExecute = false; psi.CreateNoWindow = true; psi.Arguments = fileArgument; using (Process proc = Process.Start(psi)) { proc.WaitForExit(); var exitCode = proc.ExitCode; if (exitCode == 0) { if (File.Exists(fileArgument)) { File.Delete(fileArgument); } if (LoginConfigurations.GetInstance().IsDeleteFromDome == "true") { container = new Bootstrapper().Bootstrap(); Constants.RequestBaseAddress = LoginConfigurations.GetInstance().Portal; automationApiClient = container.Resolve(); foreach (var checkedFile in checkedFiles) { if (checkedFile.IsFolder.HasValue && checkedFile.IsFolder.Value == true)//Folder { await automationApiClient.PostDeleteFolder($"{LoginConfigurations.GetInstance().Portal}/api/HandleFiles/PostDeleteFolder", SelectedPathItem.Value, checkedFile.Name, LoginConfigurations.GetInstance().SessionToken); } else if (checkedFile.IsFolder.HasValue && checkedFile.IsFolder.Value == false)//File { await automationApiClient.PostDeleteFile($"{LoginConfigurations.GetInstance().Portal}/api/HandleFiles/PostDeleteFile", SelectedPathItem.Value, checkedFile.FileIdentifier, LoginConfigurations.GetInstance().SessionToken); } } } MainThread.BeginInvokeOnMainThread( () => { IsOpenPopup = true; ErrorMessage = $"Download operation done successfully."; PopupBorderColor = Color.FromRgb(0, 255, 0); _logger.Info("Download operation done successfully."); SuccessPopupMessage = true; }); } }; } else { _logger.Error("There is no executable to run."); } } } } catch (Exception ex) { IsOpenPopup = true; PopupBorderColor = Color.FromRgb(255, 0, 0); ErrorMessage = $"Download operation does not succeeded."; _logger.Error("DownloadCommand", ex); } } } catch (Exception ex) { _logger.Error("DownloadExccute", ex); } finally { string tempFolder = string.Empty; #if DEBUG await using var stream = await FileSystem.OpenAppPackageFileAsync("externalApplications.xml"); var serializer = new System.Xml.Serialization.XmlSerializer(typeof(ExternalAppsXmlData)); var result = (ExternalAppsXmlData)serializer.Deserialize(stream); tempFolder = result.ExternalApps?[2].FullPath; #else // tempFolder = Path.Combine(AppContext.BaseDirectory, "ExternalApps\\DownloadTempFolder"); tempFolder = @"C:\ProgramData\Sasa-Software\DesktopClient\ExternalApps\DownloadTempFolder"; #endif if (Directory.Exists(tempFolder)) { DirectoryInfo directoryInfo = new DirectoryInfo(tempFolder); foreach (System.IO.FileInfo file in directoryInfo.GetFiles()) { file.Delete(); } foreach (System.IO.DirectoryInfo subDirectory in directoryInfo.GetDirectories()) { subDirectory.Delete(true); } } IsEnabledDownloadCommand = true; } });