// 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);
        }
Esempio n. 2
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);
            }
        }
        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();
            }
        }
Esempio n. 4
0
        public async Task <bool> PrepareAsync(CookieAwareWebClient client, CancellationToken cancellation)
        {
            _client = new MegaApiClient();
            await _client.LoginAnonymousAsync();

            var information = await _client.GetNodeFromLinkAsync(_uri);

            TotalSize = information.Size;
            FileName  = information.Name;
            return(true);
        }
Esempio n. 5
0
    /// <summary>
    /// Downloads the file using the specified mega url
    /// </summary>
    /// <param name="megaUrl">The mega url</param>
    /// <param name="onAnswerCallback">The on answer callback</param>
    public async Task DownloadFileAsync(string megaUrl, Func <CallbackAnswer, Task> onAnswerCallback)
    {
        try
        {
            double downloadProgress = 0;
            var    swUpdater        = Stopwatch.StartNew();
            Log.Information("Starting download from Mega. Url: {0}", megaUrl);
            var client = new MegaApiClient();
            await client.LoginAnonymousAsync();

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

            var nodeName = node.Name;

            Log.Debug("Downloading {0}", nodeName);
            IProgress <double> progressHandler = new Progress <double>(async x => {
                downloadProgress = x;

                if (swUpdater.Elapsed.Seconds < 5)
                {
                    return;
                }
                swUpdater.Restart();
                await onAnswerCallback(new CallbackAnswer()
                {
                    CallbackAnswerMode = CallbackAnswerMode.EditMessage,
                    CallbackAnswerText = $"Downloading Progress: {downloadProgress:.##} %"
                });

                // await telegramService.EditMessageTextAsync($"Downloading Progress: {downloadProgress:.##} %");
                // swUpdater.Start();
            });

            await client.DownloadFileAsync(fileLink, nodeName, progressHandler);
        }
        catch (Exception ex)
        {
            await onAnswerCallback(new CallbackAnswer()
            {
                CallbackAnswerMode = CallbackAnswerMode.SendMessage,
                CallbackAnswerText = $"Sesuatu kesalahan telah terjadi."
            });

            // await telegramService.SendTextMessageAsync($"🚫 <b>Sesuatu telah terjadi.</b>\n{ex.Message}");
        }
    }
        public async Task DownloadUrlAsync(ICrawledUrl crawledUrl, string downloadPath, bool overwriteFiles = false)
        {
            _logger.Debug($"[MEGA] Staring downloading {crawledUrl.Url}");

            Uri uri = new Uri(crawledUrl.Url);

            if (await IsUrlAFolder(uri))
            {
                await DownloadFolderAsync(uri, Path.Combine(downloadPath, crawledUrl.DownloadPath), overwriteFiles);
            }
            else
            {
                (_, string id, _) = MegaUrlDataExtractor.Extract(crawledUrl.Url);
                INodeInfo fileNodeInfo = await _client.GetNodeFromLinkAsync(uri);

                string path = Path.Combine(downloadPath, crawledUrl.DownloadPath,
                                           $"{id.Substring(0, 5)}_{fileNodeInfo.Name}");
                await DownloadFileAsync(null, uri, fileNodeInfo, path, overwriteFiles);
            }

            _logger.Debug($"[MEGA] Finished downloading {crawledUrl.Url}");
        }
Esempio n. 7
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();
            }

            var information = await _client.GetNodeFromLinkAsync(_uri);

            TotalSize = information.Size;
            FileName  = information.Name;
            return(true);
        }
Esempio n. 8
0
        public override async Task <(ISource source, string failReason)> FindHandlerAsync(DiscordMessage message, ICollection <IArchiveHandler> handlers)
        {
            if (string.IsNullOrEmpty(message.Content))
            {
                return(null, null);
            }

            var matches = ExternalLink.Matches(message.Content);

            if (matches.Count == 0)
            {
                return(null, null);
            }

            var client = new MegaApiClient();
            await client.LoginAnonymousAsync();

            foreach (Match m in matches)
            {
                try
                {
                    if (m.Groups["mega_link"].Value is string lnk &&
                        !string.IsNullOrEmpty(lnk) &&
                        Uri.TryCreate(lnk, UriKind.Absolute, out var uri))
                    {
                        var node = await client.GetNodeFromLinkAsync(uri).ConfigureAwait(false);

                        if (node.Type == NodeType.File)
                        {
                            var buf = bufferPool.Rent(1024);
                            try
                            {
                                int read;
                                using (var stream = await client.DownloadAsync(uri, doodad, Config.Cts.Token).ConfigureAwait(false))
                                    read = await stream.ReadBytesAsync(buf).ConfigureAwait(false);
                                foreach (var handler in handlers)
                                {
                                    var(canHandle, reason) = handler.CanHandle(node.Name, (int)node.Size, buf.AsSpan(0, read));
                                    if (canHandle)
                                    {
                                        return(new MegaSource(client, uri, node, handler), null);
                                    }
                                    else if (!string.IsNullOrEmpty(reason))
                                    {
                                        return(null, reason);
                                    }
                                }
                            }
                            finally
                            {
                                bufferPool.Return(buf);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Config.Log.Warn(e, $"Error sniffing {m.Groups["mega_link"].Value}");
                }
            }
            return(null, null);
        }