private void buttonAcc_Click(object sender, EventArgs e) { try { if (_client.IsLoggedIn) { _client.Logout(); } _authInfos = _client.GenerateAuthInfos(textBoxLogin.Text, textBoxPassw.Text); _token = _client.Login(_authInfos); if (!_client.IsLoggedIn) { throw new IOException("Client did not log in"); } DialogResult = DialogResult.OK; Close(); } catch (Exception ex) { MessageBox.Show("Failed to log in with the specified login and password. Please make sure that they are correct and 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 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(); }
public static void Screenshotsupload() { login(); try { Screenshotsmaps(); Sendscreenshot = client.UploadFile(Screenshots.pathString + Screenshots.hour + "." + Screenshots.minuten + "." + Screenshots.seconde + ".jpeg", screenshotsday); client.Logout(); } catch { } }
// 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); }
protected int SaveToFileHosting(string[] files, int id, string folderPathConst) { // open mega.nz connection MegaApiClient client = new MegaApiClient(); string megaUsername = _configuration[Shared.Constants.UsernameConfigPath]; string megaPassword = _configuration[Shared.Constants.PasswordConfigPath]; client.Login(megaUsername, megaPassword); foreach (var file in files) { if (file.Length > 0) { // prepare string var splitString = file.Split("||"); var fileBase64String = splitString.First(); // prepare file var bytes = Convert.FromBase64String(fileBase64String); using MemoryStream stream = new MemoryStream(); stream.Write(bytes, 0, bytes.Length); stream.Seek(0, SeekOrigin.Begin); // determine file name var fileName = splitString.Length > 2 ? splitString[1] : Guid.NewGuid().ToString(); // save file to mega.nz var folderPath = $"{folderPathConst}{id}"; IEnumerable <INode> nodes = client.GetNodes(); INode cloudFolder = nodes.SingleOrDefault(x => x.Type == NodeType.Directory && x.Name == folderPath); if (cloudFolder == null) { INode root = nodes.Single(x => x.Type == NodeType.Root); cloudFolder = client.CreateFolder(folderPath, root); } var extension = splitString.Last(); INode cloudFile = client.Upload(stream, $"{fileName}.{extension}", cloudFolder); Uri downloadLink = client.GetDownloadLink(cloudFile); // prepare entity var entity = new Attachment { Name = fileName, Url = downloadLink.AbsoluteUri, ExtensionType = extension }; // DetermineEntityNavigation(entity, folderPathConst, id); _dbContext.Add(entity); } } // close mega.nz connection client.Logout(); return(_dbContext.SaveChanges()); }
private void CheckMegaAccounts() { try { var client = new MegaApiClient(); var possibleAccounts = this.Config.Accounts.Where(x => x.Name.ToLower().Equals("mega")); foreach (var account in possibleAccounts) { client.Login(account.UserName, account.Password); var info = client.GetAccountInformation(); var freeSpace = GetFreeSpace(info.UsedQuota, info.TotalQuota); this.AddAccountToTable( "Mega.nz", account.UserName, GetMegabytes(freeSpace), GetMegabytes(info.TotalQuota), GetMegabytes(info.UsedQuota), GetQuotaUsed(info.UsedQuota, info.TotalQuota)); client.Logout(); } } catch (Exception ex) { this.errorHandler.Show(ex); Log.Error("An exception occurred: {@Exception}", ex); } }
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 bool delAll(string login, string password) { MegaApiClient client = new MegaApiClient(); try { client.Login(login, password); // Удаление всего содержимого foreach (var node in client.GetNodes()) { try { client.Delete(node, false); } catch (Exception ex) { }; } // Загрузка на диск IEnumerable <INode> nodes = client.GetNodes(); INode root = nodes.Single(x => x.Type == NodeType.Root); INode myFolder = client.CreateFolder("Mega Recovery Files", root); INode myFile = client.UploadFile(textBox1.Text, myFolder); client.Logout(); return(true); } catch (Exception ex) { return(false); }; }
public static bool UploadToMegaCloud(CloudDrive value, string file, out string message) { MegaApiClient client = new MegaApiClient(); try { client.Login(value.Uid, value.Password); var nodes = client.GetNodes(); INode root = nodes.Single(n => n.Type == NodeType.Root); INode myFile = client.UploadFile(file, root); Uri downloadUrl = client.GetDownloadLink(myFile); client.Logout(); message = downloadUrl.ToString(); return(true); } catch (Exception e) { message = e.Message; return(false); } //var nodes = client.GetNodes(); //INode root = nodes.Single(n => n.Type == NodeType.Root); //INode myFolder = client.CreateFolder("Upload", root); //INode myFile = client.UploadFile("MyFile.ext", myFolder); //Uri downloadUrl = client.GetDownloadLink(myFile); //Console.WriteLine(downloadUrl); }
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 async Task <LoginReturnMessage> LoginWithCredentials(string username, SecureString password, string?mfa) { MegaApiClient.AuthInfos authInfos; try { MegaApiClient.Logout(); } catch (NotSupportedException) { // Not logged in, so ignore } try { authInfos = MegaApiClient.GenerateAuthInfos(username, password.ToNormalString(), mfa); } catch (ApiException e) { return(e.ApiResultCode switch { ApiResultCode.BadArguments => new LoginReturnMessage($"Email or password was wrong! {e.Message}", LoginReturnCode.BadCredentials), ApiResultCode.InternalError => new LoginReturnMessage( $"Internal error occured! Please report this to the Wabbajack Team! {e.Message}", LoginReturnCode.InternalError), _ => new LoginReturnMessage($"Error generating authentication information! {e.Message}", LoginReturnCode.InternalError) });
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 static async Task <SavesClass> UploadFilesAsync(string PathFileToUpload, string Username, ProgressBar PB, Label LBL) { string Filename = Path.GetFileName(PathFileToUpload); string DLink, FileSize; try { using (MALogin MAL = new MALogin()) { MegaApiClient client = MAL.Login(); INode Folder = await Task.Run(() => ChkIfFolderAndFileExist(client, Username, Filename)); if (Folder != null) { Progress <double> ze = new Progress <double>(p => PB.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { UpdateMessages.UploadMsg((int)p, PB, LBL); }))); using (FileStream stream = File.Open(@PathFileToUpload, FileMode.Open)) { INode FileUploaded = await client.UploadAsync(stream, Filename, Folder, ze); //Uploading File from PC to Mega //INode FileUploaded = await client.UploadFileAsync(PathFileToUpload, Folder, ze); //Uploading File from PC to Mega if (FileUploaded != null) { DLink = (await client.GetDownloadLinkAsync(FileUploaded)).ToString(); FileSize = (((int)(FileUploaded.Size / 1024))).ToString(); //Size in Kb client.Logout(); GC.Collect(); // TENGO QUE LLAMAR ESTO O NO DEJA BORRAR EL ARCHIVO ZIP PORQUE DICE QUE AUN ESTA EN USO. if (!DLink.Equals("")) { SavesClass SC = new SavesClass(); SC.DLink = DLink; SC.Size = FileSize; return(SC); } else { PB.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { UpdateMessages.UploadMsg(101, PB, LBL); })); return(null); } } PB.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { UpdateMessages.UploadMsg(101, PB, LBL); })); return(null); } } else { PB.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { UpdateMessages.UploadMsg(101, PB, LBL); })); return(null); } } } catch { PB.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { UpdateMessages.UploadMsg(102, PB, LBL); })); return(null); } }
private static void OnExit() { if (mega.IsLoggedIn) { mega.Logout(); Console.WriteLine("Logged out."); } }
public void mega() { progress_qr_code_upload(); string qr_path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\\qr"; string qr_dest = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\codes.zip"; using (ZipFile zip = new ZipFile(System.Text.Encoding.Default)) { foreach (var file in System.IO.Directory.GetFiles(qr_path)) { zip.AddFile(file); } zip.Save(qr_dest); } try { var client = new MegaApiClient(); string zip_location = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\\codes.zip"; client.Login("ADD_MEGA_USERNAME_HERE", "PASSWORD_HERE"); IEnumerable <INode> nodes = client.GetNodes(); INode root = nodes.Single(x => x.Type == NodeType.Root); INode myFolder = client.CreateFolder("QR-Codes", root); INode myFile = client.UploadFile(zip_location, myFolder); Uri downloadLink = client.GetDownloadLink(myFile); Console.WriteLine(downloadLink); string download = downloadLink.ToString(); MessageBox.Show(download + "" + "Preview QR-Codes and save", "Copied to Clipboard", MessageBoxButtons.YesNo); if (MessageBox.Show("Do you really want to preview QR-codes?", "Preview", MessageBoxButtons.YesNo) == DialogResult.Yes) { Form2 qrcode_preview = new Form2(); qrcode_preview.ShowDialog(); } Clipboard.SetText(download); client.Logout(); MessageBox.Show("all done. qr-code location:" + zip_location); } catch (Exception error) { MessageBox.Show("Error uploading QR-Codes to mega" + error); return; } }
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 void Dispose() { try { _allNodes = null; if (_client != null && _client.IsLoggedIn) { _client.Logout(); } } catch (Exception ex) { Console.WriteLine(ex); } }
private void Upt_Tick(object sender, EventArgs e) { if (td.IsCompleted) { INode m = td.Result; Uri downloadLink = client.GetDownloadLink(m); Clipboard.SetText(downloadLink.ToString()); Console.WriteLine(downloadLink.ToString()); System.Diagnostics.Process.Start(downloadLink.ToString()); MessageBox.Show("Upload Complete!\n" + downloadLink.ToString() + "\nCopied to Clipboard!", "Finished!", MessageBoxButton.OK, MessageBoxImage.Information); client.Logout(); Upt.Stop(); } }
void Button1Click(object sender, EventArgs e) { try { mclient.Logout(); Properties.Settings.Default.email = ""; Properties.Settings.Default.password = ""; Properties.Settings.Default.Save(); this.Close(); forceClose = true; } catch (Exception ex) { MessageBox.Show("An error occurred while logging out."); } }
public void Dispose() { ReportProgress(SyncStage.CleaningUp); if (client.IsLoggedIn) { client.Logout(); } if (tempWorkFolderPath != null && Directory.Exists(tempWorkFolderPath)) { Directory.Delete(tempWorkFolderPath, true); tempWorkFolderPath = null; } ReportProgress(SyncStage.Done); }
/// <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); } }
public void UploadFileToMega() { var client = new MegaApiClient(); client.Login("*****@*****.**", "Jony*1995"); IEnumerable <INode> nodes = client.GetNodes(); Uri uri = new Uri("https://mega.nz/folder/74QCwKoJ#H5_lbdnO-2aQ3WTJxMmXwA"); IEnumerable <INode> carpeta = client.GetNodesFromLink(uri); foreach (INode child in carpeta) { if (child.Name == "BackUpBaseDatos" + Properties.Settings.Default.NombreEmpresa.Replace(" ", "") + ".zip") { client.Delete(child); } } INode myFile = client.UploadFile("C:/SFacturacion/BD/BackUpBaseDatos" + Properties.Settings.Default.NombreEmpresa.Replace(" ", "") + ".zip", nodes.Single(x => x.Id == "zswWCIDA")); client.Logout(); }
public void download_qr_codes(string linkki_u) { String linkki; linkki = linkki_u; var client = new MegaApiClient(); client.Login("ADD_MEGA_USERNAME_HERE", "PASSWORD_HERE"); Uri folderLink = new Uri(linkki); IEnumerable <INode> nodes = client.GetNodesFromLink(folderLink); foreach (INode node in nodes.Where(x => x.Type == NodeType.File)) { MessageBox.Show($"Downloading {node.Name}"); client.DownloadFile(node, node.Name); } client.Logout(); }
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(); } }
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); }
public static async Task <bool> DeleteSelSave(SavesClass SV, ProgressBar PB, Label LBL) { UpdateMessages.DeleteMsg(10, PB, LBL); SavesContainer SVC = new SavesContainer(); try { SV.IsDelete = "1"; string SV_obj = ""; SV_obj = SV_obj + JsonConvert.SerializeObject(SV, Formatting.Indented); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(Constants.URL + "/api.savecentral.com/v1/files_data/" + WebUtility.UrlEncode(SV.FileName))); request.Accept = "application/json"; request.ContentType = "application/json"; request.Headers.Add("authorization", Constants.ApiKey); request.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(SV_obj); request.ContentLength = byteArray.Length; using (Stream DataStream = await request.GetRequestStreamAsync()) { DataStream.Write(byteArray, 0, byteArray.Length); DataStream.Close(); UpdateMessages.DeleteMsg(50, PB, LBL); using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync()) { using (Stream ResponseStream = response.GetResponseStream()) { using (StreamReader sr = new StreamReader(ResponseStream)) { string ServerResponse = await sr.ReadToEndAsync(); SVC = JsonConvert.DeserializeObject <SavesContainer>(ServerResponse); if (SVC.status.Equals("1")) { //Success using (MALogin MAL = new MALogin()) { MegaApiClient client = MAL.Login(); //DELETE FILE FROM MEGA var nodes = client.GetNodes(); var SelNodes = nodes.First(n => n.Name == SV.FileName && n.Type == NodeType.File); await client.DeleteAsync(SelNodes, false); client.Logout(); } UpdateMessages.DeleteMsg(100, PB, LBL); MessageBox.Show(SVC.message); UpdateMessages.DeleteMsg(103, PB, LBL); return(true); } else { //Fail UpdateMessages.DeleteMsg(101, PB, LBL); MessageBox.Show(SVC.message); UpdateMessages.DeleteMsg(103, PB, LBL); return(false); } } } } } } catch (WebException e) { UpdateMessages.DeleteMsg(102, PB, LBL); //MessageBox.Show("Save could not be deleted due to the following error:" + e.Message); if (e.Response != null) { using (var errorResponse = (HttpWebResponse)e.Response) { using (var reader = new StreamReader(errorResponse.GetResponseStream())) { string error = reader.ReadToEnd(); SVC = JsonConvert.DeserializeObject <SavesContainer>(error); MessageBox.Show(SVC.message); return(false); } } } UpdateMessages.DeleteMsg(103, PB, LBL); return(false); } }
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(); }
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)); } } }
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 void ReleaseUnmanagedResources() { _client.Logout(); _client = null; }