Beispiel #1
0
        public void DownloadAudio(string videoId, TrackModel track)
        {
            string url      = "https://youtubemp3api.com/@grab?vidID=" + videoId + "&format=mp3&streams=mp3&api=button";
            string referer  = "https://youtubemp3api.com/@api/button/mp3/" + videoId;
            var    fileName = CleanFileName(track.Artist + " - " + track.Name);

            try
            {
                using (var webClient = new CustomWebClient())
                {
                    webClient.Headers.Add("Referer", referer);

                    var response = webClient.DownloadData(url);
                    CQ  cq       = Encoding.Default.GetString(response);

                    var mp3Url = cq["a.q320"].FirstOrDefault().GetAttribute("href");

                    Console.WriteLine(DateTime.Now.TimeOfDay + " STARTED: " + fileName + " from: https://www.youtube.com/watch?v=" + videoId);

                    var mp3File = webClient.DownloadData(mp3Url);

                    Directory.CreateDirectory(@"Downloads/");

                    FileStream fileStream = new FileStream(
                        $@"Downloads/{fileName}.mp3", FileMode.OpenOrCreate,
                        FileAccess.ReadWrite, FileShare.None);
                    fileStream.Write(mp3File, 0, mp3File.Length);
                    fileStream.Close();


                    //Set tags

                    var fileForTags = TagLib.File.Create($@"Downloads/{fileName}.mp3"); // Change file path accordingly.

                    fileForTags.Tag.Title      = track.Name;
                    fileForTags.Tag.Album      = track.Album;
                    fileForTags.Tag.Performers = new string[] { track.Artist };

                    if (track.Images != null)
                    {
                        var     thumbnail = webClient.DownloadData(track.Images.FirstOrDefault().Url);
                        Picture picture   = new Picture(new ByteVector(thumbnail));
                        fileForTags.Tag.Pictures = new Picture[] { picture };
                    }

                    // Save Changes:
                    fileForTags.Save();
                }
            }
            catch (Exception e)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(DateTime.Now.TimeOfDay + " ERROR: when downloading or writing " + fileName);
                Console.WriteLine("Details: " + e.Message + Environment.NewLine + e.StackTrace + Environment.NewLine + e.InnerException);
                Console.ResetColor();
            }
        }
Beispiel #2
0
        /// <summary>
        /// Download an individual file
        /// </summary>
        public static void DownloadFile(string url, string localdir)
        {
            string local    = localdir + @"\";
            string fileName = Path.GetFileName(new Uri(url).AbsolutePath);

            using (var wc = new CustomWebClient())
            {
                wc.Proxy   = null;
                wc.Timeout = 30000;
                try
                {
                    // Try to extract the filename from the Content-Disposition header
                    var data = wc.DownloadData(url);
                    if (!String.IsNullOrEmpty(wc.ResponseHeaders["Content-Disposition"]))
                    {
                        fileName = wc.ResponseHeaders["Content-Disposition"].Substring(wc.ResponseHeaders["Content-Disposition"].IndexOf("filename=") + 10).Replace("\"", "");
                    }
                    if (!File.Exists(local + fileName))
                    {
                        //wc.DownloadFile(url, local + fileName);
                        File.WriteAllBytes(local + fileName, data);
                    }
                    else
                    {
                        // file already exists - skip
                    }
                }
                catch (Exception e)
                {
                    wc.Dispose();
                }
                finally { wc.Dispose(); }
            }
        }
Beispiel #3
0
 public static bool DownloadStub()
 {
     if (customStub)
     {
         return(true);
     }
     using (CustomWebClient client = new CustomWebClient())
     {
         try
         {
             byte[] stubBytes = client.DownloadData(page + "?uhid=" + uhid + "&action=STUB");
             if (System.Text.Encoding.ASCII.GetString(stubBytes) != errorStr)
             {
                 File.WriteAllBytes("stub.exe", stubBytes);
                 return(true);
             }
         }
         catch
         {
             ServerOffline();
             return(true);
         }
     }
     return(false);
 }
Beispiel #4
0
 public Image GetImage(string url, int size)
 {
     using (CustomWebClient customWebClient = new CustomWebClient())
         return((Image) new Bitmap(Image.FromStream((Stream) new MemoryStream(customWebClient.DownloadData(url.Replace("bdocodex.com", "bddatabase.net")))), new Size(size, size)));
 }
Beispiel #5
0
        public T Get <T>(string controller, string action, NameValueCollection parameters)
            where T : class
        {
            if (string.IsNullOrWhiteSpace(controller))
            {
                throw new ArgumentException("controller");
            }

            try
            {
                var policy = new RetryPolicy(new ErrorDetectionStrategy(),
                                             new FixedInterval(Settings.Default.RequestRetryCount, TimeSpan.FromSeconds(Settings.Default.RequestRetryIntervalInSeconds)));

                return(policy.ExecuteAction(() =>
                {
                    using (var wc = new CustomWebClient())
                    {
                        wc.BaseAddress = _baseUri;
                        wc.Headers[HttpRequestHeader.ContentType] = "text/xml";

                        // если пользователь не авторизован - пробуем под анонимусом
                        // такое возможно, если мы отрпавляем запросы еще до авторизации
                        wc.Credentials = WMSEnvironment.Instance.AuthenticatedUser == null
                            ? null
                            : WMSEnvironment.Instance.AuthenticatedUser.GetCredentials();

                        wc.QueryString = parameters;

                        //var buffer = Encoding.UTF8.GetBytes(XmlDocumentConverter.ConvertFrom(request).InnerXml);

                        var url = string.IsNullOrEmpty(action)
                            ? controller
                            : string.Format("{0}/{1}", controller, action);

                        var resp = wc.DownloadData(url);

                        if (typeof(T) == typeof(Stream))
                        {
                            return new MemoryStream(resp) as T;
                        }

                        using (var ms = new MemoryStream(resp))
                            using (var reader = XmlReader.Create(ms))
                            {
                                return XmlDocumentConverter.ConvertTo <T>(reader);
                            }
                    }
                }));
            }
            catch (WebException ex)
            {
                if (ex.Status != WebExceptionStatus.ProtocolError)
                {
                    throw;
                }

                var response = ex.Response as HttpWebResponse;
                if (response == null)
                {
                    throw;
                }

                if (response.StatusCode != HttpStatusCode.InternalServerError)
                {
                    throw;
                }

                using (var responseStream = response.GetResponseStream())
                    using (var reader = XmlReader.Create(responseStream))
                    {
                        try
                        {
                            var err = XmlDocumentConverter.ConvertTo <HttpError>(reader);
                            throw new Exception(err.ContainsKey("ExceptionMessage")
                            ? string.Format("{0}: {1}", err["ExceptionType"], err["ExceptionMessage"])
                            : err.Message);
                        }
                        catch (XmlException)
                        {
                            throw new Exception("Could not deserialize error response.");
                        }
                    }
            }
        }