示例#1
0
        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;
                }
            }
        }
示例#2
0
        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";
        }
        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 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);
            }
        }
示例#5
0
        static void Mega()
        {
            MegaApiClient       client = MegaNz.GetClient("*****@*****.**");
            IAccountInformation info   = client.GetAccountInformation();

            Console.WriteLine(info.UsedQuota.ToString() + "/" + info.TotalQuota.ToString());
        }
示例#6
0
        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);
     }
 }
        // 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);
        }
        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);
        }
        private async static Task FetchMegaFile(string inSaveLocation, DownloadProgressCallback delProgress)
        {
            string megaUrl = await FetchMegaUrl();

            if (File.Exists(inSaveLocation))
            {
                File.Delete(inSaveLocation);
            }

            // Because the MegaApiClient just Task.Run()s (rather than actually parking until the native events are over)
            // I might want to use the single-threaded API all wrapped in a single Task.Run(). Probably negligible gains
            // though (only save ~number of commands - 1 threadpool requests) and it could be annoying if I want to handle
            // user input for ex: "Do you want to retry?"
            MegaApiClient client = new MegaApiClient();

            try
            {
                await client.LoginAnonymousAsync();

                INodeInfo node = await client.GetNodeFromLinkAsync(new Uri(megaUrl));

                await client.DownloadFileAsync(new Uri(megaUrl), inSaveLocation, new ProgressReporter(delProgress, node.Size));
            }
            catch (Exception ex)
            {
                // Check to see if we can split up the errors any further.
                throw new CannotConnectToMegaException("", ex);;
            }
            finally
            {
                await client.LogoutAsync();
            }
        }
示例#11
0
 private void loginBtn_Click(object sender, EventArgs e)
 {
     MegaClient       = new MegaApiClient();
     statusLabel.Text = "Logging in...";
     loginBtn.Enabled = false;
     Login();
 }
示例#12
0
        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;
                }
            }
        }
示例#13
0
        public async Task <bool> PrepareAsync(CookieAwareWebClient client, CancellationToken cancellation)
        {
            _client = new MegaApiClient(new Options(InternalUtils.GetMegaAppKey().Item1));

            var storage = SettingsHolder.Content.MegaAuthenticationStorage;
            var token   = new MegaApiClient.LogonSessionToken(
                storage.GetEncrypted <string>(KeySession),
                storage.GetEncrypted <byte[]>(KeyToken));

            if (!string.IsNullOrWhiteSpace(token.SessionId) && token.MasterKey != null)
            {
                await _client.LoginAsync(token);
            }
            else
            {
                await _client.LoginAnonymousAsync();
            }

            try {
                var information = await _client.GetNodeFromLinkAsync(_uri);

                TotalSize = information.Size;
                FileName  = information.Name;
                return(true);
            } catch (ApiException e) {
                WindowsHelper.ViewInBrowser(_uri);
                throw new InformativeException("Unsupported link", "Please download it manually.", e);
            }
        }
示例#14
0
文件: Mega.cs 项目: aeax/ShareX
 public Mega(MegaApiClient.AuthInfos authInfos, string parentNodeId)
 {
     AllowReportProgress = false;
     _megaClient = new MegaApiClient(this);
     _authInfos = authInfos;
     _parentNodeId = parentNodeId;
 }
        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);
        }
示例#16
0
        async void Checkup()
        {
            var wait = DevExpress.XtraSplashScreen.SplashScreenManager.ShowOverlayForm(this.simpleButton1);

            progressBarControl1.Properties.Minimum     = 0;
            progressBarControl1.Properties.Maximum     = main_lista.Count;
            progressBarControl1.Properties.Step        = 1;
            progressBarControl1.Properties.PercentView = true;
            try
            {
                foreach (var klijent in main_lista)
                {
                    MegaApiClient mega = new MegaApiClient();
                    var           auth = mega.GenerateAuthInfos(klijent.username, klijent.pass);
                    mega.Login(auth);
                    var nodes = await mega.GetNodesAsync();

                    klijent.zadnji_upload = nodes.Where(n => n.Type == NodeType.File).Max(xx => xx.CreationDate);
                    gridControl1.Refresh();
                    gridView1.RefreshData();
                    progressBarControl1.PerformStep();
                    progressBarControl1.Update();
                }
            }
            catch (Exception ex)
            {
                DevExpress.XtraSplashScreen.SplashScreenManager.CloseOverlayForm(wait);
                XtraMessageBox.Show(ex.Message);
            }
            DevExpress.XtraSplashScreen.SplashScreenManager.CloseOverlayForm(wait);
            progressBarControl1.EditValue = 0;
        }
        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();
        }
