Beispiel #1
0
        public IList<Track> Search(string query)
        {
            var result = new List<Track>();
            try
            {
                Ping pinger = new Ping();
                PingOptions pingerOptions = new PingOptions(255, true);
                string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
                byte[] buffer = Encoding.ASCII.GetBytes(data);
                int timeout = 60000;
                string hostName = @"vk.com";
                PingReply reply = pinger.Send(hostName, timeout, buffer, pingerOptions);
                if (reply.Status != IPStatus.Success)
                {
                    return new ReadOnlyCollection<Track>(result);
                }

                if (_cookie == null)
                {
                    var res = Auth(Config.GetInstance().VKLogin, Config.GetInstance().VKPassword, out _cookie);
                    if (!res)
                    {
                        throw new Exception("Failed to authorize at vk.com.");
                    }
                }

                var url = "http://vk.com/gsearch.php?section=audio&q=" + HttpUtility.UrlEncode(query) + "&name=1";

                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(_cookie);

                var responseStream = request.GetResponse().GetResponseStream();
                string content = "";

                using (var reader = new StreamReader(responseStream, Encoding.GetEncoding(1251)))
                {
                    content = reader.ReadToEnd();
                }

                Regex tableRegex = new Regex(@"(<table id=""searchResults""(.|\n)*>(.|\n)*)<td id=""filters""", RegexOptions.Multiline);

                content = tableRegex.Match(content).Groups[1].Value;
                content = StripHtmlEntities(content) + "</tr></table>";

                // Нет метки о том, что ничего не найдено
                if (!content.Contains("noResults"))
                {
                    var doc = XDocument.Load(new StringReader(content));
                    var td = doc.Root.XPathSelectElement("tr/td");
                    XElement tmpElement;
                    Regex onclickRegex = new Regex(@"\((.*)\)");

                    foreach (var div in td.Elements())
                    {
                        var track = new Track();

                        string onImgClick = div.XPathSelectElement("table/tbody/tr/td/img").Attribute("onclick").Value;
                        var match = onclickRegex.Match(onImgClick);

                        if (!match.Success)
                            continue;

                        var terms = match.Groups[1].Value.Replace("\'", "").Split(',');

                        track.Uri = new Uri("http://cs" + terms[1] + ".vkontakte.ru/u" + terms[2] + "/audio/" +
                            terms[3] + ".mp3");

                        tmpElement = div.XPathSelectElements("table/tbody/tr/td/div").
                            Where(el => el.Attribute("class").Value == "audioTitle").First();

                        track.Singer = tmpElement.XPathSelectElement("b").Value;

                        track.Title = (from element in tmpElement.Elements("span")
                                       where (element.Attribute("id") != null) && element.Attribute("id").Value.Contains("title")
                                       select element.Value).First();

                        var duration = (from element in tmpElement.Parent.Elements("div")
                                        where element.Attribute("class").Value == "duration"
                                        select element.Value).First();

                        TimeSpan tmp;
                        TimeSpan.TryParse("00:" + duration, out tmp);
                        track.Duration = tmp;
                        track.Source = TrackSource.VK;

                        track.Id = track.GetHash();

                        result.Add(track);

                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("VKComDataProvider error: " + e.Message);
                Console.WriteLine("Query: " + query);
            }

            return new ReadOnlyCollection<Track>(result);
        }
        public IList<Track> Search(string query)
        {
            var result = new List<Track>();
            try
            {
                if (_cookie == null)
                {
                    var res = Auth(Config.GetInstance().VKLogin, Config.GetInstance().VKPassword, out _cookie);
                    if (!res)
                    {
                        throw new Exception("Failed to authorize at vk.com.");
                    }
                }

                var url = "http://vk.com/al_search.php";

                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(_cookie);
                request.ContentType = @"application/x-www-form-urlencoded";
                request.Method = "POST";

                string parameters = "al=1&c[q]=" + HttpUtility.UrlEncode(query).ToUpper() + "&c[section]=audio";
                byte[] message = Encoding.UTF8.GetBytes(parameters);
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(message, 0, message.Length);
                    requestStream.Close();
                }

                var responseStream = request.GetResponse().GetResponseStream();
                string content = "";

                using (var reader = new StreamReader(responseStream, Encoding.GetEncoding(1251)))
                {
                    content = reader.ReadToEnd();
                }



                string techInfo = @"(<!--.*<!>|<!--.*->|<!>)";
                content = Regex.Replace(content, techInfo, String.Empty);

                // Нет метки о том, что ничего не найдено
                if (content != "")
                {
                    content = "<div>" + content + "</div>";
                    content = StripHtmlEntities(content);
                    var doc = XDocument.Load(new StringReader(content));
                    XElement audioElement;

                    var elements = doc.Root.Elements();

                    foreach (var divTrack in elements)
                    {
                        var track = new Track();
                        audioElement = divTrack;

                        if (audioElement.FirstAttribute.Value == "search_more_results")
                        {
                            break;
                        }

                        var trackUri = audioElement.XPathSelectElement("div/table/tr/td/input").Attribute("value").Value;

                        var terms = trackUri.Replace("\'", "").Split(',');

                        var startId = terms[0].IndexOf("audio/") + "audio/".Length;
                        var finishId = terms[0].IndexOf(".mp3");

                        track.Id = terms[0].Substring(startId, finishId - startId);
                        track.Uri = new Uri(terms[0]);

                        string titleTag = audioElement.XPathSelectElements("div/table/tr/td/div/span").First().ToString(SaveOptions.DisableFormatting);
                        track.Title = PrepareTitle(titleTag);
                        string singerTag = audioElement.XPathSelectElements("div/table/tr/td/div/b/a").First().ToString(SaveOptions.DisableFormatting);
                        track.Singer = PrepareTitle(singerTag);

                        var duration = audioElement.XPathSelectElements("div/table/tr/td/div").
                            Where(el => el.Attribute("class").Value == "duration fl_r").First().Value;

                        TimeSpan tmp;
                        TimeSpan.TryParse("00:" + duration, out tmp);
                        track.Duration = tmp;

                        track.Source = TrackSource.VK;

                        track.Id = track.GetHash();

                        result.Add(track);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("VKComDataProvider error: " + e.Message);
                Console.WriteLine("Query: " + query);
            }

            return new ReadOnlyCollection<Track>(result);
        }
        public IList<Track> Search(string query)
        {
            var result = new List<Track>();
            try
            {
                if (_cookie == null)
                {
                    var res = Auth(Config.GetInstance().VKLogin, Config.GetInstance().VKPassword, out _cookie);
                    if (!res)
                    {
                        throw new Exception("Failed to authorize at vk.com.");
                    }
                }

                string url = "http://vk.com/al_search.php";
                string parameters = "al=1&c[q]=" + HttpUtility.UrlEncode(query).ToUpper() + "&c[section]=audio";

                string content = MakeRequest(url, parameters, _cookie);
                
                string techInfo = @"(<!--.*<!>|<!--.*->|<!>)";
                content = Regex.Replace(content, techInfo, String.Empty);

                // Нет метки о том, что ничего не найдено
                if (content != "")
                {
                    content = "<div>" + content + "</div>";
                    content = StripHtmlEntities(content);
                    var doc = XDocument.Load(new StringReader(content));
                    XElement audioElement;
                    content = null;
                    var elements = doc.Root.Elements();

                    foreach (var divTrack in elements)
                    {
                        try
                        {
                            var track = new Track();
                            audioElement = divTrack;

                            if (audioElement.FirstAttribute.Value == "search_more_results")
                            {
                                break;
                            }

                            var audioData = audioElement.Attribute("data-audio").Value.Split(new string[] { " quot;," }, StringSplitOptions.None);
                            track.Uri = new Uri(audioElement.Attribute("data-full-id").Value, UriKind.Relative);
                            track.Title = PrepareDataLine(audioData[3]);
                            track.Singer = PrepareDataLine(audioData[4]);
                            track.Duration = TimeSpan.FromSeconds(Convert.ToDouble(audioData[5].Split(',')[0]));
                            track.Source = TrackSource.VK;

                            track.Id = track.GetHash();

                            result.Add(track);
                        }
                        catch (Exception innerE)
                        {
                            Debug.WriteLine("VKComDataProvider (track parse): " + innerE.Message);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("VKComDataProvider (global): " + e.Message);
                Debug.WriteLine("Query: " + query);
            }

            

            return new ReadOnlyCollection<Track>(result);
        }