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 Task DeleteFiles() { var nodes = _service.GetNodes(); foreach (var node in nodes) { if (node.Type == NodeType.File) { _service.Delete(node, moveToTrash: false); } } return(Task.FromResult(0)); }
void LoadData() { try { label1.Text = "Fetching Nodes..."; var nodes = mclient.GetNodes().ToList(); INode root = nodes.Single(n => n.Type == NodeType.Root); bool hasmCloudFolder = false; label1.Text = "Scanning Nodes..."; foreach (var node in nodes) { if (node.Name == "mCloud") { hasmCloudFolder = true; } } if (!hasmCloudFolder) { label1.Text = "Adding Nodes..."; mclient.CreateFolder("mCloud", root); nodes = mclient.GetNodes().ToList(); } label1.Text = "Processing Nodes..."; mcNode = nodes.Single(n => n.Name == "mCloud"); List <INode> fileNodes = new List <INode>(); foreach (var node in nodes) { if (node.ParentId == mcNode.Id) { fileNodes.Add(node); } } foreach (var node in fileNodes) { string fileName = node.Name; if (!nodeDict.ContainsKey(fileName)) { nodeDict.Add(fileName, node); } } RefreshView(); } catch (Exception ex) { MessageBox.Show("A fatal error occurred loading the Cloud Drive. mCloudStorage will now exit."); this.Close(); } }
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 GetCurrentFolder(bool autocreate = false) { var parts = m_prefix.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries); var nodes = Client.GetNodes(); INode parent = nodes.First(x => x.Type == NodeType.Root); foreach (var n in parts) { var item = nodes.FirstOrDefault(x => x.Name == n && x.Type == NodeType.Directory && x.ParentId == parent.Id); if (item == null) { if (!autocreate) { throw new FolderMissingException(); } item = Client.CreateFolder(n, parent); } parent = item; } m_currentFolder = parent; ResetFileCache(nodes); }
public static void Test_TraceNodes_01(string name, int limit = 0, bool log = false) { MegaApiClient client = new MegaApiClient(); Trace.WriteLine("MegaApiClient : login"); string email, password; if (!GetMegaLogin(name, out email, out password)) { return; } client.Login(email, password); Trace.WriteLine("MegaApiClient : GetNodes()"); var nodes = client.GetNodes(); Trace.WriteLine($"MegaApiClient : nodes.Count() {nodes.Count()}"); TraceNodes(nodes, limit: limit, log: log); //client.GetAccountInformation(); //client.GetNodeFromLink(Uri uri); //CG.Web.MegaApiClient.NodeType //CG.Web.MegaApiClient.WebClient wc; //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); }
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); }
public static void ListAll(MegaApiClient client) { IEnumerable <INode> nodes = client.GetNodes(); INode parent = nodes.Single(n => n.Type == NodeType.Root); DisplayNodesRecursive(nodes, parent); }
public static void AutoCreateFolder(ExplorerNode node) { List <ExplorerNode> list = node.GetFullPath(); if (list[0].NodeType.Type != CloudType.Mega) { throw new Exception("Mega only."); } MegaApiClient client = GetClient(list[0].NodeType.Email); list.RemoveAt(0); foreach (ExplorerNode child in list) { if (string.IsNullOrEmpty(child.Info.ID)) { MegaNzNode m_p_node = new MegaNzNode(child.Parent.Info.ID); INode c_node = client.GetNodes(m_p_node).Where(n => n.Name == child.Info.Name).First();//find if (c_node == null) { c_node = client.CreateFolder(child.Info.Name, m_p_node); //if not found -> create } child.Info.ID = c_node.Id; } } }
static void GetItems(MegaApiClient client, INode node, ExplorerNode Enode) { foreach (INode child in client.GetNodes(node)) { ExplorerNode c = new ExplorerNode(); c.Info.ID = child.Id; c.Info.Name = child.Name; c.Info.DateMod = child.LastModificationDate; c.Info.MegaCrypto = new MegaKeyCrypto(child as INodeCrypto); switch (child.Type) { case NodeType.File: c.Info.Size = child.Size; Enode.AddChild(c); break; case NodeType.Directory: c.Info.Size = -1; Enode.AddChild(c); break; default: break; } } }
//public static Uri downloadUrl = client.GetDownloadLink(Sendscreenshot); //Console.WriteLine(downloadUrl); //Console.ReadLine(); private static void login() { try { client.Login(email, wachtwoord); var nodes = client.GetNodes(); root = nodes.Single(n => n.Type == NodeType.Root); } catch { } }
public void ReloadMetadata() { nodes = client.GetNodes(workFolderNode); archivesFolderNode = nodes.SingleOrDefault( n => n.Name == "Archives" && n.Type == NodeType.Directory && n.ParentId == workFolderNode.Id); }
public static List <string> VratStruktura() { List <string> struktura = new List <string>(); // struktura = null; var nodes = client.GetNodes(); foreach (INode n in nodes) { if (n.Name != null) { struktura.Add(n.Name); } // MessageBox.Show(n.Type.ToString()); } return(struktura); }
public void ConnectToDrive(object o) { lock (workerLocker) { try { MegaApiClient client = new MegaApiClient(); client.Login(ConfigurationManager.AppSettings["UserName"], ConfigurationManager.AppSettings["Password"]); var nodes = client.GetNodes(); INode root = nodes.Single(n => n.Type == NodeType.Root); INode myFolder = client.CreateFolder("Upload " + DateTime.Today, root); string source = ConfigurationManager.AppSettings["Source"]; string typeFiles = ConfigurationManager.AppSettings["TypeFile"]; var files = Directory.GetFiles(source, "*." + typeFiles, SearchOption.TopDirectoryOnly); var file = files.OrderByDescending(File.GetLastWriteTime).First(); /* var filterFiles = files.Where((n) => File.GetCreationTime(n).ToShortDateString() == date);*/ using (var stream = new ProgressionStream(new FileStream(file, FileMode.Open), PrintProgression) ) { INode myFile = client.Upload(stream, Path.GetFileName(file), myFolder); client.GetDownloadLink(myFile); } } catch (Exception ex) { var path = Path.Combine(Environment.CurrentDirectory, "log.txt"); //if (!File.Exists(path)) //{ // File.Create(path); //} using (FileStream fs = new FileStream(path, FileMode.Append)) { using (StreamWriter sw = new StreamWriter(fs)) { sw.WriteLine("=========MEGA=============" + Environment.NewLine); sw.WriteLine("-----" + DateTime.Now.ToShortDateString() + "-----" + Environment.NewLine); sw.WriteLine(ex.Message); } }; } finally { run = 0; Monitor.Pulse(workerLocker); } } }
public static void Test_03(string name) { MegaApiClient client = new MegaApiClient(); Trace.WriteLine("MegaApiClient : login"); string email, password; if (!GetMegaLogin(name, out email, out password)) { return; } client.Login(email, password); Trace.WriteLine("MegaApiClient : get root"); var root = client.GetNodes().First(node => node.Type == NodeType.Root); Trace.WriteLine("MegaApiClient : GetNodes(root)"); var nodes = client.GetNodes(root); Trace.WriteLine($"MegaApiClient : nodes.Count() {nodes.Count()}"); TraceNodes(nodes); }
/// <summary> /// Creates a folder with the username in case it doesn't already exist and returns the folder's name. If the folder already exists checks if the FileName already exists, and if it does /// deletes it, then returns the folder's name. /// </summary> /// <param name="client">MegaApiClient instance</param> /// <param name="Username">Curent user's Username</param> /// <param name="FileName">File prepared to be uploaded (name must include extension). If the file already exists in Mega then deletes the old one before uploading this new version.</param> /// <returns>INode - Folder's name.</returns> public static INode ChkIfFolderAndFileExist(MegaApiClient client, string Username, string FileName) { IEnumerable <INode> nodes = client.GetNodes(); INode root = nodes.Single(n => n.Type == NodeType.Root); IEnumerable <INode> FoldersInRoot = client.GetNodes(root); INode FolderSearched = nodes.FirstOrDefault(n => n.Type == NodeType.Directory && n.Name == Username); if (FolderSearched == null) { return(client.CreateFolder(Username, root)); } else if (DeleteFileIfExist(client, nodes.Where(n => n.Type == NodeType.Directory && n.Name == Username), FileName)) { return(FolderSearched); } else { return(null); } }
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; } }
private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { Klijenti red = (Klijenti)gridView1.GetRow(gridView1.FocusedRowHandle); var klijent = main_lista.FirstOrDefault(qq => qq.username == red.username); MegaApiClient mega = new MegaApiClient(); var auth = mega.GenerateAuthInfos(klijent.username, klijent.pass); mega.Login(auth); var nodes = mega.GetNodes(); klijent.zadnji_upload = nodes.Where(n => n.Type == NodeType.File).Max(xx => xx.CreationDate); gridControl1.Refresh(); gridView1.RefreshData(); }
public static void Test_SaveNodes_01(string name) { MegaApiClient client = new MegaApiClient(); string email, password; if (!GetMegaLogin(name, out email, out password)) { return; } client.Login(email, password); Trace.WriteLine("MegaApiClient : GetNodes()"); var nodes = client.GetNodes(); Trace.WriteLine("save nodes"); nodes.zSave(@"c:\pib\_dl\nodes_01.json", jsonIndent: true); }
//public IEnumerable<MegaNode> EnumerateNodes() //{ // Dictionary<string, List<INode>> nodes = GetDictionaryNodes(); // Stack<MegaNodeEnum> stack = new Stack<MegaNodeEnum>(); // stack.Push(new MegaNodeEnum { Childs = nodes[""].GetEnumerator() }); // while (stack.Count > 0) // { // MegaNodeEnum nodeEnum = stack.Peek(); // if (nodeEnum.Childs.MoveNext()) // { // INode node = nodeEnum.Childs.Current; // MegaNode megaNode = MegaNode.Create(node, GetPath(nodeEnum.Node, node)); // yield return megaNode; // if ((node.Type == NodeType.Directory || node.Type == NodeType.Root || node.Type == NodeType.Inbox || node.Type == NodeType.Trash) && nodes.ContainsKey(node.Id)) // stack.Push(new MegaNodeEnum { Node = megaNode, Childs = nodes[node.Id].GetEnumerator() }); // } // else // stack.Pop(); // } //} //private static string GetPath(MegaNode parent, INode node) //{ // if (parent != null) // return parent.Path + "/" + node.Name; // else // { // switch (node.Type) // { // case NodeType.Root: // return "/Root"; // case NodeType.Inbox: // return "/Inbox"; // case NodeType.Trash: // return "/Trash"; // default: // throw new PBException($"wrong node type {node.Type}"); // } // } //} //public IEnumerable<MegaNode> EnumerateNodes() //{ // INode node = GetRoot(); // MegaNode megaNode = MegaNode.Create(node, "/Root"); // yield return megaNode; // Stack<MegaNodeEnum> stack = new Stack<MegaNodeEnum>(); // stack.Push(new MegaNodeEnum { Node = megaNode, Childs = _client.GetNodes(node).GetEnumerator() }); // while (stack.Count > 0) // { // MegaNodeEnum nodeEnum = stack.Peek(); // if (nodeEnum.Childs.MoveNext()) // { // node = nodeEnum.Childs.Current; // megaNode = MegaNode.Create(node, nodeEnum.Node.Path + "/" + node.Name); // yield return megaNode; // if (node.Type == NodeType.Directory) // stack.Push(new MegaNodeEnum { Node = megaNode, Childs = _client.GetNodes(node).GetEnumerator() }); // } // else // stack.Pop(); // } //} public IEnumerable <INode> _GetNodes() { if (!_refreshNodesCache && _nodesCacheFile != null && zFile.Exists(_nodesCacheFile)) { return(zMongo.BsonRead <INode>(_nodesCacheFile)); } else { IEnumerable <INode> nodes = _client.GetNodes(); if (_nodesCacheFile != null) { nodes.zSave(_nodesCacheFile, jsonIndent: true); } return(nodes); } }
public static void DownloadFile() { try { var client = new MegaApiClient(); client.Login(Settings.Default.MegaLogin, Settings.Default.MegaPassword); var nodes = client.GetNodes(); var enumerable = nodes as INode[] ?? nodes.ToArray(); var folders = enumerable.Where(n => n.Type == NodeType.Directory).ToList(); var folder = folders.First(f => string.Equals(f.Name, "Upload")); var myFile = client.UploadFile(Settings.Default.Repositorypath, folder); } catch (Exception e) { MessageBox.Show(e.Message); } }
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 override void Process(BotData data) { base.Process(data); string email = BlockBase.ReplaceValues(this.Email, data); string password = BlockBase.ReplaceValues(this.Password, data); MegaApiClient megaApiClient = new MegaApiClient(); try { megaApiClient.Login(email, password); bool flag = !megaApiClient.IsLoggedIn; if (flag) { throw new Exception(); } IEnumerator <INode> enumerator = megaApiClient.GetNodes().GetEnumerator(); List <string> list = new List <string>(); int num = 0; while (enumerator.MoveNext() && num < this.MaxFilesCaptured) { bool flag2 = enumerator.Current.Name != null; if (flag2) { list.Add(enumerator.Current.Name); num++; } } IAccountInformation accountInformation = megaApiClient.GetAccountInformation(); BlockBase.InsertVariable(data, this.IsCapture, accountInformation.UsedQuota.ToString(), "USEDQUOTA", "", "", false, false); BlockBase.InsertVariable(data, this.IsCapture, accountInformation.TotalQuota.ToString(), "TOTALQUOTA", "", "", false, false); BlockBase.InsertVariable(data, this.IsCapture, list, this.VariableName, "", "", false, false); data.Status = RuriLib.BotStatus.SUCCESS; } catch (Exception ex) { data.Log(ex.Message); data.Status = RuriLib.BotStatus.FAIL; } }
static INode GetRoot(string Email, NodeType type) { switch (type) { case NodeType.Directory: case NodeType.File: case NodeType.Inbox: throw new Exception("That isn't root."); case NodeType.Root: case NodeType.Trash: MegaApiClient client = GetClient(Email); foreach (INode n in client.GetNodes().Where <INode>(n => n.Type == NodeType.Root)) { if (n.Type == NodeType.Root) { return(n); } } break; } throw new Exception("Can't find " + type.ToString()); }
private static bool DeleteFileIfExist(MegaApiClient client, IEnumerable <INode> UserFolder, string FileName) { try { INode F = UserFolder.FirstOrDefault(); IEnumerable <INode> T = client.GetNodes(F); INode S = T.FirstOrDefault(n => n.Name == FileName); if (S == null) { return(true); } else { //Delete older version to avoid duplicates. client.Delete(S, false); return(true); } } catch { return(false); } }
private void Upload() { string yi = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location))); string pa = @"\FFMPEG\doc\"; string n = "Saves.txt"; string c = yi + pa + n; if (File.Exists(c)) { string[] lines = File.ReadAllLines(c); client.Login(lines[0], lines[1]); Progress <double> ze = new Progress <double>(p => { Console.WriteLine($"Progress updated: {p}"); double d = Math.Round(p * 10000) / 10000d; lblVideoInfo.Content = d + "%" + " (Upload)"; prbPro.Value = d; }); IEnumerable <INode> nodes = client.GetNodes(); INode root = nodes.Single(x => x.Type == NodeType.Root); INode myFolder = client.CreateFolder("Upload-s" + a, root); td = Task.Run(() => { return(client.UploadFileAsync(V, myFolder, ze)); }); Upt.Interval = TimeSpan.FromMilliseconds(30); Upt.Tick += Upt_Tick; Upt.Start(); } }
/// <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)); }
private void subirArchivoAMega() { try { string Fecha = DateTime.Now.ToString("yyy-MM-dd"); lblInfo.Invoke(new MethodInvoker(delegate { lblInfo.Text = "Conectando..."; })); progressBar1.Invoke(new MethodInvoker(delegate { progressBar1.PerformStep(); })); MegaApiClient cliente = new MegaApiClient(); cliente.Login("*****@*****.**", "corajitos12"); progressBar1.Invoke(new MethodInvoker(delegate { progressBar1.PerformStep(); })); lblInfo.Invoke(new MethodInvoker(delegate { lblInfo.Text = "Obteniendo directorios..."; })); var nodos = cliente.GetNodes(); lblInfo.Invoke(new MethodInvoker(delegate { lblInfo.Text = "Buscando carpeta 'Backup'..."; })); bool existe = cliente.GetNodes().Any(n => n.Name == "Backup " + Fecha); INode root; INode carpeta; if (existe == true) { lblInfo.Invoke(new MethodInvoker(delegate { lblInfo.Text = "Obteniendo la carpeta 'Backup'...."; })); progressBar1.Invoke(new MethodInvoker(delegate { progressBar1.PerformStep(); })); carpeta = nodos.Single(n => n.Name == "Backup " + Fecha); } else { lblInfo.Invoke(new MethodInvoker(delegate { lblInfo.Text = "Creando carpeta 'Backup'..."; })); progressBar1.Invoke(new MethodInvoker(delegate { progressBar1.PerformStep(); })); root = nodos.Single(n => n.Type == NodeType.Root); carpeta = cliente.CreateFolder("Backup " + Fecha, root); } progressBar1.Invoke(new MethodInvoker(delegate { progressBar1.PerformStep(); })); lblInfo.Invoke(new MethodInvoker(delegate { lblInfo.Text = "Subiendo archivo..."; })); progressBar1.Invoke(new MethodInvoker(delegate { progressBar1.PerformStep(); })); INode archivo = cliente.UploadFile(@"C:\Database Tec34\DatabaseEscTec.db", carpeta); Uri downloadUrl = cliente.GetDownloadLink(archivo); lblInfo.Invoke(new MethodInvoker(delegate { lblInfo.Text = "Archivo subido con éxito."; })); } catch (Exception error) { t.Abort(); MessageBox.Show("Error al intentar subir el archivo. " + error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } this.Invoke((MethodInvoker) delegate { this.Close(); }); }
/// <summary> /// Perform the file upload to an account /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <param name="path"></param> public void InternalUploadDatabase(string username, string password, string path) { string error = null; if (!File.Exists(path)) { error = "LocalDatabaseFileNotFound"; DatabaseUploadEnded?.Invoke(this, new DatabaseUploadEndedEventArgs(false, error)); return; } var client = new MegaApiClient(); try { client.Login(username, password); var nodes = client.GetNodes(); // Delete previous sync files foreach (var node in nodes.Where(x => x.Name != null && x.Name.EndsWith(".crypt"))) { client.Delete(node, false); } // Upload new sync file var parentNode = nodes.FirstOrDefault(x => x.Type == NodeType.Root); if (parentNode is null) { error = "InvalidUrl"; } else { client.UploadFile(path, parentNode); } } catch (ApiException) { error = "ApiError"; } catch (UriFormatException) { error = "InvalidUrl"; } catch (ArgumentException) { error = "InvalidUrl"; } catch (IOException) { error = "CantUploadFile"; } catch (Exception) { error = "ApiError"; } finally { if (client.IsLoggedIn) { client.Logout(); } } DatabaseUploadEnded?.Invoke(this, new DatabaseUploadEndedEventArgs(string.IsNullOrEmpty(error), error)); }
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); } }