示例#18
0
        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); };
        }
示例#19
0
        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);
        }
示例#20
0
        public void GenerateAuthInfos_ValidCredentials_Succeeds(string email, string password, string expectedResult)
        {
            var authInfos = MegaApiClient.GenerateAuthInfos(email, password);
            var result    = JsonConvert.SerializeObject(authInfos, Formatting.None).Replace('\"', '\'');

            Assert.Equal(expectedResult, result);
        }
示例#21
0
        public static void ListAll(MegaApiClient client)
        {
            IEnumerable <INode> nodes = client.GetNodes();
            INode parent = nodes.Single(n => n.Type == NodeType.Root);

            DisplayNodesRecursive(nodes, parent);
        }
示例#22
0
        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);
        }
示例#23
0
        public static ExplorerNode GetListFileFolder(ExplorerNode node)
        {
            node.Child.Clear();
            ExplorerNode  root   = node.GetRoot;
            MegaApiClient client = GetClient(root.NodeType.Email);

            if (root == node)
            {
                string ID = node.Info.ID;
                INode  n  = null;
                if (!string.IsNullOrEmpty(ID))
                {
                    n = new MegaNzNode(ID);
                }
                else
                {
                    n = GetRoot(root.NodeType.Email, NodeType.Root);
                    AppSetting.settings.SetRootID(root.NodeType.Email, CloudType.Mega, n.Id);
                }
                GetItems(client, n, node);
            }
            else
            {
                if (node.Info.Size != -1)
                {
                    throw new Exception("Can't explorer,this item is not folder.");
                }
                MegaNzNode inode = new MegaNzNode(node.Info.Name, node.Info.ID, node.Parent.Info.ID, -1, NodeType.Directory, node.Info.DateMod);
                GetItems(client, inode, node);
            }
            return(node);
        }
示例#24
0
文件: Mega.cs 项目: Vpload/ShareX
 public Mega(MegaApiClient.AuthInfos authInfos, string parentNodeId)
 {
     AllowReportProgress = false;
     _megaClient         = new MegaApiClient(this);
     _authInfos          = authInfos;
     _parentNodeId       = parentNodeId;
 }
        public static MegaApiClient Login(string account, string code)
        {
            if (string.IsNullOrEmpty(account))
                throw new ArgumentNullException(nameof(account));

            var client = new MegaApiClient();

            var refreshToken = LoadRefreshToken(account);

            if (refreshToken != null) {
                client.Login(refreshToken);
            } else {
                if (string.IsNullOrEmpty(code))
                    throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.ProvideAuthenticationData, account));

                var parts = code.Split(new[] { ',' }, 2);
                if (parts.Length != 2)
                    throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.ProvideAuthenticationData, account));

                client.Login(parts[0], parts[1]);
            }

            refreshToken = (MegaApiClient.AuthInfos)typeof(MegaApiClient).GetField("_authInfos", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(client);
            SaveRefreshToken(account, refreshToken);

            return client;
        }
示例#26
0
        /// <inheritdoc cref="IFileUploader"/>
        /// <summary>
        /// Uploads the file to mega.nz.
        /// </summary>
        /// <returns>The result as <see cref="string"/>.</returns>
        /// <seealso cref="IFileUploader"/>
        public async Task <string> UploadToMega()
        {
            var client           = new MegaApiClient();
            var possibleAccounts = this.GetPossibleAccounts("mega");

            foreach (var account in possibleAccounts)
            {
                LoginMega(client, account);
                var info = await client.GetAccountInformationAsync();

                if (info.UsedQuota + GetFileSize(this.FileName) > info.TotalQuota)
                {
                    continue;
                }

                var root     = GetRootFolderMega(client);
                var progress = this.GetProgress();
                var node     = await client.UploadFileAsync(this.FileName, root, progress, null);

                var link = await client.GetDownloadLinkAsync(node);

                await client.LogoutAsync();

                return(link.AbsoluteUri);
            }

            return(string.Empty);
        }
