/// <summary> /// Downloads the specified test file and verifies its contents. /// </summary> private async Task TestFileDownload(TestData.TestFile testFile) { var target = Path.GetTempFileName(); try { Debug.WriteLine("Temporary local file: " + target); using (var feedback = new DebugFeedbackChannel("Test")) { using (var initializing = feedback.BeginSubOperation("InitializeData")) await TestData.Current.BringToInitialState(initializing); var client = new MegaClient(TestData.Current.Email1, TestData.Current.Password1); var filesystem = await client.GetFilesystemSnapshotAsync(feedback); var file = testFile.TryFind(filesystem); if (file == null) Assert.Fail("Could not find expected file to download: " + testFile.Name); await file.DownloadContentsAsync(target, feedback); using (var expectedContents = testFile.Open()) using (var contents = File.OpenRead(target)) TestHelper.AssertStreamsAreEqual(expectedContents, contents); } } finally { File.Delete(target); } }
public override NtStatus ReadFile(string fileName, byte[] buffer, out int bytesRead, long offset, DokanFileInfo info) { if (!FilesystemStruct.ContainsKey(fileName)) { bytesRead = 0; return(DokanResult.FileNotFound); } if (info.Context == null) { using (var stream = MegaClient.Download(FilesystemStruct[fileName])) { try { stream.Position = offset; } catch (Exception) { } bytesRead = stream.Read(buffer, 0, buffer.Length); } } else { var stream = info.Context as Stream; lock (stream) { stream.Position = offset; bytesRead = stream.Read(buffer, 0, buffer.Length); } } return(DokanResult.Success); }
public async Task SuccessfulLogin_IsSuccessful() { var client = new MegaClient(TestData.Current.Email1, TestData.Current.Password1); using (var connecting = new DebugFeedbackChannel("Test")) await client.EnsureConnectedAsync(connecting); }
public override NtStatus WriteFile(string fileName, byte[] buffer, out int bytesWritten, long offset, DokanFileInfo info) { if (!FilesystemStruct.ContainsKey(fileName)) { bytesWritten = 0; return(DokanResult.FileNotFound); } if (info.Context == null) { using (var stream = new MemoryStream()) { try { MegaClient.Upload(stream, Path.GetFileName("R:" + fileName), NodeList.Single(x => x.Id == FilesystemStruct[fileName].ParentId)); stream.Position = offset; } catch (Exception) { } bytesWritten = (int)stream.Length; stream.Write(buffer, 0, buffer.Length); } } else { var stream = info.Context as Stream; lock (stream) { stream.Position = offset; stream.Write(buffer, 0, buffer.Length); bytesWritten = (int)stream.Length; } } return(DokanResult.Success); }
public MegaFSHook() { Instance = this; if (NodeList.Count < 1) { NodeList = MegaClient.GetNodes().ToList(); } FilesystemStruct = Flat23dst(NodeList[0]); }
private void MGFuseUI_FormClosing(object sender, FormClosingEventArgs e) { if (MegaClient != null) { if (MegaClient.IsLoggedIn) { MegaClient.Logout(); } } Application.Exit(); }
private void quitbtn_Click(object sender, EventArgs e) { if (MegaClient != null) { if (MegaClient.IsLoggedIn) { MegaClient.Logout(); } } Application.Exit(); }
public async Task SendFileToContact_SeemsToWork() { using (var feedback = new DebugFeedbackChannel("Test")) { using (var initializing = feedback.BeginSubOperation("InitializeData")) await TestData.Current.BringToInitialState(initializing); using (var sending = feedback.BeginSubOperation("Sending")) { var client = new MegaClient(TestData.Current.Email1, TestData.Current.Password1); await client.AddContactAsync(TestData.Current.Email2, sending); var contactList = await client.GetContactListSnapshotAsync(sending); Assert.AreEqual(1, contactList.Count); var account2 = contactList.Single(); var filesystem = await client.GetFilesystemSnapshotAsync(sending); var file = TestData.SmallFile.Find(filesystem); await file.SendToContactAsync(account2, sending); } using (var receiving = feedback.BeginSubOperation("Receiving")) { var client = new MegaClient(TestData.Current.Email2, TestData.Current.Password2); var filesystem = await client.GetFilesystemSnapshotAsync(receiving); var file = TestData.SmallFile.Find(filesystem); Assert.IsNotNull(file); var target = Path.GetTempFileName(); // Verify contents. try { Debug.WriteLine("Temporary local file: " + target); await file.DownloadContentsAsync(target, feedback); using (var expectedContents = TestData.SmallFile.Open()) using (var contents = File.OpenRead(target)) TestHelper.AssertStreamsAreEqual(expectedContents, contents); } finally { File.Delete(target); } } } }
public async Task AccountListLoad_DoesNotCauseApocalypse() { using (var feedback = new DebugFeedbackChannel("Test")) { using (var initializing = feedback.BeginSubOperation("InitializeData")) await TestData.Current.BringToInitialState(initializing); var client = new MegaClient(TestData.Current.Email1, TestData.Current.Password1); await client.EnsureConnectedAsync(feedback); await client.GetContactListSnapshotAsync(feedback); } }
public async void GetAccount() { var accinfo = await MegaClient.GetAccountInformationAsync(); static_quota_max = accinfo.TotalQuota; MGFuseMain.dynamic_quota_used = accinfo.UsedQuota; MGFuseMain.dynamic_quota_free = static_quota_max - dynamic_quota_used; storageLabel.Text = (static_quota_max / 1024 / 1024 / 1024) + " GB total\n" + (dynamic_quota_used / 1024 / 1024 / 1024) + " GB used\n" + (dynamic_quota_free / 1024 / 1024 / 1024) + " GB free"; //Mount FUSE //dokan mount new Thread(() => { this.PerformSafely(() => { unmountBtn.Enabled = true; }); Dokan.Mount(new MegaFUSE.MFuseFS(new MegaFSHook()), DriveLetter.ToString() + ":\\", DokanOptions.FixedDrive, 5, null); }).Start(); }
public async Task TestAccountInitialization_IsSuccessful() { using (var connecting = new DebugFeedbackChannel("Test")) { using (var initializing = connecting.BeginSubOperation("InitializeData")) { await TestData.Current.BringToInitialState(initializing); var client = new MegaClient(TestData.Current.Email1, TestData.Current.Password1); await client.EnsureConnectedAsync(connecting); } } }
public static void Test_TraceMegaNodes_02(string name, string directory = "/", NodesOptions options = NodesOptions.Default, int limit = 0, bool log = false) { MegaClient megaClient = new MegaClient(); string email, password; if (!GetMegaLogin(name, out email, out password)) { return; } megaClient.Email = email; megaClient.Password = password; megaClient.Login(); TraceNodes(megaClient.GetNodes(directory, options), limit: limit, log: log); }
public static void Ls(string[] parameters, NodesOptions option1, LsOptions option2) { if (parameters.Length > 1) { Trace.WriteLine("syntax error"); return; } if (parameters.Length == 1) { Cd(parameters); } MegaClient megaClient = GetMegaClient(); //NodesOptions options = NodesOptions.Directory | NodesOptions.File; TraceNodes(megaClient.GetNodes(GetMegaEnvironment().GetDirectory(), option1), option1, option2); }
/// <summary> /// Uploads the specified test file and ensures that it looks like it really did get uploaded. /// </summary> private async Task TestFileUpload(TestData.TestFile testFile) { using (var feedback = new DebugFeedbackChannel("Test")) { var client = new MegaClient(TestData.Current.Email1, TestData.Current.Password1); var filesystem = await client.GetFilesystemSnapshotAsync(feedback); // Just stick it in the root, do not care about what already exists there. CloudItem file; using (var stream = testFile.Open()) file = await filesystem.Files.NewFileAsync(testFile.Name, stream, feedback); Assert.AreEqual(testFile.Name, file.Name); Assert.AreEqual(testFile.Size, file.Size); } }
public static void Test_GetMegaNodes_v2(string name) { MegaClient megaClient = new MegaClient(); string email, password; if (!GetMegaLogin(name, out email, out password)) { return; } megaClient.Email = email; megaClient.Password = password; megaClient.Login(); // .zSave(@"c:\pib\_dl\meganode_01.json", jsonIndent: true) //megaClient.GetDictionaryNodes1_v2(); megaClient.GetMegaNodes().zSave(@"c:\pib\_dl\meganode_02.json", jsonIndent: true); }
public override NtStatus DeleteFile(string fileName, DokanFileInfo info) { if (!FilesystemStruct.ContainsKey(fileName)) { return(DokanResult.FileNotFound); } if (FilesystemStruct.ContainsKey(fileName) && (FilesystemStruct[fileName].Type == NodeType.Directory)) { return(DokanResult.InvalidParameter); } var fileNode = FilesystemStruct[fileName]; MegaClient.Delete(fileNode); FilesystemStruct.Remove(fileName); NodeList.Remove(fileNode); return(DokanResult.Success); }
public async void Login() { try { await MegaClient.LoginAsync(usernameInput.Text, passwordInput.Text); statusLabel.Text = "Logged in!"; MGFuseUI.ShowPanel <MgmtPanel>(); return; } catch (ApiException ex) { MessageBox.Show("API Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (Exception) { MessageBox.Show("Failed logging in! Please try again later.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } statusLabel.Text = "Login failed!"; loginBtn.Enabled = true; }
public async Task SendFolderToContact_SeemsToWork() { using (var feedback = new DebugFeedbackChannel("Test")) { using (var initializing = feedback.BeginSubOperation("InitializeData")) await TestData.Current.BringToInitialState(initializing); using (var sending = feedback.BeginSubOperation("Sending")) { var client = new MegaClient(TestData.Current.Email1, TestData.Current.Password1); await client.AddContactAsync(TestData.Current.Email2, sending); var contactList = await client.GetContactListSnapshotAsync(sending); Assert.AreEqual(1, contactList.Count); var account2 = contactList.Single(); var filesystem = await client.GetFilesystemSnapshotAsync(sending); var folder = filesystem.Files.Children .Single(i => i.Type == ItemType.Folder && i.Name == "Folder1"); await folder.SendToContactAsync(account2, sending); } using (var receiving = feedback.BeginSubOperation("Receiving")) { var client = new MegaClient(TestData.Current.Email2, TestData.Current.Password2); var filesystem = await client.GetFilesystemSnapshotAsync(receiving); var file = TestData.SmallFile.Find(filesystem); Assert.IsNotNull(file); Assert.IsNotNull(file.Parent); Assert.AreEqual("Folder1", file.Parent.Name); } } }
private static MegaClient GetMegaClient() { MegaClient megaClient = new MegaClient(); //string environmentFile = XmlConfig.CurrentConfig.GetExplicit("LocalEnvironment"); //if (!zFile.Exists(environmentFile)) //{ // Trace.WriteLine("login not defined"); // return null; //} //string login = XDocument.Load(environmentFile).zXPathExplicitValue("Login"); string login = GetMegaEnvironment().GetLogin(); XmlConfig localConfig = XmlConfig.CurrentConfig.GetConfig("LocalConfig"); XmlConfigElement configElement = localConfig.GetConfigElement($"Login[@name = '{login}']"); if (configElement == null) { Trace.WriteLine($"unknow login \"{login}\""); return(null); } megaClient.Email = configElement.GetExplicit("@email"); megaClient.Password = configElement.GetExplicit("@password"); megaClient.Login(); return(megaClient); }
/// <summary> /// Materializes an instance from an Item structure returned by the Mega API, treated as a template for this item. /// Parent-child relationships are not automatically linked up - that is left up to the creator. /// </summary> internal static CloudItem FromTemplate(Item template, MegaClient client) { Argument.ValidateIsNotNull(template, "template"); Argument.ValidateIsNotNull(client, "client"); CloudItem item = new CloudItem(client) { TypeID = template.Type, // Filter out invalid sizes that Mega does not work with (anything less than 1). Size = template.Size.GetValueOrDefault() > 0 ? (long?)template.Size.Value : null, ID = template.ID, OwnerID = template.OwnerID, LastUpdated = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero).AddSeconds(template.Timestamp).ToLocalTime(), ParentID = template.ParentID, EncryptedKeys = template.EncryptedKeys.ToImmutableHashSet(), IsShareRoot = template.ShareKey.HasValue }; bool hasEncryptedData = true; switch (template.Type) { case KnownItemTypes.File: item.Type = ItemType.File; break; case KnownItemTypes.Folder: item.Type = ItemType.Folder; break; case KnownItemTypes.Inbox: item.Type = ItemType.Inbox; hasEncryptedData = false; break; case KnownItemTypes.Trash: item.Type = ItemType.Trash; hasEncryptedData = false; break; case KnownItemTypes.Files: item.Type = ItemType.Files; hasEncryptedData = false; break; default: item.Type = ItemType.Unknown; break; } if (hasEncryptedData) { // Decrypt the item attributes, if the item has them and if we have a key. var itemKey = client.DecryptItemKey(item.EncryptedKeys); // We have a key for this item! var attributesKey = Algorithms.DeriveNodeAttributesKey(itemKey); item.Attributes = ItemAttributes.DecryptAndDeserialize(template.Attributes, attributesKey); } return item; }
public async void StartDownload() { try { ProgressBar.Tag = this; ProgressLabel.Text = ""; ProgressLabel.Visible = true; Directory.CreateDirectory(Path.GetDirectoryName(SavePath)); FileInfo file = new FileInfo(SavePath); DialogResult overwriteFile = DialogResult.Yes; if (file.Exists) { switch (MegaDownload.OverwriteMode) { case 0: overwriteFile = DialogResult.No; break; case 1: overwriteFile = DialogResult.Yes; break; case 2: if (Node.ModificationDate > file.CreationTime) { overwriteFile = DialogResult.Yes; } else { overwriteFile = DialogResult.No; } break; case 3: overwriteFile = MessageBox.Show($"File [{file.Name}] already exists. Overwrite?", "", MessageBoxButtons.YesNo); break; } if (overwriteFile == DialogResult.Yes) { file.Delete(); } } if (overwriteFile == DialogResult.Yes) { DownloadTask = MegaClient.DownloadFileAsync(Node, SavePath, Progress, MegaDownload.cancellationTokenSource.Token); await DownloadTask; } MegaDownload.UpdateQueue(this); } catch (Exception ex) { if (DownloadTask.IsCanceled) { DownloadTask.Dispose(); } //MessageBox.Show(ex.Message); } finally { //Finished = true; //ProgressBar.Tag = null; //ProgressBar.Value = 0; //ProgressLabel.Visible = false; } }
public async void StartDownload() { DownloadTask = MegaClient.DownloadAsync(Node, Progress); }
public void RefreshFS() { NodeList = MegaClient.GetNodes().ToList(); FilesystemStruct = Flat23dst(NodeList[0]); }
private CloudItem(MegaClient client) { _client = client; Attributes = new ItemAttributes(); Children = ImmutableHashSet.Create<CloudItem>(); EncryptedKeys = ImmutableHashSet.Create<EncryptedItemKey>(); }
public async Task TransferringFiles_OfVariousSizes_SeemsToWork() { var interestingSizes = new List<int> { 0, 1, 8, 15, 16, 255, 256, 1023, 1024, }; // Now also add all the chunk sizes and chunk +-1 sizes for a reasonable amount of chunks. var chunkSizes = Algorithms.MeasureChunks(8 * 1024 * 1024); foreach (var chunkSize in chunkSizes) { interestingSizes.Add(chunkSize - 16); interestingSizes.Add(chunkSize - 15); interestingSizes.Add(chunkSize - 1); interestingSizes.Add(chunkSize); interestingSizes.Add(chunkSize + 1); interestingSizes.Add(chunkSize + 15); interestingSizes.Add(chunkSize + 16); } using (var feedback = new DebugFeedbackChannel("Test")) { var client = new MegaClient(TestData.Current.Email1, TestData.Current.Password1); var filesystem = await client.GetFilesystemSnapshotAsync(feedback); foreach (var size in interestingSizes) await TestFileUploadAndDownload(size, filesystem, feedback); } }
/// <summary> /// Brings the two test accounts to the initial state. /// </summary> /// <remarks> /// Account 1 contents: /// Files /// - Folder1 /// -- Folder2 /// --- EmptyFile /// -- SmallFile /// - BigFile /// - MediumFile /// Contacts /// /// Account 2 contents: /// Files /// Contacts /// - Account 1 /// </remarks> public async Task BringToInitialState(IFeedbackChannel feedback) { var client1 = new MegaClient(Email1, Password1); var client2 = new MegaClient(Email2, Password2); var filesystem1 = await client1.GetFilesystemSnapshotAsync(feedback); // Got folders? var folder1 = filesystem1.Files.Children .FirstOrDefault(ci => ci.Type == ItemType.Folder && ci.Name == "Folder1"); CloudItem folder2 = null; if (folder1 != null) folder2 = folder1.Children .FirstOrDefault(ci => ci.Type == ItemType.Folder && ci.Name == "Folder2"); // Make folders, if needed. if (folder1 == null) folder1 = await filesystem1.Files.NewFolderAsync("Folder1", feedback); if (folder2 == null) folder2 = await folder1.NewFolderAsync("Folder2", feedback); // Got files? var bigFile = BigFile.TryFind(filesystem1); var mediumFile = MediumFile.TryFind(filesystem1); var smallFile = SmallFile.TryFind(filesystem1); var emptyFile = EmptyFile.TryFind(filesystem1); // Then upload the new files. if (emptyFile == null || emptyFile.Parent != folder2) using (var stream = OpenTestDataFile(EmptyFile.Name)) emptyFile = await folder2.NewFileAsync(EmptyFile.Name, stream, feedback); if (smallFile == null || smallFile.Parent != folder1) using (var stream = OpenTestDataFile(SmallFile.Name)) smallFile = await folder1.NewFileAsync(SmallFile.Name, stream, feedback); if (mediumFile == null || mediumFile.Parent != filesystem1.Files) using (var stream = OpenTestDataFile(MediumFile.Name)) mediumFile = await filesystem1.Files.NewFileAsync(MediumFile.Name, stream, feedback); if (bigFile == null || bigFile.Parent != filesystem1.Files) using (var stream = OpenTestDataFile(BigFile.Name)) bigFile = await filesystem1.Files.NewFileAsync(BigFile.Name, stream, feedback); // Delete all items that we do not care about for account 1. var goodItems = new[] { folder1.ID, folder2.ID, bigFile.ID, mediumFile.ID, smallFile.ID, emptyFile.ID }; await DeleteUnwantedItems(filesystem1.Files, goodItems, feedback); await DeleteUnwantedItems(filesystem1.Trash, goodItems, feedback); // Delete all files and folders for account 2. var filesystem2 = await client2.GetFilesystemSnapshotAsync(feedback); foreach (var item in filesystem2.AllItems.Where(ci => ci.Type == ItemType.File || ci.Type == ItemType.Folder)) await item.DeleteAsync(feedback); // Delete all contacts. foreach (var contact in await client1.GetContactListSnapshotAsync(feedback)) await contact.RemoveAsync(feedback); foreach (var contact in await client2.GetContactListSnapshotAsync(feedback)) await contact.RemoveAsync(feedback); // Add account 1 as contact to account 2. await client2.AddContactAsync(Email1, feedback); }
internal FilesystemSnapshot(MegaClient owner) { _owner = owner; }
static void Main(string[] args) { var client = new MegaClient(); client.GetClient(); }
public async void StartDownload() { try { ProgressBar.Tag = this; ProgressLabel.Text = ""; ProgressLabel.Visible = true; Directory.CreateDirectory(Path.GetDirectoryName(SavePath)); FileInfo file = new FileInfo(SavePath); DialogResult overwriteFile = DialogResult.Yes; if (file.Exists) { switch (MegaDownload.OverwriteMode) { case 0: overwriteFile = DialogResult.No; break; case 1: overwriteFile = DialogResult.Yes; break; case 2: if (Node.ModificationDate > file.CreationTime) { overwriteFile = DialogResult.Yes; } else { overwriteFile = DialogResult.No; } break; case 3: overwriteFile = MessageBox.Show($"File [{file.Name}] already exists. Overwrite?", "", MessageBoxButtons.YesNo); break; } if (overwriteFile == DialogResult.Yes) { file.Delete(); } } if (overwriteFile == DialogResult.Yes) { DownloadTask = MegaClient.DownloadFileAsync(Node, SavePath, Progress, MegaDownload.cancellationTokenSource.Token); await DownloadTask; } MegaDownload.UpdateQueue(this); } catch (Exception ex) { if (DownloadTask.IsCanceled) { DownloadTask.Dispose(); if (File.Exists(SavePath)) { File.Delete(SavePath); } ProgressBar.Value = 0; ProgressLabel.Text = ""; } else { var logFileName = $"00-DOWNLOAD-LOG-{DateTime.Now.ToString("MM-dd-yyyy")}.txt"; string log = $"\n{DateTime.Now}\nNode id: {Node.Id}\nSavePath:{SavePath}\nexception: {ex.Message}\n"; File.AppendAllText(logFileName, log); } } }
public async Task CancelingDownload_SeemsToWork() { var target = Path.GetTempFileName(); try { Debug.WriteLine("Temporary local file: " + target); using (var feedback = new DebugFeedbackChannel("Test")) { using (var initializing = feedback.BeginSubOperation("InitializeData")) await TestData.Current.BringToInitialState(initializing); var client = new MegaClient(TestData.Current.Email1, TestData.Current.Password1); var filesystem = await client.GetFilesystemSnapshotAsync(feedback); var file = TestData.BigFile.TryFind(filesystem); if (file == null) Assert.Fail("Could not find the test file to download."); CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromSeconds(3)); await file.DownloadContentsAsync(target, feedback, cts.Token); } } finally { File.Delete(target); } }