public MegaDownload(MegaApiClient megaClient, List <CloudFile> files, ProgressBar[] progressBars, Label[] progressLabels, int overwriteMode = 3) { progressbars = progressBars; progresslabels = progressLabels; downloads = new List <MegaFileDownload>(); OverwriteMode = overwriteMode; MegaApiClient megaApiClient = new MegaApiClient(); megaApiClient.LoginAnonymous(); downloadFolderPath = MainForm.syncFolderPath + "/New Files " + DateTime.Now.Date.ToShortDateString(); try { foreach (CloudFile file in files) { MegaFileDownload megaFileDownload = new MegaFileDownload(megaApiClient, this, file.MegaNode, downloadFolderPath + file.Path); downloadQueue.Enqueue(megaFileDownload); downloads.Add(megaFileDownload); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public formLoadModpack(Modpack m) : this() { var mega = new MegaApiClient(); mega.LoginAnonymous(); foreach (ModDL d in m.Mods) { ListViewItem lv = new ListViewItem(); lv.Text = d.Name; lv.Tag = d; var node = mega.GetNodeFromLink(d.URL); lv.SubItems.Add(BytesToString(node.Size)); lsvModDLs.Items.Add(lv); } Font temp = rtbDescription.SelectionFont; rtbDescription.SelectionFont = new Font(temp, FontStyle.Bold); rtbDescription.AppendText(m.Name + "\r\n"); rtbDescription.AppendText("by " + m.Authors + "\r\n\r\n"); rtbDescription.SelectionFont = temp; rtbDescription.AppendText(m.Description); }
// 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 void downloadFiles() { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } textBox1.Text = textBox1.Text + "\r\ndownloading the latest version..."; MegaApiClient mega = new MegaApiClient(); mega.LoginAnonymous(); Uri link = new Uri(megaLink); IEnumerable <INode> nodes = mega.GetNodesFromLink(link); foreach (INode node in nodes.Where(x => x.Type == NodeType.File)) { if (node.ParentId == "OG4B2D6S" || node.ParentId == "KSpkxCwB" || File.Exists(Path.Combine(path, node.Name))) { continue; } mega.DownloadFile(node, Path.Combine(path, node.Name)); textBox1.Text = textBox1.Text + "."; } mega.Logout(); textBox1.Text = textBox1.Text + "\r\nfinished downloading"; }
public void GenerateLinks() { string megaFolderId = FolderIDInput; if (string.IsNullOrWhiteSpace(megaFolderId)) { LinkOutput = ResourceHelper.Get(StringKey.EnterMegaFolderIdToGenerateLinks); return; } MegaApiClient client = new MegaApiClient(); client.LoginAnonymous(); IEnumerable <INode> nodes = client.GetNodesFromLink(new Uri($"https://mega.nz/{megaFolderId}")); if (nodes?.Any() == false) { LinkOutput = $"{ResourceHelper.Get(StringKey.NoLinksFoundInFolder)}: {megaFolderId}"; client.Logout(); return; } LinkOutput = ""; foreach (INode node in nodes.Where(x => x.Type == NodeType.File)) { LinkOutput += String.Format("iros://MegaSharedFolder/{0},{1},{2}\r\n", megaFolderId, node.Id, node.Name); } client.Logout(); }
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); }
private void buttonAnon_Click(object sender, EventArgs e) { try { if (_client.IsLoggedIn) { _client.Logout(); } _authInfos = null; _token = null; _client.LoginAnonymous(); if (!_client.IsLoggedIn) { throw new IOException("Client did not log in"); } DialogResult = DialogResult.Ignore; Close(); } catch (Exception ex) { MessageBox.Show("Failed to log in as an anonymous user. Please make sure that you are connected to the internet, then try again.\n\nError message: " + ex.Message, "Log in to mega.nz", MessageBoxButtons.OK, MessageBoxIcon.Error); DialogResult = DialogResult.None; } }
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); } }
static void Main(string[] args) { Config.LoadConfig(); MegaApiClient mega = new MegaApiClient(); mega.LoginAnonymous(); ScrapService scrapService = new ScrapService(mega); scrapService.CheckHealth(); }
private readonly int _maxRetries = 10; //todo: load from IUniversalDownloaderPlatformSettings public MegaDownloader(MegaCredentials credentials = null) { _client = new MegaApiClient(); if (credentials != null) { _client.Login(credentials.Email, credentials.Password); } else { _client.LoginAnonymous(); } }
public override async Task Download(Archive a, string destination) { var client = new MegaApiClient(); Utils.Status("Logging into MEGA (as anonymous)"); client.LoginAnonymous(); var fileLink = new Uri(Url); var node = client.GetNodeFromLink(fileLink); Utils.Status($"Downloading MEGA file: {a.Name}"); client.DownloadFile(fileLink, destination); }
public void DownloadFileFromUrl(string url) { var client = new MegaApiClient(); client.LoginAnonymous(); Uri fileLink = new Uri("https://mega.nz/#!bkwkHC7D!AWJuto8_fhleAI2WG0RvACtKkL_s9tAtvBXXDUp2bQk"); INodeInfo node = client.GetNodeFromLink(fileLink); Console.WriteLine($"Downloading {node.Name}"); client.DownloadFile(fileLink, node.Name); client.Logout(); }
public override async Task <bool> Verify() { var client = new MegaApiClient(); Utils.Status("Logging into MEGA (as anonymous)"); client.LoginAnonymous(); var fileLink = new Uri(Url); try { var node = client.GetNodeFromLink(fileLink); return(true); } catch (Exception) { return(false); } }
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); }
private bool DownloadMegaArchive(MEGAArchive m, bool download) { var client = new MegaApiClient(); Status("Logging into MEGA (as anonymous)"); client.LoginAnonymous(); var file_link = new Uri(m.URL); var node = client.GetNodeFromLink(file_link); if (!download) { return(true); } Status("Downloading MEGA file: {0}", m.Name); var output_path = Path.Combine(DownloadFolder, m.Name); client.DownloadFile(file_link, output_path); return(true); }
/// <summary> /// Checks if we can login to MEGA /// </summary> /// <returns>True if online, false if offline.</returns> public static bool IsMegaOnline() { try { MegaApiClient client = new MegaApiClient(); client.LoginAnonymous(); if (client.IsLoggedIn) { client.Logout(); return(true); } return(false); } catch { return(false); } }
private void Form1_Load(object sender, EventArgs e) { this.Text = "Omnibus - v" + version; //Create Tooltips for settings and download location button ToolTip toolTip1 = new ToolTip(); toolTip1.AutoPopDelay = 5000; toolTip1.InitialDelay = 1000; toolTip1.ReshowDelay = 500; toolTip1.ShowAlways = true; toolTip1.SetToolTip(this.button1, "Settings"); toolTip1.SetToolTip(this.button2, "Open Download Location"); //Set the save location to the current directory if this is the first run if (Properties.Settings.Default.DownloadLocation == "") { string path = AppDomain.CurrentDomain.BaseDirectory; Properties.Settings.Default.DownloadLocation = path; Properties.Settings.Default.Save(); } if (Properties.Settings.Default.LogLocation == "") { string path = AppDomain.CurrentDomain.BaseDirectory; Properties.Settings.Default.LogLocation = path; Properties.Settings.Default.Save(); } //Warn user to get UserAgent string and cookies on first run if (Properties.Settings.Default.UserAgent == "") { MessageBox.Show("Thank you for using Omnibus! Before you can get started, you are going to have to gather a few things. " + "Read the Setup information on github (https://github.com/fireshaper/Omnibus) for more information."); } //Log in to the MEGA client Anonymously mClient.LoginAnonymous(); }
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(); }
private void downloadMega_button_Click(object sender, EventArgs e) { maximumDownloads = (int)maximumDownloads_numericUpDown.Value; checkedFiles = new List <CloudFile>(); checkedFilesSize = 0; GetCheckedFiles((((SortedTreeModel)newFilesTreeViewAdv.Model).InnerModel as TreeModel).Nodes[0]); DialogResult dialogResult = MessageBox.Show($"Got links for {checkedFiles.Count} files [{(int)(checkedFilesSize / 1000000)} MB] Continue?", "Result", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.No) { return; } Directory.CreateDirectory(MainForm.syncFolderPath + @"\New Files " + DateTime.Now.ToShortDateString()); ProgressBar[] usedProgressBars = new ProgressBar[maximumDownloads]; Label[] usedLabels = new Label[maximumDownloads + 1]; for (int i = 0; i < maximumDownloads; i++) { usedProgressBars[i] = progressBars[i]; usedLabels[i] = progressLabels[i]; } usedLabels[maximumDownloads] = progressLabels[progressLabels.Count - 1]; if (megaApiClient == null) { megaApiClient = new MegaApiClient(); megaApiClient.LoginAnonymous(); } megaDownload = new MegaDownload(megaApiClient, checkedFiles, usedProgressBars, usedLabels, overwriteMode_comboBox.SelectedIndex); megaDownload.Start(); stopDownload_button.Enabled = true; stopDownload_button.Visible = true; }
public DownloaderResult DownloadFolder(Uri uri) { var client = new MegaApiClient(); client.LoginAnonymous(); Logger.Debug("Successfully log into mega"); try { var nodes = client.GetNodesFromLink(uri) .Where(x => x.Type == NodeType.File && x.Name.EndsWith(".rar")) .ToArray(); if (nodes.Length > 1) { throw new Exception("There's more that 1 rar file on the mega folder"); } else if (nodes.Length <= 0) { throw new Exception("There's no rar in the remote mega folder"); } Logger.Debug("Found a rar file in {0}", uri); var node = nodes[0]; var path = Path.GetTempFileName(); Logger.Debug("Downloading {0} into {1}", node.Name, path); try { using var file = File.Open(path, FileMode.Truncate); { using var downloadStream = client.Download(node); downloadStream.CopyTo(file); } file.Seek(0, 0); using var rar = new ArchiveFile(file); var dir = path + ".extracted"; Logger.Debug("Extracting into {0}", dir); Directory.CreateDirectory(dir); try { rar.Extract(dir); return(new DownloaderResult(dir, node.Name, node.Id, node.Owner, node.ModificationDate ?? node.CreationDate)); } catch { Logger.Warning("Deleting {0} before throwing", dir); Directory.Delete(dir, true); throw; } } finally { Logger.Debug("Removing temporary file {0}", path); File.Delete(path); } } finally { client.Logout(); } }
private static void Install() { try { var launcherurl = _launcherversion.Linux; var gameurl = _gameversions[_index].Linux; if (Global.IsWindows && Global.Is64bit) { launcherurl = _launcherversion.Windows64; gameurl = _gameversions[_index].Windows64; } else if (Global.IsWindows && !Global.Is64bit) { launcherurl = _launcherversion.Windows32; gameurl = _gameversions[_index].Windows32; } _status = Status.Downloading; _view.Invoke(() => { _view.SetStatus(_status); _view.SetProgress(0); _view.SetStatusText("Preparing..."); }); var client = new MegaApiClient(); client.LoginAnonymous(); if (Assembly.GetEntryAssembly().GetName().Version.ToString() != _launcherversion.Version) { _view.Invoke(() => _view.SetStatusText("Downloading Launcher...")); var temppath = Path.GetTempPath() + Guid.NewGuid().ToString(); using (var fileStream = new FileStream(temppath, FileMode.Create)) using (var downloadStream = new ProgressionStream(client.Download(new Uri(launcherurl)), SetDownloadProgress)) downloadStream.CopyTo(fileStream); _status = Status.Installing; _view.Invoke(() => { _view.SetStatus(_status); _view.SetStatusText("Updating Launcher..."); }); if (Directory.Exists(_updatepath)) { Directory.Delete(_updatepath, true); } Directory.CreateDirectory(_updatepath); ZipFile.ExtractToDirectory(temppath, _updatepath); File.Delete(temppath); if (Global.IsUnix) { Process.Start("mono", Path.Combine(Path.Combine(_basepath, UpdateLocation), "Launcher.exe")); } else { Process.Start(Path.Combine(Path.Combine(_basepath, UpdateLocation), "Launcher.exe")); } Process.GetCurrentProcess().Kill(); } if (!Directory.Exists(Path.Combine(_gamepath, _gameversions[_index].Version))) { _view.Invoke(() => _view.SetStatusText("Downloading Game...")); var temppath = Path.GetTempPath() + Guid.NewGuid().ToString(); using (var fileStream = new FileStream(temppath, FileMode.Create)) using (var downloadStream = new ProgressionStream(client.Download(new Uri(gameurl)), SetDownloadProgress)) downloadStream.CopyTo(fileStream); _status = Status.Installing; _view.Invoke(() => { _view.SetStatus(_status); _view.SetStatusText("Updating Game..."); }); if (Directory.Exists(_gamepath)) { Directory.Delete(_gamepath, true); } Directory.CreateDirectory(_gamepath); ZipFile.ExtractToDirectory(temppath, Path.Combine(_gamepath, _gameversions[_index].Version)); File.Delete(temppath); } } catch (Exception ex) { _view.Invoke(() => _view.ShowError("An error occured while trying to install the game. More Info:" + Environment.NewLine + ex)); SetDownloadProgress(100); } _status = Status.Ready; _view.Invoke(() => { _view.SetStatus(_status); _view.SetStatusText("Ready"); ReloadPlay(); }); }
void CreateJdLinkcontainer() { DirectoryInfo di = new DirectoryInfo("Links"); if (checkedFiles.Count == 0) { MessageBox.Show("No files checked!"); return; } Directory.CreateDirectory("Links"); List <JDPackage> packages = new List <JDPackage>(); if (cloudServiceType == CloudServiceType.Mega && megaApiClient == null) { megaApiClient = new MegaApiClient(); megaApiClient.LoginAnonymous(); } foreach (CloudFile file in checkedFiles) { string folderPath = file.Path.Replace(file.Name, ""); JDPackage pak; if (!packages.ConvertAll(x => x.name).Contains(folderPath)) { pak = new JDPackage(folderPath, folderPath); pak.numberId = packages.Count.ToString("D3"); pak.downloadFolder = folderPath; packages.Add(pak); File.WriteAllText("Links" + @"\" + pak.numberId, JsonConvert.SerializeObject(pak)); } else { pak = packages.Find(x => x.name == folderPath); } JDLink link; switch (cloudServiceType) { case CloudServiceType.Mega: //string downloadLink = ""; //megaApiClient.GetDownloadLink(file.MegaNode).ToString(); link = new JDLink(file.Name, file.PublicUrl.OriginalString); break; case CloudServiceType.Yadisk: YandexDiskSharp.RestClient restClient = new YandexDiskSharp.RestClient(); string downloadLink = restClient.GetPublicResourceDownloadLink(rootFolder.PublicKey, file.Path).Href.ToString(); link = new JDLink(file.Name, downloadLink); break; default: link = new JDLink(file.Name, file.PublicUrl.OriginalString); break; } link.downloadLink.size = (int)file.Size; File.WriteAllText("Links" + @"\" + pak.numberId + "_" + pak.linksCount.ToString("D3"), JsonConvert.SerializeObject(link)); pak.linksCount++; } DialogResult dialogResult = MessageBox.Show("Got links for " + (checkedFiles.Count) + " files! Continue?", "Result", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.No) { return; } Random rnd = new Random(); int number = rnd.Next(1, 9999); string rootFolderName = rootFolder.Name; foreach (char c in Path.GetInvalidFileNameChars()) { rootFolderName = rootFolderName.Replace(c.ToString(), ""); } string dirPath = @"linkcontainers\" + rootFolderName; Directory.CreateDirectory(dirPath); System.IO.Compression.ZipFile.CreateFromDirectory("Links", dirPath + @"\linkcollector" + number + ".zip"); foreach (FileInfo file in di.EnumerateFiles()) { file.Delete(); } foreach (DirectoryInfo dir in di.EnumerateDirectories()) { dir.Delete(true); } Directory.Delete("Links"); DownloadsFinishedForm downloadsFinishedForm = new DownloadsFinishedForm(dirPath, @"linkcollector" + number + ".zip created!"); downloadsFinishedForm.Show(); }
protected virtual async Task <bool> DownloadBinaryPost(TumblrPost downloadItem) { string url = Url(downloadItem); if (!CheckIfFileExistsInDB(url)) { string blogDownloadLocation = blog.DownloadLocation(); string fileLocationUrlList = FileLocationLocalized(blogDownloadLocation, downloadItem.TextFileLocation); DateTime postDate = PostDate(downloadItem); string fileName = FileName(downloadItem); string fileLocation = FileLocation(blogDownloadLocation, fileName); if (url.Contains("https://mega.nz/#")) { Uri link = new Uri(url); Crawler.MegaLinkType linkType = Crawler.MegaLinkType.Single; //Determines if the MEGA link is a folder or single file based on if the url is mega.nz/#! or mega.nz/#F Regex regType = new Regex("(http[A-Za-z0-9_/:.]*mega.nz/#(.*)([A-Za-z0-9_]*))"); foreach (Match rmatch in regType.Matches(url)) { string subStr = rmatch.Groups[2].Value[0].ToString(); if (subStr == "!") { linkType = Crawler.MegaLinkType.Single; } if (subStr == "F") { linkType = Crawler.MegaLinkType.Folder; } } MegaApiClient client = new MegaApiClient(); client.LoginAnonymous(); switch (linkType) { case Crawler.MegaLinkType.Single: INodeInfo nodeInfo = client.GetNodeFromLink(link); fileName = nodeInfo.Name; fileLocation = FileLocation(blogDownloadLocation, fileName); UpdateProgressQueueInformation(Resources.ProgressDownloadImage, fileName); if (await DownloadBinaryFile(fileLocation, fileLocationUrlList, url)) { updateBlog(fileLocation, postDate, downloadItem, fileName); return(true); } client.Logout(); return(false); case Crawler.MegaLinkType.Folder: //If the link is a folder, download all files from it. IEnumerable <INode> nodes = client.GetNodesFromLink(link); List <INode> allFiles = nodes.Where(n => n.Type == NodeType.File).ToList(); foreach (INode node in allFiles) { fileName = node.Name; fileLocation = FileLocation(blogDownloadLocation, fileName); UpdateProgressQueueInformation(Resources.ProgressDownloadImage, fileName); if (await DownloadBinaryFile(fileLocation, fileLocationUrlList, url, node)) { updateBlog(fileLocation, postDate, downloadItem, fileName); } } client.Logout(); return(false); default: throw new ArgumentOutOfRangeException(); } } if (url.Contains("https://drive.google.com/")) { UserCredential credentials = Authenticate(); DriveService service = OpenService(credentials); RequestInfo(service, url, blogDownloadLocation + "\\"); } UpdateProgressQueueInformation(Resources.ProgressDownloadImage, fileName); if (await DownloadBinaryFile(fileLocation, fileLocationUrlList, url)) { updateBlog(fileLocation, postDate, downloadItem, fileName); return(true); } return(false); } else { string fileName = FileName(downloadItem); UpdateProgressQueueInformation(Resources.ProgressSkipFile, fileName); } return(true); }
/// <summary> /// Perform the database download /// </summary> /// <param name="url"></param> /// <param name="path"></param> /// <param name="username"></param> /// <param name="password"></param> private void InternalDownloadDatabase(string url, string path, string username = null, string password = null) { string error = null; var client = new MegaApiClient(); try { INode database = null; if (username is null) { client.LoginAnonymous(); database = client.GetNodesFromLink(new Uri(url)).Where(x => x.Name.EndsWith(".crypt")) .OrderByDescending(x => x.CreationDate) .FirstOrDefault(); } else { client.Login(username, password); database = client.GetNodes().Where(x => x.Name != null && x.Name.EndsWith(".crypt")) .OrderByDescending(x => x.CreationDate) .FirstOrDefault(); } if (database is null) { error = "CantFindFile"; } else { using (var stream = client.Download(database)) { using (var fileStream = File.Create(path)) { stream.CopyTo(fileStream); } } } } catch (ApiException) { error = "ApiError"; } catch (UriFormatException) { error = "InvalidUrl"; } catch (ArgumentException) { error = "InvalidUrl"; } catch (IOException) { error = "CantDownloadFile"; } catch (Exception) { error = "ApiError"; } finally { if (client.IsLoggedIn) { client.Logout(); } } DatabaseDownloadEnded?.Invoke(this, new DatabaseDownloadEndedEventArgs(string.IsNullOrEmpty(error), path, error)); }
// TODO: Needs a complete rewrite. Also a append/cache function for resuming incomplete files on the disk. // Should be in separated class with support for events for downloadspeed, is resumable file?, etc. // Should check if file is complete, else it will trigger an WebException -- 416 requested range not satisfiable at every request public async Task <bool> DownloadFileWithResumeAsync(string url, string destinationPath, INode node = null) { long totalBytesReceived = 0; int attemptCount = 0; int bufferSize = settings.BufferSize * 4096; if (File.Exists(destinationPath)) { //temporary method for checking downloaded file if (url.Contains("https://mega.nz/#")) { return(true); } if (url.Contains("https://drive.google.com/")) { return(true); } FileInfo fileInfo = new FileInfo(destinationPath); totalBytesReceived = fileInfo.Length; if (totalBytesReceived >= await CheckDownloadSizeAsync(url)) { return(true); } } if (ct.IsCancellationRequested) { return(false); } FileMode fileMode = totalBytesReceived > 0 ? FileMode.Append : FileMode.Create; using (FileStream fileStream = new FileStream(destinationPath, fileMode, FileAccess.Write, FileShare.Read, bufferSize, true)) { while (true) { attemptCount += 1; if (attemptCount > settings.MaxNumberOfRetries) { return(false); } CancellationTokenRegistration requestRegistration = new CancellationTokenRegistration(); try { if (url.Contains("https://mega.nz/#")) { MegaApiClient client = new MegaApiClient(); client.LoginAnonymous(); Uri link = new Uri(url); Stream stream = node != null?client.Download(node) : client.Download(link); long totalBytesToReceive; totalBytesToReceive = totalBytesReceived + stream.Length; using (Stream throttledStream = GetStreamForDownload(stream)) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = await throttledStream.ReadAsync(buffer, 0, buffer.Length, ct)) > 0) { await fileStream.WriteAsync(buffer, 0, bytesRead); totalBytesReceived += bytesRead; } } if (totalBytesReceived >= totalBytesToReceive) { break; } //client.Logout(); } else { HttpWebRequest request = CreateWebReqeust(url); requestRegistration = ct.Register(() => request.Abort()); request.AddRange(totalBytesReceived); long totalBytesToReceive = 0; using (WebResponse response = await request.GetResponseAsync()) { totalBytesToReceive = totalBytesReceived + response.ContentLength; using (Stream responseStream = response.GetResponseStream()) { using (Stream throttledStream = GetStreamForDownload(responseStream)) { byte[] buffer = new byte[4096]; int bytesRead = 0; //Stopwatch sw = Stopwatch.StartNew(); while ((bytesRead = await throttledStream.ReadAsync(buffer, 0, buffer.Length, ct)) > 0) { await fileStream.WriteAsync(buffer, 0, bytesRead); totalBytesReceived += bytesRead; //float currentSpeed = totalBytesReceived / (float)sw.Elapsed.TotalSeconds; //OnProgressChanged(new DownloadProgressChangedEventArgs(totalBytesReceived, // totalBytesToReceive, (long)currentSpeed)); } } } } if (totalBytesReceived >= totalBytesToReceive) { break; } } } catch (IOException ioException) { // file in use long win32ErrorCode = ioException.HResult & 0xFFFF; if ((win32ErrorCode == 0x21) || (win32ErrorCode == 0x20)) { return(false); } // retry (IOException: Received an unexpected EOF or 0 bytes from the transport stream) } catch (WebException webException) { if (webException.Status == WebExceptionStatus.ConnectionClosed) { // retry } else { throw; } } finally { requestRegistration.Dispose(); } } return(true); } }
public static void DownloadReferenceUrl(Launcher.Game game, bool clearCache = true) { string displayName; if (game.Name.Length > 0) { displayName = game.Name; } else { displayName = game.ID; } string workingDir = ""; if (game.Root == "roms" || game.Root == "data") { workingDir = Path.Combine(Launcher.rootDir, "nulldc-1-0-4-en-win", game.Root); } else { Console.WriteLine("no valid root found in reference entry"); return; } var di = new DirectoryInfo(workingDir); di.Attributes |= FileAttributes.Normal; var zipPath = Path.Combine(workingDir, $"{Path.GetFileNameWithoutExtension(game.ReferenceUrl)}.zip"); if (!File.Exists(zipPath)) { Console.WriteLine($"Downloading {displayName}..."); var referenceUri = new Uri(game.ReferenceUrl); if (referenceUri.Host == "mega.nz") { MegaApiClient client = new MegaApiClient(); client.LoginAnonymous(); INodeInfo node = client.GetNodeFromLink(referenceUri); Console.WriteLine($"Downloading {node.Name}"); client.DownloadFile(referenceUri, zipPath); client.Logout(); } else { using (WebClient client = new WebClient()) { Console.WriteLine($"Downloading {Path.GetFileName(referenceUri.LocalPath)}"); client.DownloadFile(referenceUri, zipPath); } } Console.WriteLine($"Download Complete"); } Console.WriteLine($"Extracting...\n"); string extractPath; if (game.Root == "roms") { extractPath = Path.Combine(workingDir, displayName); Directory.CreateDirectory(extractPath); } else { extractPath = workingDir; } using (ZipArchive archive = ZipFile.OpenRead(zipPath)) { List <Launcher.Asset> files = game.Assets; foreach (ZipArchiveEntry entry in archive.Entries) { try { var fileEntry = files.Where(f => f.Name == entry.Name).First(); if (fileEntry != null) { var destinationFile = Path.Combine(extractPath, fileEntry.LocalName()); entry.ExtractToFile(destinationFile, true); Console.WriteLine(fileEntry.VerifyFile(destinationFile)); } } catch (Exception) { } } } if (clearCache) { File.Delete(zipPath); } Console.WriteLine($"\nPress any key to continue."); Console.ReadKey(); }
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 static void ExecuteService(int option, string infoAdditional, string infoAdditional2) { try { MegaApiClient mega = new MegaApiClient(); mega.LoginAnonymous(); MainServices services = new MainServices(mega); switch (option) { case 0: //Bajar últimos services.DownloadNews(); break; case 1: //Descarga Fichero if (!string.IsNullOrEmpty(infoAdditional)) //Path { services.DownloadComicsFile(infoAdditional); } break; case 2: //Renombra comics en la carpeta Download if (!string.IsNullOrEmpty(infoAdditional)) //Path { services.RenameFiles(infoAdditional); } break; case 3: //Lista Colecciones, nombres de colleciones services.ListCollections(); break; case 4: //Arbol de directorios if (!string.IsNullOrEmpty(infoAdditional)) //Path { DirectoryInfo rootDir = new DirectoryInfo(infoAdditional); services.TreeDirectory(rootDir, new List <string>()); } break; case 5: //Fichero por collecion, con todos los nombres y links (TODAS) services.ListCollections(Constantes.File); break; case 6: //Fichero por lista, con todos los nombres y links (UNA) if (!string.IsNullOrEmpty(infoAdditional)) //Url { services.ReadCollection(infoAdditional); } break; case 7: //Segunda revision de los descargados if (!string.IsNullOrEmpty(infoAdditional) && !string.IsNullOrEmpty(infoAdditional2)) //File and Path { services.ReviewNoDownload(infoAdditional, infoAdditional2); } break; default: return; } mega.Logout(); } catch (Exception ex) { if (logger != null) { logger.Error(string.Format("Error en el método: '{0}', Mensaje de error: '{1}'", MethodBase.GetCurrentMethod().Name, ex.Message)); } } }