示例#27
0
        public void Oauth(CloudType type)
        {
            CheckThread(true);
            Type type_oauthUI;

            switch (type)
            {
            case CloudType.Dropbox:
                DropboxOauthv2 oauth_dropbox = new DropboxOauthv2();
                oauth_dropbox.TokenCallBack += Oauth_dropbox_TokenCallBack;

                type_oauthUI       = LoadDllUI.GetTypeInterface(typeof(UIinterfaceDB));
                AppSetting.UIOauth = (OauthUI)Activator.CreateInstance(type_oauthUI);

                oauth_dropbox.GetCode(AppSetting.UIOauth, AppSetting.UIMain);
                break;


            case CloudType.GoogleDrive:
                GoogleAPIOauth2 oauth_gd = new GoogleAPIOauth2();
                oauth_gd.TokenCallBack += Oauth_gd_TokenCallBack;

                type_oauthUI       = LoadDllUI.GetTypeInterface(typeof(UIinterfaceGD));
                AppSetting.UIOauth = (OauthUI)Activator.CreateInstance(type_oauthUI);

                oauth_gd.GetCode(AppSetting.UIOauth, AppSetting.UIMain);
                break;


            case CloudType.Mega:
                type_oauthUI = LoadDllUI.GetTypeInterface(typeof(UIinterfaceMegaNz));
                UIinterfaceMegaNz mega = (UIinterfaceMegaNz)Activator.CreateInstance(type_oauthUI);
                bool error             = false;
reoauthMega:
                if (!error)
                {
                    mega.ShowDialog_();
                }
                else
                {
                    mega.ShowError("Wrong email or password.");
                }
                if (mega.Success)
                {
                    MegaApiClient.AuthInfos oauthinfo = MegaApiClient.GenerateAuthInfos(mega.Email, mega.Pass);
                    MegaApiClient           client    = new MegaApiClient();
                    try
                    {
                        client.Login(oauthinfo);
                    }
                    catch (Exception) { error = true; goto reoauthMega; }
                    SaveToken(mega.Email, JsonConvert.SerializeObject(oauthinfo), CloudType.Mega);
                }
                break;


            default: throw new Exception("Not support");
            }
        }
示例#28
0
 public void GenerateAuthInfos_InvalidCredentials_Throws(string email, string password)
 {
     Assert.That(() =>
                 MegaApiClient.GenerateAuthInfos(email, password),
                 Throws.TypeOf <ArgumentNullException>()
                 .With.Property <ArgumentNullException>(x => x.ParamName).EqualTo("email")
                 .Or.With.Property <ArgumentNullException>(x => x.ParamName).EqualTo("password"));
 }
示例#29
0
            public MegaApiClient Login()
            {
                MegaApiClient client = new MegaApiClient();
                AuthInfos     AI     = JsonConvert.DeserializeObject <AuthInfos>(Constants.AuthInfoJsonString);

                client.Login(AI);
                return(client);
            }
示例#30
0
        public static void CreateFolder(ExplorerNode node)
        {
            MegaNzNode    parent_meganode = new MegaNzNode(node.Parent.Info.ID);
            MegaApiClient client          = GetClient(node.GetRoot.NodeType.Email);
            INode         folder_meganode = client.CreateFolder(node.Info.Name, parent_meganode);

            node.Info.ID = folder_meganode.Id;
        }
示例#31
0
        public InitForm(Settings settings, MegaApiClient mega)
        {
            InitializeComponent();

            _chrs     = new Dictionary <int, char>();
            _settings = settings;
            _mega     = mega;
        }
