// non folder internal static async Task <(bool success, string downloadedFilePath)> DownlaodWithMegaFileAsync(string url, string downloadFileRootPath, string fileNameNoExtension, IProgress <int> progress, CancellationToken stop) { var client = new MegaApiClient(); var downloadFileLocation = ""; try { client.LoginAnonymous(); Uri fileLink = new Uri(url); INodeInfo node = await client.GetNodeFromLinkAsync(fileLink); Console.WriteLine($"Downloading {node.Name}"); var doubleProgress = new Progress <double>((p) => progress?.Report((int)p)); downloadFileLocation = GetDownloadFilePath(downloadFileRootPath, fileNameNoExtension, GetFileExtension(node.Name)); await client.DownloadFileAsync(fileLink, downloadFileLocation, doubleProgress, stop); } catch (Exception e) { Logger.Error("MinersDownloadManager", $"MegaFile error: {e.Message}"); } finally { client.Logout(); } var success = File.Exists(downloadFileLocation); return(success, downloadFileLocation); }
private async static Task FetchMegaFile(string inSaveLocation, DownloadProgressCallback delProgress) { string megaUrl = await FetchMegaUrl(); if (File.Exists(inSaveLocation)) { File.Delete(inSaveLocation); } // Because the MegaApiClient just Task.Run()s (rather than actually parking until the native events are over) // I might want to use the single-threaded API all wrapped in a single Task.Run(). Probably negligible gains // though (only save ~number of commands - 1 threadpool requests) and it could be annoying if I want to handle // user input for ex: "Do you want to retry?" MegaApiClient client = new MegaApiClient(); try { await client.LoginAnonymousAsync(); INodeInfo node = await client.GetNodeFromLinkAsync(new Uri(megaUrl)); await client.DownloadFileAsync(new Uri(megaUrl), inSaveLocation, new ProgressReporter(delProgress, node.Size)); } catch (Exception ex) { // Check to see if we can split up the errors any further. throw new CannotConnectToMegaException("", ex);; } finally { await client.LogoutAsync(); } }
internal static async Task <(bool success, string downloadedFilePath)> DownlaodWithMegaFromFolderAsync(string url, string downloadFileRootPath, string fileNameNoExtension, IProgress <int> progress, CancellationToken stop) { var client = new MegaApiClient(); var downloadFileLocation = ""; try { client.LoginAnonymous(); var splitted = url.Split('?'); var foldeUrl = splitted.FirstOrDefault(); var id = splitted.Skip(1).FirstOrDefault(); var folderLink = new Uri(foldeUrl); //INodeInfo node = client.GetNodeFromLink(fileLink); var nodes = await client.GetNodesFromLinkAsync(folderLink); var node = nodes.FirstOrDefault(n => n.Id == id); //Console.WriteLine($"Downloading {node.Name}"); var doubleProgress = new Progress <double>((p) => progress?.Report((int)p)); downloadFileLocation = GetDownloadFilePath(downloadFileRootPath, fileNameNoExtension, GetFileExtension(node.Name)); await client.DownloadFileAsync(node, downloadFileLocation, doubleProgress, stop); } catch (Exception e) { Logger.Error("MinersDownloadManager", $"MegaFolder error: {e.Message}"); } finally { client.Logout(); } var success = File.Exists(downloadFileLocation); return(success, downloadFileLocation); }
public static async Task <bool> DownloadFilesAsync(string FileName, string PathToDownload, string DeviceIP, ProgressBar PB, Label LBL) { bool b = false; try { char separator = Path.DirectorySeparatorChar; string DirToDownload = PathToDownload + "TempDL"; Directory.CreateDirectory(DirToDownload); //MessageBox.Show(lbitemsToDownload[lbFilesToDownload.SelectedIndex].FileName + " " + lbitemsToDownload[lbFilesToDownload.SelectedIndex].NomUser); string DLink = await Download.GetDLinkFromWeb(FileName); if (DLink.Equals("")) { PB.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { UpdateMessages.DownloadMsg(101, PB, LBL); })); MessageBox.Show("Could not get download link. Please try again. If the problem persists report it."); PB.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { UpdateMessages.DownloadMsg(103, PB, LBL); })); return(b); } else { PB.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { UpdateMessages.DownloadMsg(0, PB, LBL); })); SavesClass SV = new SavesClass(); SV.FileName = FileName; SV.DLCount = "1"; await Update.UpdateDLCount(SV); MegaApiClient client = new MegaApiClient(); client.LoginAnonymous(); Progress <double> ze = new Progress <double>(p => PB.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { UpdateMessages.DownloadMsg((int)p, PB, LBL); }))); await client.DownloadFileAsync(new Uri(DLink), DirToDownload + separator + FileName, ze); ZipFile.ExtractToDirectory(DirToDownload + separator + FileName, DirToDownload); File.Delete(DirToDownload + separator + FileName); PB.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { UpdateMessages.DownloadMsg(104, PB, LBL); })); b = await FTP.CopyFilesFromLocalToFTP(DeviceIP, DirToDownload); GC.Collect(); // TENGO QUE LLAMAR ESTO O NO DEJA BORRAR EL ARCHIVO ZIP PORQUE DICE QUE AUN ESTA EN USO. client.Logout(); PB.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { UpdateMessages.DownloadMsg(105, PB, LBL); })); Misc.Dir.DeleteDir(Constants.TempFolder + System.IO.Path.DirectorySeparatorChar + "TempDL"); PB.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { UpdateMessages.DownloadMsg(103, PB, LBL); })); //Misc.Utils.TryToDeleteFile(DirToDownload + "/" + FileName); return(b); } } catch (Exception e) { UpdateMessages.DownloadMsg(102, PB, LBL); MessageBox.Show("Save could not be downloaded due to the following error: " + e.Message); UpdateMessages.DownloadMsg(103, PB, LBL); return(b); } }
public Task DownloadAsync(CookieAwareWebClient client, string destination, IProgress <double> progress, CancellationToken cancellation) { if (File.Exists(destination)) { File.Delete(destination); } return(_client.DownloadFileAsync(_uri, destination, new Progress <double>(x => progress?.Report(x / 100d)), cancellation)); }
/// <summary> /// Downloads the file using the specified mega url /// </summary> /// <param name="megaUrl">The mega url</param> /// <param name="onAnswerCallback">The on answer callback</param> public async Task DownloadFileAsync(string megaUrl, Func <CallbackAnswer, Task> onAnswerCallback) { try { double downloadProgress = 0; var swUpdater = Stopwatch.StartNew(); Log.Information("Starting download from Mega. Url: {0}", megaUrl); var client = new MegaApiClient(); await client.LoginAnonymousAsync(); var fileLink = new Uri(megaUrl); var node = await client.GetNodeFromLinkAsync(fileLink); var nodeName = node.Name; Log.Debug("Downloading {0}", nodeName); IProgress <double> progressHandler = new Progress <double>(async x => { downloadProgress = x; if (swUpdater.Elapsed.Seconds < 5) { return; } swUpdater.Restart(); await onAnswerCallback(new CallbackAnswer() { CallbackAnswerMode = CallbackAnswerMode.EditMessage, CallbackAnswerText = $"Downloading Progress: {downloadProgress:.##} %" }); // await telegramService.EditMessageTextAsync($"Downloading Progress: {downloadProgress:.##} %"); // swUpdater.Start(); }); await client.DownloadFileAsync(fileLink, nodeName, progressHandler); } catch (Exception ex) { await onAnswerCallback(new CallbackAnswer() { CallbackAnswerMode = CallbackAnswerMode.SendMessage, CallbackAnswerText = $"Sesuatu kesalahan telah terjadi." }); // await telegramService.SendTextMessageAsync($"🚫 <b>Sesuatu telah terjadi.</b>\n{ex.Message}"); } }
private async Task MegaDownload(string url) { MegaApiClient.BufferSize = 16384; MegaApiClient.ReportProgressChunkSize = 1200; var client = new MegaApiClient(); //var stream = new CG.Web.MegaApiClient.WebClient(); client.LoginAnonymous(); var megaProgress = new Progress <double>(ReportProgress); if (File.Exists(Cfg.InstallPath + Halo2DownloadName)) // Remove old rar if found { File.Delete(Cfg.InstallPath + Halo2DownloadName); } await client.DownloadFileAsync(new Uri(url), Cfg.InstallPath + Halo2DownloadName, megaProgress); }
public async Task DownloadNodeAsync(SideloaderUpdateItem task, Progress <double> progress, CancellationToken cancellationToken) { await Connect(); await RetryHelper.RetryOnExceptionAsync(async() => { task.LocalFile.Delete(); try { await _client.DownloadFileAsync(task.RemoteFile, task.LocalFile.FullName, progress, cancellationToken); } catch (Exception) { // Needed to avoid partially downloaded files causing issues task.LocalFile.Delete(); throw; } }, 2, TimeSpan.FromSeconds(1), cancellationToken); }
public async Task <string> DownloadAsync(CookieAwareWebClient client, FlexibleLoaderGetPreferredDestinationCallback getPreferredDestination, FlexibleLoaderReportDestinationCallback reportDestination, Func <bool> checkIfPaused, IProgress <long> progress, CancellationToken cancellation) { try { // TODO: Resume download? var d = getPreferredDestination(_uri.OriginalString, FlexibleLoaderMetaInformation.FromLoader(this)); if (File.Exists(d.Filename)) { if (d.CanResumeDownload && new FileInfo(d.Filename).Length == TotalSize) { return(d.Filename); } File.Delete(d.Filename); } await _client.DownloadFileAsync(_uri, d.Filename, new Progress <double>(x => progress?.Report((long)((TotalSize ?? 0d) * x / 100))), cancellation); return(d.Filename); } catch (Exception e) when(IsBandwidthLimitExceeded(e)) { throw new InformativeException("Bandwidth limit exceeded", "That’s Mega.nz for you.", e); } catch (ApiException e) { WindowsHelper.ViewInBrowser(_uri); throw new InformativeException("Unsupported link", "Please download it manually.", e); } bool IsBandwidthLimitExceeded(Exception e) { if (e is AggregateException ae) { return(IsBandwidthLimitExceeded(ae.InnerException) || ae.InnerExceptions.Any(IsBandwidthLimitExceeded)); } return(e is HttpRequestException && e.Message.Contains(@"509")); } }
private async void button_Click(object sender, RoutedEventArgs e) { button.IsEnabled = false; //warning MessageBox.Show("Next you'll be asked to choose a folder. Keep in mind that if you choose \"C:\\LOL_4.20\" the result will be \"C:\\LOL_4.20\\League of Legends\""); //Select folder path = ShowFolderBrowserDialog(); //Start the download label1.Content = "Stats: Downloading ..."; var client = new MegaApiClient(); client.LoginAnonymous(); Progress <double> ze = new System.Progress <double>(p => UpdateStatus(p)); if (File.Exists(appData + "\\ze.rar")) { File.Delete(appData + "\\ze.rar"); } await client.DownloadFileAsync(new Uri("https://mega.nz/#!pFRVxBJQ!AMbsJnS9kqhvQ-tfP8QxoBikbrjlGQ4MdzNYGo0fIKM"), appData + "\\ze.rar", ze); //smaller test file https://mega.nz/#!J90AhTAI!Piq-76v6tB6l6W2HexqoN9XU8qvGdBJ6CONFMEyCPqE StartExtracting(); }
public static async Task <string> DownloadFilesAsyncForUpdate(string FileName, string PathToDownload, ProgressBar PB, Label LBL) { string filepath = null; try { char separator = Path.DirectorySeparatorChar; string DirToDownload = PathToDownload + "TempDL"; Directory.CreateDirectory(DirToDownload); //MessageBox.Show(lbitemsToDownload[lbFilesToDownload.SelectedIndex].FileName + " " + lbitemsToDownload[lbFilesToDownload.SelectedIndex].NomUser); string DLink = await Download.GetDLinkFromWeb(FileName); if (DLink.Equals("")) { PB.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { UpdateMessages.DownloadMsg(101, PB, LBL); })); MessageBox.Show("Could not get download link. Please try again. If the problem persists report it."); PB.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { UpdateMessages.DownloadMsg(103, PB, LBL); })); return(filepath); } else { PB.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { UpdateMessages.DownloadMsg(0, PB, LBL); })); MegaApiClient client = new MegaApiClient(); client.LoginAnonymous(); Progress <double> ze = new Progress <double>(p => PB.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { UpdateMessages.DownloadMsg((int)p, PB, LBL); }))); await client.DownloadFileAsync(new Uri(DLink), DirToDownload + separator + FileName, ze); ZipFile.ExtractToDirectory(DirToDownload + separator + FileName, DirToDownload); File.Delete(DirToDownload + separator + FileName); PB.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { UpdateMessages.DownloadMsg(104, PB, LBL); })); GC.Collect(); // TENGO QUE LLAMAR ESTO O NO DEJA BORRAR EL ARCHIVO ZIP PORQUE DICE QUE AUN ESTA EN USO. client.Logout(); string[] subdirectoryEntries = Directory.GetDirectories(DirToDownload + separator + "JKSV"); //With this I get Saves and ExtData (if it exists) int count = 0; foreach (string st in subdirectoryEntries) { string[] subdirectoryEntrieslv2 = Directory.GetDirectories(st); //Here I get game name foreach (string st2 in subdirectoryEntrieslv2) { string[] subdirectoryEntrieslv3 = Directory.GetDirectories(st2); //Here I get gslot name foreach (string st3 in subdirectoryEntrieslv3) { if (st3.Contains("Saves") && !st3.Contains("ExtData")) { filepath = st3.Substring(st3.IndexOf("JKSV") - 1); } } } count++; //If this is 2 then it means the save hast ExtData folder } Misc.Dir.DeleteDir(Constants.TempFolder + System.IO.Path.DirectorySeparatorChar + "TempDL"); PB.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { UpdateMessages.DownloadMsg(103, PB, LBL); })); return(filepath); } } catch (Exception e) { UpdateMessages.DownloadMsg(102, PB, LBL); MessageBox.Show("Save could not be downloaded due to the following error: " + e.Message); UpdateMessages.DownloadMsg(103, PB, LBL); return(null); } }
private async Task DownloadFileAsync(INode fileNode, Uri fileUri, INodeInfo fileNodeInfo, string path, bool overwrite, int retry = 0) //MegaApiClient is a mess, that's why we pass so many parameters { if (fileNode == null && fileNodeInfo == null) { throw new ArgumentException("fileNode or fileNodeInfo should be filled"); } if ((fileNodeInfo != null && fileUri == null) || fileNodeInfo == null && fileUri != null) { throw new ArgumentException("Both fileUri and fileNodeInfo should be filled"); } if (fileNode != null && fileNodeInfo != null) { throw new ArgumentException("Both fileNode and fileNodeInfo cannot be filled at the same time"); } INodeInfo nodeInfo = fileNode != null ? fileNode : fileNodeInfo; if (nodeInfo.Type != NodeType.File) { throw new Exception("Node is not a file"); } if (retry > 0) { try { if (File.Exists(path)) { File.Delete(path); } } catch (Exception fileDeleteException) { throw new Common.Exceptions.DownloadException($"Unable to delete corrupted file {path}", fileDeleteException); } if (retry >= _maxRetries) { throw new Common.Exceptions.DownloadException("Retries limit reached"); } await Task.Delay(retry * 2 * 1000); } _logger.Debug($"[MEGA] Downloading {nodeInfo.Name} to {path}"); long remoteFileSize = nodeInfo.Size; bool isFilesIdentical = false; if (File.Exists(path)) { if (remoteFileSize > 0) { _logger.Debug($"[MEGA] File {path} exists, size will be checked"); try { FileInfo fileInfo = new FileInfo(path); long fileSize = fileInfo.Length; if (fileSize != remoteFileSize) { string backupFilename = $"{Path.GetFileNameWithoutExtension(path)}_old_{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}{Path.GetExtension(path)}"; _logger.Warn($"[MEGA] Local and remote file sizes does not match, file {nodeInfo.Id} will be redownloaded. Old file will be backed up as {backupFilename}. Remote file size: {remoteFileSize}, local file size: {fileSize}"); File.Move(path, Path.Combine(fileInfo.DirectoryName, backupFilename)); } else { _logger.Debug($"[MEGA] File size for {path} matches"); isFilesIdentical = true; } } catch (Exception ex) { _logger.Error(ex, $"[MEGA] Error during file comparison: {ex}"); isFilesIdentical = true; //we assume that local file is identical if we can't check remote file size } } if (isFilesIdentical) { if (!overwrite) { _logger.Warn($"[MEGA] File {path} already exists and has the same file size as remote file (or remote file is not available). Skipping..."); return; } else { _logger.Warn($"[MEGA] File {path} already exists, will be overwriten!"); try { File.Delete(path); } catch (Exception ex) { throw new Common.Exceptions.DownloadException($"Unable to delete file {path}", ex); } } } } try { //warning: returns '' in drive's root if (!Directory.Exists(path)) { Directory.CreateDirectory(new FileInfo(path).DirectoryName); } } catch (Exception ex) { throw new Common.Exceptions.DownloadException($"Unable to create directory for file {path}", ex); } try { IProgress <double> progressHandler = new Progress <double>(x => _logger.Trace("Mega download progress: {0}%", x)); if (fileNode != null) { await _client.DownloadFileAsync(fileNode, path, progressHandler); } else { await _client.DownloadFileAsync(fileUri, path, progressHandler); } FileInfo fileInfo = new FileInfo(path); long fileSize = fileInfo.Length; fileInfo = null; if (remoteFileSize > 0 && fileSize != remoteFileSize) { _logger.Warn($"Downloaded file size differs from the size returned by server. Local size: {fileSize}, remote size: {remoteFileSize}. File {path} will be redownloaded."); File.Delete(path); retry++; await DownloadFileAsync(fileNode, fileUri, fileNodeInfo, path, overwrite, retry); return; } _logger.Debug($"File size check passed for: {path}"); } catch (Exception ex) { retry++; _logger.Debug(ex, $"Encountered error while trying to download {nodeInfo.Id}, retrying in {retry * 2} seconds ({_maxRetries - retry} retries left)... The error is: {ex}"); await DownloadFileAsync(fileNode, fileUri, fileNodeInfo, path, overwrite, retry); } }
private async void installBNSNOGG(object sender, RoutedEventArgs e) { _progressControl = new ProgressControl(); ProgressGrid.Visibility = Visibility.Visible; MainGrid.Visibility = Visibility.Collapsed; ProgressPanel.Children.Add(_progressControl); try { ProgressControl.updateProgressLabel("Logging into Mega anonymously..."); var client = new MegaApiClient(); await client.LoginAnonymousAsync(); if (!Directory.Exists("modpolice")) { Directory.CreateDirectory("modpolice"); } ProgressControl.updateProgressLabel("Retrieving file list..."); IEnumerable <INode> nodes = await client.GetNodesFromLinkAsync(new Uri("https://mega.nz/folder/WXhzUZ7Y#XzlqkPa8DU4X8xrILQDdZA")); INode currentNode = null; IProgress <double> progress = new Progress <double>(x => ProgressControl.updateProgressLabel(String.Format("Downloading: {0} ({1}%)", currentNode.Name, Math.Round(x)))); //Find our latest nodes for download INode bnsnogg_node = nodes.Where(x => x.Type == NodeType.File && x.Name.Contains("bnsnogg")).OrderByDescending(t => t.ModificationDate).FirstOrDefault(); if (bnsnogg_node == null) { ProgressControl.errorSadPeepo(Visibility.Visible); ProgressControl.updateProgressLabel("Error retrieving pluginloader"); } else { currentNode = bnsnogg_node; if (File.Exists(@"modpolice\" + bnsnogg_node.Name)) { File.Delete(@"modpolice\" + bnsnogg_node.Name); } ProgressControl.errorSadPeepo(Visibility.Hidden); await client.DownloadFileAsync(currentNode, @"modpolice\" + bnsnogg_node.Name, progress); } ProgressControl.updateProgressLabel("All done, logging out..."); string _BNSNOGG_VERSION = Directory.EnumerateFiles(Environment.CurrentDirectory + @"\modpolice\").Select(x => Path.GetFileName(x)) .Where(Name => Path.GetExtension(Name) == ".zip" && Name.Contains("bnsnogg")) .OrderByDescending(d => new FileInfo(d).Name) .Select(Name => Path.GetFileNameWithoutExtension(Name)).First().ToString(); ProgressControl.updateProgressLabel("Unzipping " + _BNSNOGG_VERSION); ExtractZipFileToDirectory(@".\modpolice\" + _BNSNOGG_VERSION + ".zip", @".\modpolice", true); //pluginloader x86 if (File.Exists(SystemConfig.SYS.BNS_DIR + bin_x86 + "version.dll")) { File.Delete(SystemConfig.SYS.BNS_DIR + bin_x86 + "version.dll"); } ProgressControl.updateProgressLabel("Installing bnsnogg x86"); await Task.Delay(750); File.Move(@".\modpolice\bin\version.dll", SystemConfig.SYS.BNS_DIR + bin_x86 + "version.dll"); //pluginloader x64 if (File.Exists(SystemConfig.SYS.BNS_DIR + bin_x64 + "version.dll")) { File.Delete(SystemConfig.SYS.BNS_DIR + bin_x64 + "version.dll"); } ProgressControl.updateProgressLabel("Installing bnsnogg x64"); await Task.Delay(750); File.Move(@".\modpolice\bin64\version.dll", SystemConfig.SYS.BNS_DIR + bin_x64 + "version.dll"); if (!Directory.Exists(SystemConfig.SYS.BNS_DIR + plugins_x86)) { Directory.CreateDirectory(SystemConfig.SYS.BNS_DIR + plugins_x86); } if (File.Exists(SystemConfig.SYS.BNS_DIR + plugins_x86 + "bnsnogg.dll")) { File.Delete(SystemConfig.SYS.BNS_DIR + plugins_x86 + "bnsnogg.dll"); } File.Move(@".\modpolice\bin\plugins\bnsnogg.dll", SystemConfig.SYS.BNS_DIR + plugins_x86 + "bnsnogg.dll"); if (!Directory.Exists(SystemConfig.SYS.BNS_DIR + plugins_x64)) { Directory.CreateDirectory(SystemConfig.SYS.BNS_DIR + plugins_x64); } if (File.Exists(SystemConfig.SYS.BNS_DIR + plugins_x64 + "bnsnogg.dll")) { File.Delete(SystemConfig.SYS.BNS_DIR + plugins_x64 + "bnsnogg.dll"); } File.Move(@".\modpolice\bin64\plugins\bnsnogg.dll", SystemConfig.SYS.BNS_DIR + plugins_x64 + "bnsnogg.dll"); ProgressControl.updateProgressLabel("bnsnogg successfully installed"); await Task.Delay(2000); } catch (Exception ex) { ProgressControl.errorSadPeepo(Visibility.Visible); ProgressControl.updateProgressLabel(ex.Message); await Task.Delay(7000); } try { ProgressGrid.Visibility = Visibility.Hidden; MainGrid.Visibility = Visibility.Visible; ProgressPanel.Children.Clear(); _progressControl = null; bnsnoggPlugin = new pluginFileInfo(SystemConfig.SYS.BNS_DIR + plugins_x64 + "bnsnogg.dll"); Dispatchers.labelContent(bnsnogglocalLabel, String.Format("Current: {0}", (bnsnoggPlugin != null) ? bnsnoggPlugin.modificationTime.ToString("MM-dd-yy") : "Not Installed")); } catch (Exception) { //Why are we here, is it just to suffer? } }
private async void installAdditional(object sender, RoutedEventArgs e) { string pluginName; switch (((Button)sender).Name) { case "simplemodeInstall": pluginName = "simplemodetrainingroom"; break; case "lessloadingInstall": pluginName = "lessloadingscreens"; break; default: pluginName = "highpriority"; break; } toggleControl = false; _progressControl = new ProgressControl(); ProgressGrid.Visibility = Visibility.Visible; MainGrid.Visibility = Visibility.Collapsed; ProgressPanel.Children.Add(_progressControl); try { if (!Directory.Exists("modpolice")) { Directory.CreateDirectory("modpolice"); } ProgressControl.updateProgressLabel("Logging into Mega"); var client = new MegaApiClient(); await client.LoginAnonymousAsync(); ProgressControl.updateProgressLabel("Retrieving file list..."); IEnumerable <INode> nodes = await client.GetNodesFromLinkAsync(new Uri("https://mega.nz/folder/WXhzUZ7Y#XzlqkPa8DU4X8xrILQDdZA")); INode currentNode = null; IProgress <double> progress = new Progress <double>(x => ProgressControl.updateProgressLabel(String.Format("Downloading: {0} ({1}%)", currentNode.Name, Math.Round(x)))); INode pluginNode = nodes.Where(x => x.Type == NodeType.File && x.Name.Contains(pluginName)).OrderByDescending(t => t.ModificationDate).FirstOrDefault(); if (pluginNode == null) { ProgressControl.errorSadPeepo(Visibility.Visible); ProgressControl.updateProgressLabel("Something went wrong getting the node"); await Task.Delay(5000); toggleControl = true; return; } if (File.Exists(@"modpolice\" + pluginNode.Name)) { File.Delete(@"modpolice\" + pluginNode.Name); } currentNode = pluginNode; await client.DownloadFileAsync(currentNode, @"modpolice\" + pluginNode.Name, progress); ProgressControl.updateProgressLabel("Unzipping: " + pluginNode.Name); await Task.Delay(750); Modpolice.ExtractZipFileToDirectory(@".\modpolice\" + pluginNode.Name, @".\modpolice", true); ProgressControl.updateProgressLabel("Installing " + pluginName + " x86"); await Task.Delay(750); if (!Directory.Exists(SystemConfig.SYS.BNS_DIR + plugins_x86)) { Directory.CreateDirectory(SystemConfig.SYS.BNS_DIR + plugins_x86); } //Delete the current plugin dll if (File.Exists(SystemConfig.SYS.BNS_DIR + plugins_x86 + pluginName + ".dll")) { File.Delete(SystemConfig.SYS.BNS_DIR + plugins_x86 + pluginName + ".dll"); } //Make sure there isn't a plugin dll that is in an off state if (File.Exists(SystemConfig.SYS.BNS_DIR + plugins_x86 + pluginName + ".dll.off")) { File.Delete(SystemConfig.SYS.BNS_DIR + plugins_x86 + pluginName + ".dll.off"); } File.Move(@".\modpolice\bin\plugins\" + pluginName + ".dll", SystemConfig.SYS.BNS_DIR + plugins_x86 + pluginName + ".dll"); ProgressControl.updateProgressLabel("Installing " + pluginName + " x64"); await Task.Delay(750); if (!Directory.Exists(SystemConfig.SYS.BNS_DIR + plugins_x64)) { Directory.CreateDirectory(SystemConfig.SYS.BNS_DIR + plugins_x64); } //Delete the current plugin dll if (File.Exists(SystemConfig.SYS.BNS_DIR + plugins_x64 + pluginName + ".dll")) { File.Delete(SystemConfig.SYS.BNS_DIR + plugins_x64 + pluginName + ".dll"); } //Make sure there isn't a plugin dll that is in an off state if (File.Exists(SystemConfig.SYS.BNS_DIR + plugins_x64 + pluginName + ".dll.off")) { File.Delete(SystemConfig.SYS.BNS_DIR + plugins_x64 + pluginName + ".dll.off"); } File.Move(@".\modpolice\bin64\plugins\" + pluginName + ".dll", SystemConfig.SYS.BNS_DIR + plugins_x64 + pluginName + ".dll"); ProgressControl.updateProgressLabel("All done"); await Task.Delay(750); await client.LogoutAsync(); } catch (Exception ex) { ProgressControl.errorSadPeepo(Visibility.Visible); ProgressControl.updateProgressLabel(ex.Message); await Task.Delay(7000); } try { ProgressGrid.Visibility = Visibility.Hidden; MainGrid.Visibility = Visibility.Visible; ProgressPanel.Children.Clear(); _progressControl = null; toggleControl = true; if (pluginName == "simplemodetrainingroom") { simplemodeTraining = new pluginFileInfo(SystemConfig.SYS.BNS_DIR + plugins_x86 + "simplemodetrainingroom.dll"); Dispatchers.toggleIsChecked(simplemodeToggle, true); Dispatchers.labelContent(SimplemodeCurrentLbl, String.Format("Current: {0}", (simplemodeTraining != null) ? simplemodeTraining.modificationTime.ToString("MM-dd-yy") : "Not Installed")); } else if (pluginName == "lessloadingscreens") { lessLoadingScreen = new pluginFileInfo(SystemConfig.SYS.BNS_DIR + plugins_x86 + "lessloadingscreens.dll"); Dispatchers.toggleIsChecked(lessloadingToggle, true); Dispatchers.labelContent(lessloadingCurrentLbl, String.Format("Current: {0}", (lessLoadingScreen != null) ? lessLoadingScreen.modificationTime.ToString("MM-dd-yy") : "Not Installed")); } else { highpriorityplugin = new pluginFileInfo(SystemConfig.SYS.BNS_DIR + plugins_x86 + "highpriority.dll"); Dispatchers.toggleIsChecked(HighpriorityToggle, true); Dispatchers.labelContent(HighpriorityCurrentLbl, String.Format("Current: {0}", (highpriorityplugin != null) ? highpriorityplugin.modificationTime.ToString("MM-dd-yy") : "Not Installed")); } Dispatchers.btnIsEnabled((Button)sender, false); } catch (Exception) { //F**K ASS C**T } }
private void DownloadFileFromMega(DownloadItemViewModel newDownload, string megaFileId) { bool wasCanceled = false; newDownload.PerformCancel = () => { wasCanceled = true; try { _megaDownloadCancelTokenSource?.Cancel(); } catch (Exception dex) { Logger.Error(dex); } finally { _megaDownloadCancelTokenSource?.Dispose(); _megaDownloadCancelTokenSource = null; } newDownload.OnCancel?.Invoke(); }; var client = new MegaApiClient(); client.LoginAnonymousAsync().ContinueWith((loginResult) => { if (wasCanceled) { return; // don't continue after async login since user already canceled download } if (loginResult.IsFaulted) { newDownload.OnError?.Invoke(loginResult.Exception.GetBaseException()); return; } // get nodes from mega folder Uri fileLink = new Uri($"https://mega.nz/file/{megaFileId}"); INodeInfo node = client.GetNodeFromLink(fileLink); if (wasCanceled) { return; // don't continue after async login since user already canceled download } if (node == null) { newDownload.OnError?.Invoke(new Exception($"could not find node from link {fileLink}")); client.LogoutAsync(); return; } if (File.Exists(newDownload.SaveFilePath)) { File.Delete(newDownload.SaveFilePath); //delete old temp file if it exists (throws exception otherwise) } IProgress <double> progressHandler = new Progress <double>(x => { double estimatedBytesReceived = (double)node.Size * (x / 100); UpdateDownloadProgress(newDownload, (int)x, (long)estimatedBytesReceived); }); _megaDownloadCancelTokenSource = new CancellationTokenSource(); Task downloadTask = client.DownloadFileAsync(fileLink, newDownload.SaveFilePath, progressHandler, _megaDownloadCancelTokenSource.Token); downloadTask.ContinueWith((downloadResult) => { _megaDownloadCancelTokenSource?.Dispose(); _megaDownloadCancelTokenSource = null; client.LogoutAsync(); if (downloadResult.IsCanceled) { return; } if (downloadResult.IsFaulted) { newDownload.OnError?.Invoke(downloadResult.Exception.GetBaseException()); return; } _wc_DownloadFileCompleted(client, new AsyncCompletedEventArgs(null, false, newDownload)); }); }); }
private async void installModPolice(object sender, RoutedEventArgs e) { _progressControl = new ProgressControl(); ProgressGrid.Visibility = Visibility.Visible; MainGrid.Visibility = Visibility.Collapsed; ProgressPanel.Children.Add(_progressControl); if (((Button)sender).Name == "installOnline") { try { ProgressControl.updateProgressLabel("Logging into Mega anonymously..."); var client = new MegaApiClient(); await client.LoginAnonymousAsync(); if (!Directory.Exists("modpolice")) { Directory.CreateDirectory("modpolice"); } ProgressControl.updateProgressLabel("Retrieving file list..."); IEnumerable <INode> nodes = await client.GetNodesFromLinkAsync(new Uri("https://mega.nz/folder/WXhzUZ7Y#XzlqkPa8DU4X8xrILQDdZA")); INode currentNode = null; IProgress <double> progress = new Progress <double>(x => ProgressControl.updateProgressLabel(String.Format("Downloading: {0} ({1}%)", currentNode.Name, Math.Round(x)))); //Find our latest nodes for download INode bnspatch_node = nodes.Where(x => x.Type == NodeType.File && x.Name.Contains("bnspatch")).OrderByDescending(t => t.ModificationDate).FirstOrDefault(); INode pluginloader_node = nodes.Where(x => x.Type == NodeType.File && x.Name.Contains("pluginloader")).OrderByDescending(t => t.ModificationDate).FirstOrDefault(); if (pluginloader_node == null) { ProgressControl.errorSadPeepo(Visibility.Visible); ProgressControl.updateProgressLabel("Error retrieving pluginloader"); } else { currentNode = pluginloader_node; if (File.Exists(@"modpolice\" + pluginloader_node.Name)) { File.Delete(@"modpolice\" + pluginloader_node.Name); } ProgressControl.errorSadPeepo(Visibility.Hidden); await client.DownloadFileAsync(currentNode, @"modpolice\" + pluginloader_node.Name, progress); } if (pluginloader_node == null) { ProgressControl.errorSadPeepo(Visibility.Visible); ProgressControl.updateProgressLabel("Error retrieving pluginloader"); } else { currentNode = bnspatch_node; if (File.Exists(@"modpolice\" + bnspatch_node.Name)) { File.Delete(@"modpolice\" + bnspatch_node.Name); } ProgressControl.errorSadPeepo(Visibility.Hidden); await client.DownloadFileAsync(currentNode, @"modpolice\" + bnspatch_node.Name, progress); } ProgressControl.updateProgressLabel("All done, logging out..."); } catch (Exception ex) { ProgressControl.errorSadPeepo(Visibility.Visible); ProgressControl.updateProgressLabel(ex.Message); await Task.Delay(3000); } } try { string _BNSPATCH_VERSION = Directory.EnumerateFiles(Environment.CurrentDirectory + @"\modpolice\").Select(x => Path.GetFileName(x)) .Where(Name => Path.GetExtension(Name) == ".zip" && Name.Contains("bnspatch")) .OrderByDescending(d => new FileInfo(d).Name) .Select(Name => Path.GetFileNameWithoutExtension(Name)).First().ToString(); string _PLUGINLOADER_VERSION = Directory.EnumerateFiles(Environment.CurrentDirectory + @"\modpolice\").Select(x => Path.GetFileName(x)) .Where(Name => Path.GetExtension(Name) == ".zip" && Name.Contains("pluginloader")) .OrderByDescending(d => new FileInfo(d).Name) .Select(Name => Path.GetFileNameWithoutExtension(Name)).First().ToString(); ProgressControl.updateProgressLabel("Unzipping " + _PLUGINLOADER_VERSION); ExtractZipFileToDirectory(@".\modpolice\" + _PLUGINLOADER_VERSION + ".zip", @".\modpolice", true); await Task.Delay(750); ProgressControl.updateProgressLabel("Unzipping " + _BNSPATCH_VERSION); ExtractZipFileToDirectory(@".\modpolice\" + _BNSPATCH_VERSION + ".zip", @".\modpolice", true); //pluginloader x86 if (File.Exists(SystemConfig.SYS.BNS_DIR + bin_x86 + "winmm.dll")) { File.Delete(SystemConfig.SYS.BNS_DIR + bin_x86 + "winmm.dll"); } ProgressControl.updateProgressLabel("Installing pluginloader x86"); await Task.Delay(750); File.Move(@".\modpolice\bin\winmm.dll", SystemConfig.SYS.BNS_DIR + bin_x86 + "winmm.dll"); //pluginloader x64 if (File.Exists(SystemConfig.SYS.BNS_DIR + bin_x64 + "winmm.dll")) { File.Delete(SystemConfig.SYS.BNS_DIR + bin_x64 + "winmm.dll"); } ProgressControl.updateProgressLabel("Installing pluginloader x64"); await Task.Delay(750); File.Move(@".\modpolice\bin64\winmm.dll", SystemConfig.SYS.BNS_DIR + bin_x64 + "winmm.dll"); //bnspatch x86 ProgressControl.updateProgressLabel("Checking if plugins folder exists for x86"); await Task.Delay(500); if (!Directory.Exists(SystemConfig.SYS.BNS_DIR + plugins_x86)) { Directory.CreateDirectory(SystemConfig.SYS.BNS_DIR + plugins_x86); } ProgressControl.updateProgressLabel("Installing bnspatch x86"); if (File.Exists(SystemConfig.SYS.BNS_DIR + plugins_x86 + "bnspatch.dll")) { File.Delete(SystemConfig.SYS.BNS_DIR + plugins_x86 + "bnspatch.dll"); } File.Move(@".\modpolice\bin\plugins\bnspatch.dll", SystemConfig.SYS.BNS_DIR + plugins_x86 + "bnspatch.dll"); //bnspatch x64 ProgressControl.updateProgressLabel("Checking if plugins folder exists for x64"); await Task.Delay(500); if (!Directory.Exists(SystemConfig.SYS.BNS_DIR + plugins_x64)) { Directory.CreateDirectory(SystemConfig.SYS.BNS_DIR + plugins_x64); } ProgressControl.updateProgressLabel("Installing bnspatch x64"); if (File.Exists(SystemConfig.SYS.BNS_DIR + plugins_x64 + "bnspatch.dll")) { File.Delete(SystemConfig.SYS.BNS_DIR + plugins_x64 + "bnspatch.dll"); } File.Move(@".\modpolice\bin64\plugins\bnspatch.dll", SystemConfig.SYS.BNS_DIR + plugins_x64 + "bnspatch.dll"); ProgressControl.updateProgressLabel("Searching for patches.xml"); await Task.Delay(500); if (!File.Exists(patches_xml)) { ProgressControl.updateProgressLabel("patches.xml not found, installing..."); File.WriteAllText(patches_xml, Properties.Resources.patches); } ProgressControl.updateProgressLabel("pluginloader & bnspatch successfully installed"); await Task.Delay(2000); } catch (Exception ex) { ProgressControl.errorSadPeepo(Visibility.Visible); ProgressControl.updateProgressLabel(ex.Message); await Task.Delay(7000); } try { ProgressGrid.Visibility = Visibility.Hidden; MainGrid.Visibility = Visibility.Visible; ProgressPanel.Children.Clear(); _progressControl = null; //Get the file info and display version for pluginloader pluginloader = new pluginFileInfo(SystemConfig.SYS.BNS_DIR + @"\bin\" + "winmm.dll"); Dispatchers.labelContent(pluginloaderLabel, String.Format("Current: {0}", (pluginloader != null) ? pluginloader.modificationTime.ToString("MM-dd-yy") : "Not Installed")); bnspatchPlugin = new pluginFileInfo(SystemConfig.SYS.BNS_DIR + plugins_x86 + "bnspatch.dll"); Dispatchers.labelContent(bnspatchLabel, String.Format("Current: {0}", (bnspatchPlugin != null) ? bnspatchPlugin.modificationTime.ToString("MM-dd-yy") : "Not Installed")); } catch (Exception) { //Why are we here, is it just to suffer? } //refreshSomeShit(); }
private async void installLoginHelperClick(object sender, RoutedEventArgs e) { _progressControl = new ProgressControl(); ProgressGrid.Visibility = Visibility.Visible; MainGrid.Visibility = Visibility.Collapsed; ProgressPanel.Children.Add(_progressControl); string pluginName = "loginhelper"; if (((Button)sender).Name.Contains("CHARSELECT")) { pluginName = "charselect"; } await Task.Run(async() => { try { if (!Directory.Exists("modpolice")) { Directory.CreateDirectory("modpolice"); } ProgressControl.updateProgressLabel("Logging into Mega anonymously..."); var client = new MegaApiClient(); await client.LoginAnonymousAsync(); if (!Directory.Exists("modpolice")) { Directory.CreateDirectory("modpolice"); } ProgressControl.updateProgressLabel("Retrieving file list..."); IEnumerable <INode> nodes = await client.GetNodesFromLinkAsync(new Uri("https://mega.nz/folder/4EUF2IhL#Ci1Y-sbbyw7nwwMGvHV2_w")); INode currentNode = null; IProgress <double> progress = new Progress <double>(x => ProgressControl.updateProgressLabel(String.Format("Downloading: {0} ({1}%)", currentNode.Name, Math.Round(x)))); //Find our latest nodes for download INode loginhelper_node = nodes.Where(x => x.Type == NodeType.File && x.Name.Contains(pluginName)).OrderByDescending(t => t.ModificationDate).FirstOrDefault(); if (loginhelper_node == null) { ProgressControl.errorSadPeepo(Visibility.Visible); ProgressControl.updateProgressLabel("Something went wrong getting the node"); await Task.Delay(7000); return; } if (File.Exists(@"modpolice\" + loginhelper_node.Name)) { File.Delete(@"modpolice\" + loginhelper_node.Name); } currentNode = loginhelper_node; await client.DownloadFileAsync(currentNode, @"modpolice\" + loginhelper_node.Name, progress); ProgressControl.updateProgressLabel("Unzipping: " + loginhelper_node.Name); await Task.Delay(750); Modpolice.ExtractZipFileToDirectory(@".\modpolice\" + loginhelper_node.Name, @".\modpolice", true); ProgressControl.updateProgressLabel("Installing " + pluginName + " x86"); await Task.Delay(750); if (!Directory.Exists(plugins_x86)) { Directory.CreateDirectory(plugins_x86); } ProgressControl.updateProgressLabel("Installing " + pluginName + " x86"); if (File.Exists(Path.Combine(plugins_x86, pluginName + ".dll"))) { File.Delete(Path.Combine(plugins_x86, pluginName + ".dll")); } File.Move(@".\modpolice\bin\plugins\" + pluginName + ".dll", Path.Combine(plugins_x86, pluginName + ".dll")); ProgressControl.updateProgressLabel("Installing " + pluginName + " x64"); await Task.Delay(750); if (!Directory.Exists(plugins_x64)) { Directory.CreateDirectory(plugins_x64); } ProgressControl.updateProgressLabel("Installing " + pluginName + " x64"); if (File.Exists(Path.Combine(plugins_x64, pluginName + ".dll"))) { File.Delete(Path.Combine(plugins_x64, pluginName + ".dll")); } File.Move(@".\modpolice\bin64\plugins\" + pluginName + ".dll", Path.Combine(plugins_x64, pluginName + ".dll")); if (pluginName == "loginhelper") { ProgressControl.updateProgressLabel("Searching for use-ingame-login.xml"); await Task.Delay(750); if (!File.Exists(login_xml)) { ProgressControl.updateProgressLabel("patches.xml not found, installing..."); if (!Directory.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "BnS", "patches"))) { Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "BnS", "patches")); } File.WriteAllText(login_xml, Properties.Resources.use_ingame_login); } } ProgressControl.updateProgressLabel("All done, just tidying up."); await client.LogoutAsync(); } catch (Exception ex) { ProgressControl.errorSadPeepo(Visibility.Visible); ProgressControl.updateProgressLabel(ex.Message); await Task.Delay(7000); } }); ProgressGrid.Visibility = Visibility.Hidden; MainGrid.Visibility = Visibility.Visible; ProgressPanel.Children.Clear(); _progressControl = null; //Check if loginhelper is installed loginHelper_installed = (File.Exists(Path.Combine(plugins_x86, pluginName + ".dll")) && File.Exists(Path.Combine(plugins_x64, pluginName + ".dll"))); charselect_installed = (File.Exists(Path.Combine(plugins_x86, "charselect.dll")) && File.Exists(Path.Combine(plugins_x64, "charselect.dll"))); await Task.Run(async() => await checkOnlineVersion()); }
private async void downloadClick(object sender, RoutedEventArgs e) { _progressControl = new ProgressControl(); ProgressGrid.Visibility = Visibility.Visible; MainGrid.Visibility = Visibility.Collapsed; ProgressPanel.Children.Add(_progressControl); await Task.Run(async() => { try { ProgressControl.updateProgressLabel("Logging into Mega anonymously..."); var client = new MegaApiClient(); await client.LoginAnonymousAsync(); if (!Directory.Exists("modpolice")) { Directory.CreateDirectory("modpolice"); } ProgressControl.updateProgressLabel("Retrieving file list..."); IEnumerable <INode> nodes = await client.GetNodesFromLinkAsync(new Uri("https://mega.nz/folder/WXhzUZ7Y#XzlqkPa8DU4X8xrILQDdZA")); INode currentNode = null; IProgress <double> progress = new Progress <double>(x => ProgressControl.updateProgressLabel(String.Format("Downloading: {0} ({1}%)", currentNode.Name, Math.Round(x)))); //Find our latest nodes for download INode bnspatch_node = nodes.Where(x => x.Type == NodeType.File && x.Name.Contains("bnspatch")).OrderByDescending(t => t.ModificationDate).FirstOrDefault(); INode pluginloader_node = nodes.Where(x => x.Type == NodeType.File && x.Name.Contains("pluginloader")).OrderByDescending(t => t.ModificationDate).FirstOrDefault(); if (pluginloader_node == null) { ProgressControl.errorSadPeepo(Visibility.Visible); ProgressControl.updateProgressLabel("Errorr retrieving pluginloader"); } else { currentNode = pluginloader_node; if (File.Exists(@"modpolice\" + pluginloader_node.Name)) { File.Delete(@"modpolice\" + pluginloader_node.Name); } ProgressControl.errorSadPeepo(Visibility.Hidden); await client.DownloadFileAsync(currentNode, @"modpolice\" + pluginloader_node.Name, progress); } if (pluginloader_node == null) { ProgressControl.errorSadPeepo(Visibility.Visible); ProgressControl.updateProgressLabel("Errorr retrieving pluginloader"); } else { currentNode = bnspatch_node; if (File.Exists(@"modpolice\" + bnspatch_node.Name)) { File.Delete(@"modpolice\" + bnspatch_node.Name); } ProgressControl.errorSadPeepo(Visibility.Hidden); await client.DownloadFileAsync(currentNode, @"modpolice\" + bnspatch_node.Name, progress); } ProgressControl.updateProgressLabel("All done, logging out..."); await client.LogoutAsync(); ProgressControl.updateProgressLabel("Peepo berry happy!"); Thread.Sleep(1500); } catch (Exception ex) { ProgressControl.errorSadPeepo(Visibility.Visible); ProgressControl.updateProgressLabel(ex.Message); Thread.Sleep(4000); } }); ProgressGrid.Visibility = Visibility.Hidden; MainGrid.Visibility = Visibility.Visible; ProgressPanel.Children.Clear(); _progressControl = null; }