public byte[] Download(Track track) {
            if (track.Source == TrackSource.VK)
            {
                return DataProviders[1].Download(track);
            }
            return null;
		}
		public byte[] Download(Track track) {
			try {
				WebClient c = new WebClient();
				return c.DownloadData("http://prostopleer.com/download/" + track.Id);
			} catch {
				return null;
			}
		}
		public IList<Track> Search(string query) {
			// Result
			var result = new List<Track>();
			try {
				Debug.Print(": " + query);

				// Download results
				var webClient = new WebClient();
				webClient.Encoding = Encoding.UTF8;
				webClient.Headers.Add("X-Requested-With", "XMLHttpRequest");
				var response = webClient.DownloadString("http://prostopleer.com/search?q=" + query.Replace(" ", "%20"));

				// Prepare and parse string
				response = response.Substring(25, response.Length - 25 - 2);
				var regExp = new Regex("<li (.*?)>", RegexOptions.Compiled);
				foreach (Match item in regExp.Matches(response)) {
					var xmlString = item.ToString().Replace("\\\"", "\"").Replace("<li ", "").Replace(">", "");

					Track tr = new Track();
					var regExp2 = new Regex("([^=,]*)=(\"[^\"]*\"|[^,\"]*)", RegexOptions.Compiled);
					foreach (Match item2 in regExp2.Matches(xmlString)) {
						var key = item2.Groups[1].ToString().Trim().ToLowerInvariant();
						var value = item2.Groups[2].ToString().Trim().ToLowerInvariant().Replace("\"", "");

						switch (key) {
						case "duration": tr.Duration = TimeSpan.FromSeconds(int.Parse(value)); break;
						case "singer": tr.Singer = value; break;
						case "song": tr.Title = value; break;
						case "file_id": tr.Id = value; break;
						}
					}
					result.Add(tr);
				}
			} catch {
				Debug.Print(": shit happens");
			}

			Debug.Print(": shomething found");
			return new ReadOnlyCollection<Track>(result);
		}
Beispiel #4
0
		public void Remove(Track track) {
			Player.Instance.Playlist.Tracks.Remove(track);
		}
Beispiel #5
0
		public void Add(Track track) {
            string userAddress = GetUserAddress();
			Player.Instance.Playlist.Tracks.Add(track);
            UserManager.Instance.AddActionPoints(userAddress, 1);
		}
        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 byte[] Download(Track track)
 {
     try
     {
         WebClient c = new WebClient();
         return c.DownloadData(track.Uri);
     }
     catch (Exception e)
     {
         Console.WriteLine("VKComDataProvider error: " + e.Message);
     }
     return null;
 }
        public IList<Track> Search(string query) {
            var result = new List<Track>();
            try
            {
                //<DANGEROUS HARD CODE>
                var hashmap = Config.GetInstance().CacheDir + "hashmap.txt";
                //</DANGEROUS HARD CODE>

                if (!File.Exists(hashmap))
                {
                    return new ReadOnlyCollection<Track>(result);
                }

                List<string> queryWords = query.ToUpper().Split(' ').ToList();
           
                string[] lines = File.ReadAllLines(hashmap).Reverse().ToArray();
                List<KeyValuePair<int, string>> mostPossibleResults = new List<KeyValuePair<int, string>>();

                foreach (string line in lines)
                {
                    string tempLine = String.Join(" ",line.ToUpper().Split('|').Skip(1).Take(2).ToList());

                    bool hasAllQueryWords = true;
                    int relevance = 0;
                    int prevIndex = -1;
                    int currentIndex = -1;
                    foreach (string word in queryWords)
                    {
                        if (tempLine.Contains(word))
                        {
                            currentIndex = tempLine.IndexOf(word);
                            if (HasExactWord(tempLine, word))
                            {
                                currentIndex = ExactWordIndex(tempLine, word);
                                relevance += 3;
                            }
                            else
                            {
                                relevance++;
                            }

                            if (prevIndex != -1)
                            {
                                if (currentIndex > prevIndex)
                                {
                                    relevance++;
                                }
                            }
                            prevIndex = currentIndex;
                        }
                        else
                        {
                            hasAllQueryWords = false;
                            break;
                        }
                    }
                    if (hasAllQueryWords)
                    {
                        KeyValuePair<int, string> pair = new KeyValuePair<int, string>(relevance, line);
                        mostPossibleResults.Add(pair);
                    }
                }

                foreach(var mostPossibleRow in mostPossibleResults.OrderByDescending(x=>x.Key))
                {
                    Track track = new Track();

                    var values = mostPossibleRow.Value.Split('|');

                    var hash = values[0];
                    var singer = values[1];
                    var title = values[2];
                    var duration = values[3];

                    if (!File.Exists(Config.GetInstance().CacheDir + hash + ".mp3"))
                    {
                        continue;
                    }

                    track.Id = hash;
                    track.Singer = singer;
                    track.Title = title;
                    TimeSpan tmp;
                    TimeSpan.TryParse(duration, out tmp);
                    track.Duration = tmp;
                    track.Source = TrackSource.Cache;
                    result.Add(track);
                }
                
            }
            catch
            {
                Console.WriteLine("FileSystemDataProvider error");
                Console.WriteLine("Query: " + query);
            }

            return new ReadOnlyCollection<Track>(result);
		}
		public byte[] Download(Track track) {
			throw new NotImplementedException();
		}
Beispiel #10
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);
        }
Beispiel #11
0
        public byte[] Download(Track track)
        {
            try
            {
                WebDownload c = new WebDownload();
                c.Timeout = Config.GetInstance().DownloadTimeout;

                return c.DownloadData(track.Uri);
            }
            catch (Exception e)
            {
                Console.WriteLine("VKComDataProvider error: " + e.Message);
            }
            return null;
        }
Beispiel #12
0
        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);
        }
Beispiel #13
0
        public byte[] Download(Track track)
        {
            try
            {
                string url = "http://vk.com/al_audio.php";
                string parameters = "act=reload_audio&al=1&ids=" + HttpUtility.UrlEncode(track.Uri.OriginalString);

                string content = MakeRequest(url, parameters, _cookie);

                var trackUrl = content.Split(new string[] { "<!json>[[" }, StringSplitOptions.None)[1].Split(',')[2];
                trackUrl = Regex.Unescape(trackUrl).Replace("\"", "");
                track.Uri = new Uri(trackUrl);

                WebDownload downloader = new WebDownload();
                downloader.Timeout = Config.GetInstance().DownloadTimeout;

                Stream trackStream = downloader.OpenRead(track.Uri);
                MemoryStream resultStream = new MemoryStream();

                byte[] buffer = new byte[4096];
                while (trackStream.CanRead)
                {
                    Array.Clear(buffer, 0, buffer.Length);
                    int bytesRead = trackStream.Read(buffer, 0, buffer.Length);

                    if (bytesRead == 0)
                    {
                        break;
                    }

                    resultStream.Write(buffer, 0, bytesRead);
                }

                return resultStream.ToArray();
            }
            catch (Exception e)
            {
                Console.WriteLine("VKComDataProvider error: " + e.Message);
            }
            return null;
        }