示例#32
0
        public static MegaApiClient GetClient(string email)
        {
            MegaApiClient client = new MegaApiClient();

            MegaApiClient.AuthInfos authinfo = JsonConvert.DeserializeObject <MegaApiClient.AuthInfos>(AppSetting.settings.GetToken(email, CloudType.Mega));
            client.Login(authinfo);
            return(client);
        }
示例#33
0
        public static ExplorerNode GetItem(ExplorerNode node)
        {
            MegaApiClient client = GetClient(node.GetRoot.NodeType.Email);
            MegaNzNode    inode  = new MegaNzNode(node.Info.ID);

            GetItems(client, inode, node);
            return(node);
        }
        private static void SaveRefreshToken(string account, MegaApiClient.AuthInfos refreshToken)
        {
            var refreshTokens = Settings.Default.RefreshTokens;
            if (refreshTokens != null) {
                foreach (RefreshTokenSetting setting in refreshTokens)
                    if (setting.Account == account) {
                        refreshTokens.Remove(setting);
                        break;
                    }
            } else {
                refreshTokens = Settings.Default.RefreshTokens = new System.Collections.ObjectModel.Collection<RefreshTokenSetting>();
            }

            refreshTokens.Insert(0, new RefreshTokenSetting() { Account = account, EMail = refreshToken.Email, Hash = refreshToken.Hash, PasswordAesKey = refreshToken.PasswordAesKey });

            Settings.Default.Save();
        }
示例#35
0
        /// <summary>
        /// Constructor for PackBlock
        /// </summary>
        /// <param name="packBlock"></param>
        /// <param name="installerWorker"></param>
        /// <param name="progressFile"></param>
        /// <param name="progressAll"></param>
        /// <param name="progressCurFile"></param>
        /// <param name="progressText"></param>
        /// <param name="progressDetails"></param>
        /// <param name="launcherButton"></param>
        public Downloader(PackBlock packBlock, Installer installerWorker, Windows7ProgressBar progressFile, Windows7ProgressBar progressAll, Label progressCurFile, Label progressText, Label progressDetails, PictureBox launcherButton)
        {
            this.activeForm = "packBlock";

            this.packBlock = packBlock;
            this.installer = installerWorker;
            this.megaClient = new MegaApiClient();

            // construct error report
            this.reportError = new EmailReporter();

            // define controls
            this.progressCurFile = progressCurFile;
            this.progressFile = progressFile;
            this.progressAll = progressAll;
            this.progressText = progressText;
            this.progressDetails = progressDetails;
            this.launcherButton = launcherButton;

            // define calculate worker
            this.calculateFiles.DoWork += CalculateFiles_DoWork;
            this.calculateFiles.RunWorkerCompleted += CalculateFiles_RunWorkerCompleted;
            this.calculateFiles.WorkerSupportsCancellation = true;

            // define download worker
            this.downloadFiles.DoWork += DownloadFiles_DoWork;
            this.downloadFiles.RunWorkerCompleted += DownloadFiles_RunWorkerCompleted;
            this.downloadFiles.WorkerSupportsCancellation = true;
        }
示例#36
0
 public void Login_NullAuthInfos_Throws(MegaApiClient.AuthInfos authInfos)
 {
     Assert.That(
         () => this.Client.Login(authInfos),
         Throws.TypeOf<ArgumentNullException>()
         .With.Property<ArgumentNullException>(x => x.ParamName).EqualTo("authInfos"));
 }
示例#37
0
        public void Setup()
        {
            this.Client = new MegaApiClient(new PollyWebClient());
            if (this._options.HasFlag(Options.LoginAuthenticated))
            {
                this.Client.Login(Username, Password);
            }

            if (this._options.HasFlag(Options.LoginAnonymous))
            {
                this.Client.LoginAnonymous();
            }

            if (this._options.HasFlag(Options.Clean))
            {
                this.SanitizeStorage();
            }
        }
示例#38
0
文件: Mega.cs 项目: aeax/ShareX
 public Mega(MegaApiClient.AuthInfos authInfos)
     : this(authInfos, null)
 {
 }
 public MegaContext(MegaApiClient client)
 {
     Client = client;
 }