public LyricsInfo SearchLyricsAsync(string artist, string song) { var geniusClient = new GeniusClient(); Song songInfo = geniusClient.Search($"{artist} {song}"); String uri = songInfo.Url; var client = new HttpClient(); var response = client.GetAsync(uri).GetAwaiter().GetResult(); LyricsInfo lyricsInfo = null; if (response.IsSuccessStatusCode) { lyricsInfo = new LyricsInfo(); lyricsInfo.Artist = songInfo.Artist; lyricsInfo.Song = songInfo.Title; lyricsInfo.ThumbnailUrl = songInfo.ThumbnailUrl; var body = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(body); var lyricsDiv = doc.DocumentNode.SelectSingleNode("//div[@class='lyrics']"); lyricsInfo.Lyrics = lyricsDiv.InnerText.Trim(); } response.Dispose(); client.Dispose(); return(lyricsInfo); }
public ParserGenius(string query = "NEFFEX - Trust me") { var geniusClient = new GeniusClient("0KELsTGebL5A6ZExHu-h4sLL7MlZxoX_4DKfGgXC1RrilwKQhWpGeMcXik0hMZ35"); var result = geniusClient.SearchClient.Search(TextFormat.Dom, query); var firstHit = result.Result.Response.First(); string str = firstHit.Result.ToString(); //Создаём устойчивое выражение, чтобы найти id нашей песни var regex = new Regex(@"(\W)id(\W):\s\d*"); var collection = regex.Matches(str); var matches = collection.First(); Console.WriteLine($"Found this id: {matches.Value}"); string id = matches.Value.Remove(0, 6); //По пулученному id получаем песню Song song = geniusClient.SongsClient.GetSong(TextFormat.Dom, id).Result.Response; if (song is null) { Console.WriteLine("Song is null, next actions stopped."); return; } Console.WriteLine($"URl : {song.Url}"); _fullAddress = song.Url; if (_fullAddress is null) { Console.WriteLine("Address is null, next actions stopped."); return; } }
/// <summary> /// Create a new genius fetcher that requires a <paramref name="geniusApiKey" /> to query on https://genius.com. /// It can expand / modify the artist information from a song. /// </summary> /// <param name="geniusApiKey"> /// The API-key that will be used for the queries (i.e. to create the /// <see cref="GeniusClient" />). /// </param> public GeniusSongInfoFetcher(string geniusApiKey) { if (string.IsNullOrWhiteSpace(geniusApiKey)) { throw new ArgumentException("Value cannot be null or whitespace.", nameof(geniusApiKey)); } GeniusClient = new GeniusClient(geniusApiKey); }
public async Task <SearchHit> SearchGeniusAsync(string searchValue) { var client = new GeniusClient(ConfigData.Data.Genius.AccessToken); var result = await client.SearchClient.Search(searchValue); if (!result.Response.Hits.Any()) { return(null); } return(result.Response.Hits[0]); }
public async Task <SongResult> GetUrlAsync(string searchValue) { var client = new GeniusClient(ConfigData.Data.GeniusAccessToken); var result = await client.SearchClient.Search(TextFormat.Dom, searchValue); if (!result.Response.Any()) { return(null); } var songObject = result.Response[0].Result as JObject; return(songObject?.ToObject <SongResult>()); }
/// <summary> /// Create a new genius fetcher that requires a <paramref name="geniusApiKey" /> to query on https://genius.com. /// It can expand / modify the artist information from a song. /// </summary> /// <param name="geniusApiKey"> /// The API-key that will be used for the queries (i.e. to create the /// <see cref="GeniusClient" />). If the genius api key is <code>null</code> (or empty), then the constructor will try to find a /// system variable identified by <see cref="GeniusSystemVariable"/> and use this value instead. /// </param> public GeniusSongInfoFetcher(string geniusApiKey = null) { if (string.IsNullOrWhiteSpace(geniusApiKey)) { geniusApiKey = Environment.GetEnvironmentVariable(GeniusSystemVariable); } if (string.IsNullOrWhiteSpace(geniusApiKey)) { throw new ArgumentException( $"Value cannot be null or whitespace. System variable ${GeniusSystemVariable} is also not set.", nameof(geniusApiKey)); } GeniusClient = new GeniusClient(geniusApiKey); }
public static async Task Main(string[] args) { try { // Genius.NET doesn't provide OAuth related wrappers. var client = new GeniusClient("API_KEY"); // GET /annotations/:id var annotation = await client.AnnotationClient.GetAnnotation(10225840); // POST /annotations var newAnnotation = await client.AnnotationClient.PostAnnotation( new AnnotationPayload("hello **world!**", new ReferentPayload("http://seejohncode.com/2014/01/27/vim-commands-piping/", "execute commands", new ContextForDisplay("You may know that you can", " from inside of vim, with a vim command:")), new WebPagePayload(title: "Secret of Mana"))); // PUT /annotations var updatedAnnotation = await client.AnnotationClient.UpdateAnnotation( new AnnotationPayload("hello **world!**", new ReferentPayload("http://seejohncode.com/2014/01/27/vim-commands-piping/", "execute commands", new ContextForDisplay("You may know that you can", " from inside of vim, with a vim command:")), new WebPagePayload(title: "Secret of Mana"))); // DELETE /annotations/:id var deletedAnnotation = await client.AnnotationClient.DeleteAnnotation(10225840); // PUT /annotations/:id/upvote var upvotedAnnotation = await client.AnnotationClient.UpVoteAnnotation(10225840); // PUT /annotations/:id/downvote var downvotedAnnotation = await client.AnnotationClient.DownVoteAnnotation(10225840); // PUT /annotations/:id/unvote var unvotedAnnotation = await client.AnnotationClient.UnVoteAnnotation(10225840); // GET /account var user = await client.AccountClient.GetAccount(); // GET /referents var referent = await client.ReferentClient.GetReferent(webPageId : "10347"); // GET /songs/:id var song = await client.SongClient.GetSong(378195); // GET /artists/:id var artist = client.ArtistClient.GetArtist(16775); // GET /artists/:id/songs var artistsSongs = await client.ArtistClient.GetArtistsSongs(16775, sort : "title"); // GET /web_pages/lookup var webPage = await client.WebPageClient.GetWebPage(Uri.EscapeUriString("https://docs.genius.com")); // GET /search var search = client.SearchClient.Search("Kendrick Lamar"); } catch (Exception e) { Console.WriteLine(e); } }
public static void ClassInit(TestContext context) { _geniusClient = GeniusClientInitializer.GetClient(); _inputData = TestInputData.GetFromJsonFile(); }
static async void Search(object sender, MessageEventArgs e) //realyzing Genius API { if (e.Message.Text == "/cancel") { botClient.OnMessage -= Search; botClient.OnMessage += Bot_OnMessage; await botClient.SendTextMessageAsync( chatId : e.Message.Chat, text : $"Последнее действие отменено"); } else { try { Console.WriteLine($"Received '{e.Message.Text}' in chat with {e.Message.From.Username}."); var geniusClient = new GeniusClient("Gfx7YiVFLGVjdlyrbgQHvfcnEf1hT4Xad0UJ3s72zFN-RqjE-qTiGhuc2ya1BJjB"); var searchResult = await geniusClient.SearchClient.Search(textFormat : TextFormat.Dom, searchTerm : e.Message.Text); var result = Result.FromJson(searchResult.Response[0].Result.ToString()); var songResult = await geniusClient.SongsClient.GetSong(TextFormat.Dom, result.Id.ToString()); HtmlWeb web = new HtmlWeb(); string lyric = web.Load(result.Url.ToString()).DocumentNode.SelectSingleNode("//div[@class='lyrics']").InnerText; Song song = songResult.Response; string info = $"*{song.Title}*\n*{result.PrimaryArtist.Name}*\n"; int count = 0; if (song.FeaturedArtists.Count != 0) { info += "_Featuring by:_ "; count = 0; foreach (Artist artist in song.FeaturedArtists) { if (count == 0) { info += "*" + artist.Name.Replace("*", "") + "*"; } else { info += " & " + "*" + artist.Name.Replace("*", "") + "*"; } count++; } info += "\n"; } if (song.ProducerArtists.Count != 0) { info += "_Produced by:_ "; count = 0; foreach (Artist artist in song.ProducerArtists) { if (count == 0) { info += "*" + artist.Name.Replace("*", "") + "*"; } else { info += " & " + "*" + artist.Name.Replace("*", "") + "*"; } count++; } info += "\n"; } if (song.Album != null) { info += $"_Album_: *{song.Album.Name.Replace("*", "")}*\n"; } info += $"_Release date_: *{song.ReleaseDate}*"; lyric = info + lyric; lyric = lyric.Replace("[", "*["); lyric = lyric.Replace("]", "]*"); lyric = lyric.Replace("&", "&"); lyric = lyric.Replace("\n\n\n", ""); lyric += "Powered by: " + result.Url.ToString(); Console.WriteLine($"Give text on message '{e.Message.Text}': {result.FullTitle}"); await botClient.SendPhotoAsync( chatId : e.Message.Chat, photo : result.HeaderImageUrl.ToString()); if (lyric.Length > 4096) { int numOfMessages = (lyric.Length / 4096) + 1; int pastIndex = 0; int index = 0; for (int i = 0; i < numOfMessages; i++) { if (i == 0) { index = lyric.LastIndexOf('\n', 4096); await botClient.SendTextMessageAsync( chatId : e.Message.Chat, text : lyric.Substring(0, index), parseMode : ParseMode.Markdown); pastIndex = index; } else if (i == numOfMessages - 1) { await botClient.SendTextMessageAsync( chatId : e.Message.Chat, text : lyric.Substring(pastIndex, lyric.Length - pastIndex), parseMode : ParseMode.Markdown); } else { index += 4096; await botClient.SendTextMessageAsync( chatId : e.Message.Chat, text : lyric.Substring(pastIndex, 4096), parseMode : ParseMode.Markdown); pastIndex = index; } } } else { await botClient.SendTextMessageAsync( chatId : e.Message.Chat, text : lyric, parseMode : ParseMode.Markdown); } botClient.OnMessage -= Search; botClient.OnMessage += Bot_OnMessage; } catch (Exception ex) { Console.WriteLine(new string('-', 40)); Console.WriteLine(ex.ToString()); Console.WriteLine(new string('-', 40)); Console.WriteLine($"Error was in chat with {e.Message.From.Username}"); await botClient.SendTextMessageAsync( chatId : e.Message.Chat, text : "Такой песни нету, попробуй еще раз"); } } }
public GeniusAPI(ref MainWindow mw) { mainW = mw; geniusClient = new GeniusClient("W0knrrPmfODbCT-Oe26Uimx8GJSqszwKyh34soM0oQuNRSppLmlOuHffrO8YD0iL"); }
private static async Task Examples() { var geniusClient = new GeniusClient("CLIENT_ACCESS_KEY"); #region Annotations // GET an annotation by Id var getAnnotation = await geniusClient.AnnotationsClient.GetAnnotation("10225840", TextFormat.Dom); // Create/POST an annotation var annotationPayload = new AnnotationPayload { Annotation = new Annotation { Body = new AnnotationBody { MarkDown = "hello **world!**" } }, Referent = new Referent { RawAnnotableUrl = "http://seejohncode.com/2014/01/27/vim-commands-piping/", Fragment = "execute commands", ContextForDisplay = new ContextForDisplay { BeforeHtml = "You may know that you can ", AfterHtml = " from inside of a vim, with a vim command:" } }, WebPage = new WebPage { CanonicalUrl = null, OgUrl = null, Title = "Secret of Mana" } }; var postAnnotation = await geniusClient.AnnotationsClient.CreateAnnotation(annotationPayload, TextFormat.Dom); // Update an annotation var annotationUpdatePayload = new AnnotationPayload { Annotation = new Annotation { Body = new AnnotationBody { MarkDown = "hello **world!** is very generic" } } }; var updatedAnnotation = await geniusClient.AnnotationsClient.UpdateAnnotation(postAnnotation.Response.Id, annotationUpdatePayload, TextFormat.Dom); // Delete an annotation var deletedAnnotation = await geniusClient.AnnotationsClient.DeleteAnnotation(postAnnotation.Response.Id, TextFormat.Dom); #endregion #region Voting // Upvote await geniusClient.VoteClient.Vote(VoteType.Upvote, "Annotation_ID", TextFormat.Dom); //Downvote await geniusClient.VoteClient.Vote(VoteType.Downvote, "Annotation_ID", TextFormat.Dom); //UnVote (Remove the vote) await geniusClient.VoteClient.Vote(VoteType.Unvote, "Annotation_ID", TextFormat.Dom); #endregion #region Referent var referentBySongId = await geniusClient.ReferentsClient.GetReferentBySongId(TextFormat.Dom, "Song_Id", "Created_by_id", "per_page", "page"); var referentByWebPageId = await geniusClient.ReferentsClient.GetReferentByWebPageId(TextFormat.Dom, "Web_page_id"); #endregion #region Songs var song = geniusClient.SongsClient.GetSong(TextFormat.Dom, "SONG_ID"); #endregion #region Artists var artistInfo = geniusClient.ArtistsClient.GetArtist(TextFormat.Dom, "ARTIST_ID"); var songsByArtist = geniusClient.ArtistsClient.GetSongsByArtist(TextFormat.Dom, "ARTIST_ID"); #endregion #region WebPages var webPage = geniusClient.WebPagesClient.GetWebPage(TextFormat.Dom, "URL"); #endregion #region Search var searchResult = geniusClient.SearchClient.Search(TextFormat.Dom, "Kendrick%20Lamar"); #endregion #region Account var accountInfo = geniusClient.AccountsClient.GetAccountInfo(TextFormat.Dom); #endregion }
public static void ClassInit(TestContext context) { string apiKey = ConfigurationManager.AppSettings["API_KEY"]?.ToString(); _geniusClient = new GeniusClient(apiKey); }
private async void LyricFinder2(string artistName, string songName) { progressBar.Visible = true; //Search for artistName artistName = artistName.Replace(" ", "%20"); songName = songName.Replace(" ", "%20"); try { var geniusClient = new GeniusClient(_token); var search = await geniusClient.SearchClient.Search(TextFormat.Dom, artistName + "%20" + songName); if (search.Response.Count == 0) { return; } var result = JsonConvert.DeserializeObject <Result>(search.Response[0].Result.ToString()); if (string.IsNullOrEmpty(songName)) { var songs = new List <Song>(); HttpResponse <List <Song> > response; var page = 1; do { response = await geniusClient.ArtistsClient.GetSongsByArtist(TextFormat.Dom, result.primary_artist.id + "", "", "20", page + ""); songs.AddRange(response.Response); page++; } while (response.Response.Any()); progressBar.Maximum = songs.Count; foreach (var song in songs) { var lyrics = await Task.Factory.StartNew(() => GetLyrics(song.ApiPath)); progressBar.PerformStep(); ProcessList(lyrics); UpdateDisplay(); } } else { var lyrics = await Task.Factory.StartNew(() => GetLyrics(result.api_path)); ProcessList(lyrics); UpdateDisplay(); } } catch (Exception ex) { Console.Error.Write(ex); errorLabel.Visible = true; } finally { progressBar.Visible = false; searchButton.Enabled = true; } }
public GeniusAPIHelper() { client = new GeniusClient(Settings.GeniusToken); }