AcManager.Tools.Helpers.Loaders.GoogleDriveLoader.PrepareAsync C# (CSharp) Method

PrepareAsync() public method

public PrepareAsync ( WebClient client, CancellationToken cancellation ) : Task
client System.Net.WebClient
cancellation System.Threading.CancellationToken
return Task
        public override async Task<bool> PrepareAsync(WebClient client, CancellationToken cancellation) {
            if (!Url.Contains("://drive.google.com/uc?", StringComparison.OrdinalIgnoreCase)) return true;

            // TODO: drop if page is bigger than, let’s say, 1MB
            var downloadPage = await client.DownloadStringTaskAsync(Url);
            if (cancellation.IsCancellationRequested) return false;

            if (client.ResponseHeaders?.Get("Content-Type").Contains("text/html", StringComparison.OrdinalIgnoreCase) == false) return true;
            var match = Regex.Match(downloadPage, @"href=""(/uc\?export=download[^""]+)", RegexOptions.IgnoreCase);
            if (!match.Success) {
                NonfatalError.Notify(ToolsStrings.Common_CannotDownloadFile, ToolsStrings.DirectLoader_GoogleDriveChanged);
                return false;
            }

            Url = "https://drive.google.com" + HttpUtility.HtmlDecode(match.Groups[1].Value);
            Logging.Write("Google Drive download link: " + Url);

            try {
                var totalSizeMatch = Regex.Match(downloadPage, @"</a> \((\d+(?:\.\d+)?)([KMGT])\)</span> ");
                if (totalSizeMatch.Success) {
                    var value = double.Parse(totalSizeMatch.Groups[1].Value, CultureInfo.InvariantCulture);
                    var unit = totalSizeMatch.Groups[2].Value;

                    switch (unit.ToLowerInvariant()) {
                        case "k":
                            value *= 1024;
                            break;

                        case "m":
                            value *= 1024 * 1024;
                            break;

                        case "g":
                            value *= 1024 * 1024 * 1024;
                            break;

                        case "t":
                            value *= 1024d * 1024 * 1024 * 1024;
                            break;
                    }

                    TotalSize = (long)value;
                }
            } catch (Exception) {
                // ignored
            }

            return true;
        }
    }