public async Task ReadPlaylistSongDetailsAsync(YoutubeResult youtubeResult) { if (!youtubeResult.SongDetailsLoaded) { foreach (var songs in youtubeResult.Songs.ChunkBy(50)) { var queryVideo = _youtubeService.Videos.List("contentDetails,snippet"); // contentDetails for time, snippet for title queryVideo.MaxResults = 50; queryVideo.Id = string.Join(',', songs.Select(a => a.Id)); var videos = (await queryVideo.ExecuteAsync(youtubeResult.CancellationToken)).Items; foreach (var video in videos) { var songIndex = youtubeResult.Songs.FindIndex(e => e.Id == video.Id); if (songIndex >= 0) { var song = youtubeResult.Songs[songIndex]; //song.Title = video.Snippet.Title; //song.Duration = XmlConvert.ToTimeSpan(video.ContentDetails.Duration) // ISO 8601 time format song.SetDetails( video.Snippet.Title, video.Snippet.LiveBroadcastContent?.ToLower() == "live", XmlConvert.ToTimeSpan(video.ContentDetails.Duration) // ISO 8601 time format ); youtubeResult.Songs[songIndex] = song; } } } } }
/// <summary> /// Reads the songs from an unread playlist, returns the next page token. /// </summary> public async Task <string> ReadPlaylistSongsBasicAsync(YoutubeResult youtubeResult, string token = "") { if (!youtubeResult.SongsLoaded) { var playlistQuery = _youtubeService.PlaylistItems.List("snippet"); playlistQuery.PlaylistId = youtubeResult.Id; playlistQuery.MaxResults = 50; playlistQuery.PageToken = token ?? ""; var playlistResponse = await playlistQuery.ExecuteAsync(youtubeResult.CancellationToken); if (playlistResponse != null) { youtubeResult.Songs.AddRange( playlistResponse.Items.Select((e) => new SongInfo() { Id = e.Snippet.ResourceId.VideoId, Title = e.Snippet.Title, Duration = null } ).ToList()); } return(playlistResponse.NextPageToken); } return(null); }
public async Task SendAudioAsync(YoutubeResult result) { if (result.Meta != null) { await ReplyAsync(":musical_note: " + result.Meta.FullName); await Stop(); } await SendAudioAsync(result.Path); }
public async Task ShouldCreateNewItemCorrectly() { var id = System.IO.Path.GetTempFileName(); var item = new YoutubeResult() { Title = "Teste 1", Description = "Descrição 1", Type = YoutubeResultType.Video, ContentId = id, PublishedAt = DateTime.Now, }; await _serviceProvider.Create(item); var createdItem = await _serviceProvider.GetResult(YoutubeResultType.Video, id); Assert.NotNull(createdItem); }
private async Task <ListVideos> GetVidsAsync() { var res = new ListVideos(); var result = new YoutubeResult(); try { res.lsVideos = new List <YoutubeAPIViewModel>(); var path = "https://www.googleapis.com/youtube/v3/playlistItems?part=contentDetails&maxResults=50&playlistId=PLAC325451207E3105&key=AIzaSyB7cEKc5O5lr9aF10Gr3ODo_AFbIGOjjHM"; HttpResponseMessage response = await client.GetAsync(path); if (response.IsSuccessStatusCode) { result = await response.Content.ReadAsAsync <YoutubeResult>(); foreach (var item in result.items) { var vidRes = new VideoResult(); var uri = $"https://www.googleapis.com/youtube/v3/videos?part=snippet%2CcontentDetails%2Cstatistics&id={item.contentDetails.videoId}&key=AIzaSyB7cEKc5O5lr9aF10Gr3ODo_AFbIGOjjHM"; HttpResponseMessage resp = await client.GetAsync(uri); if (response.IsSuccessStatusCode) { vidRes = await resp.Content.ReadAsAsync <VideoResult>(); var you = new YoutubeAPIViewModel { Id = vidRes.items.FirstOrDefault().id, Title = vidRes.items.FirstOrDefault().snippet.title, Description = vidRes.items.FirstOrDefault().snippet.description, //Tumbnail = vidRes.items.FirstOrDefault().snippet.thumbnails.FirstOrDefault().medium.url }; res.lsVideos.Add(you); } } } } catch (Exception ex) { throw ex; } return(res); }
public async Task <YoutubeResult> SearchAsync(string query, bool loadBasic = true, bool loadDetails = true) { var result = YoutubeResult.Invalid; //var list = new List<SongInfo>(); if (!string.IsNullOrWhiteSpace(query)) { if (IsValidPlaylist(query, out string playlistId)) { // Read playlist result = await GetPlaylistByIdAsync(playlistId); } else if (IsValidVideo(query, out string videoId)) { // Return single result = new YoutubeResult() { Id = videoId, Type = YoutubeResultType.Video, //SongsLoaded = true, //Songs = new List<SongInfo>(new[] { await GetVideoByIdAsync(videoId).ConfigureAwait(false) }) }; } else { // Search manually var songInfo = await GetVideoFromQueryAsync(query).ConfigureAwait(false); result = new YoutubeResult() { Id = songInfo.Id, Type = YoutubeResultType.Video, SongsLoaded = true, Songs = new List <SongInfo>(new[] { songInfo }) }; } } if (loadBasic && result != YoutubeResult.Invalid) { return(await result.LoadSongsAsync(loadDetails)); } return(result); }
public async Task ShouldUpdateExistingItem() { var id = System.IO.Path.GetTempFileName(); var item = new YoutubeResult() { Title = "Teste 1", Description = "Descrição 1", Type = YoutubeResultType.Video, ContentId = id, PublishedAt = DateTime.Now, }; await _serviceProvider.Create(item); item.Title = "UPDATED"; await _serviceProvider.Update(item); var existingItem = await _serviceProvider.GetResult(YoutubeResultType.Video, id); Assert.Equal(existingItem.Title, "UPDATED"); }
public async Task ShouldDeleteExistingItem() { var id = System.IO.Path.GetTempFileName(); var item = new YoutubeResult() { Title = "Teste 1", Description = "Descrição 1", Type = YoutubeResultType.Video, ContentId = id, PublishedAt = DateTime.Now, }; await _serviceProvider.Create(item); var deleted = await _serviceProvider.Delete(YoutubeResultType.Video, id); Assert.True(deleted); var existingItem = await _serviceProvider.GetResult(YoutubeResultType.Video, id); Assert.Null(existingItem); }
public static async Task DownloadYoutubeThumbnail(YoutubeResult result) { if (string.IsNullOrEmpty(result.ImgUrl)) { return; } using var client = new WebClient(); try { await client.DownloadFileTaskAsync(new Uri(result.ImgUrl), result.ImagePath); var image = new BitmapImage(); image.BeginInit(); image.StreamSource = new MemoryStream(File.ReadAllBytes(result.ImagePath)); image.EndInit(); result.ImageBitMap = image; } catch (Exception e) { Console.WriteLine("Could not download image, {0}", e); OnError(e.ToString()); } }
public static async Task <List <YoutubeResult> > GetYoutubeQuery(string query) { var youtubeResults = new List <YoutubeResult>(); try { string url = string.Format("https://www.youtube.com/results?search_query='{0}'", query); string htmlText = await GetContentFromUrl(url); var html = new HtmlDocument(); html.LoadHtml(htmlText); //File.WriteAllText("test.html", htmlText); var youtubeResultNodes = html.DocumentNode.CssSelect("#dismissable"); if (youtubeResultNodes == null || youtubeResultNodes.Count() == 0) { AeroError.EmitError("No Results found"); return(null); } int youtubeResultCount = youtubeResultNodes.Count(); for (int i = 0; i < youtubeResultCount; i++) { HtmlNode node = youtubeResultNodes.ElementAt(i); var titleNode = node.CssSelect("#video-title"); string YoutubeUrl = titleNode.Count() == 0 ? null : titleNode.First()?.Attributes?.GetKey("href"); string Title = node.CssSelect("#video-title > yt-formatted-string").First().InnerText.Trim(); if (string.IsNullOrEmpty(YoutubeUrl)) { continue; } YoutubeUrl = string.Format("https://www.youtube.com{0}", YoutubeUrl); string ThumbnailImage = node.CssSelect("#img")?.First().Attributes.GetKey("src"); var result = new YoutubeResult { Url = YoutubeUrl, ImgUrl = ThumbnailImage, Title = Title, ImagePath = Path.Join(output, i.ToString() + ".jpg"), }; youtubeResults.Add(result); } var playlistResults = html.DocumentNode.CssSelect("#contents > ytd-playlist-renderer"); Console.WriteLine("playlists count = {0}", playlistResults.Count()); for (int i = 0; i < playlistResults.Count(); i++) { var playlistVideoHeader = playlistResults.ElementAt(i); string YoutubeUrl = playlistVideoHeader.CssSelect("#content > a")?.First()?.Attributes?.GetKey("href"); YoutubeUrl = string.Format("https://www.youtube.com{0}", YoutubeUrl); string thumbnailUrl = playlistVideoHeader.CssSelect("#img")?.First().Attributes.GetKey("src"); if (string.IsNullOrEmpty(YoutubeUrl)) { continue; } string playlistCount = playlistVideoHeader.CssSelect("#overlays > ytd-thumbnail-overlay-side-panel-renderer > yt-formatted-string")?.First().InnerText; var youtubeResult = new YoutubeResult { Url = YoutubeUrl, ImgUrl = thumbnailUrl, Title = playlistVideoHeader.CssSelect("#video-title")?.First()?.Attributes?.GetKey("title") + " PLAYLIST", ImagePath = Path.Join(output, (i + youtubeResultCount).ToString() + ".jpg"), IsPlayList = true, PlayListCount = playlistCount, }; youtubeResults.Add(youtubeResult); } //END OF LOOP await DownloadThumbnails(youtubeResults); } catch (Exception e) { Console.WriteLine(e.ToString()); OnError(e.ToString()); } return(youtubeResults); }
public void AddItem(YoutubeResult youtubeResult) { _contexto.YoutubeResults.Add(youtubeResult); _contexto.SaveChanges(); }
public async Task <List <YoutubeResult> > BuscarNoYouTubeAsync(string chavePesquisa) { try { List <YoutubeResult> listaYoutubeItem = new List <YoutubeResult>(); var youtubeService = new YouTubeService(new BaseClientService.Initializer() { ApiKey = Secrets.YoutubeKey, ApplicationName = this.GetType().ToString() }); var searchListRequest = youtubeService.Search.List("snippet"); searchListRequest.Q = chavePesquisa; searchListRequest.MaxResults = 50; // Call the search.list method to retrieve results matching the specified query term. var searchListResponse = await searchListRequest.ExecuteAsync(); YoutubeResult item; // Add each result to the appropriate list, and then display the lists of // matching videos, channels, and playlists. foreach (var searchResult in searchListResponse.Items) { switch (searchResult.Id.Kind) { case "youtube#video": item = new YoutubeResult { YoutubeId = searchResult.Id.VideoId, ChannelTitle = searchResult.Snippet.Title, Description = searchResult.Snippet.Description, ETag = searchResult.Snippet.ETag, LiveBroadcastContent = searchResult.Snippet.LiveBroadcastContent, PublishedAt = searchResult.Snippet.PublishedAt, PublishedAtRaw = searchResult.Snippet.PublishedAtRaw, Title = searchResult.Snippet.Title, Thumbnails = searchResult.Snippet.Thumbnails.Medium.Url, Type = TypeItem.Video }; listaYoutubeItem.Add(item); break; case "youtube#channel": item = new YoutubeResult { YoutubeId = searchResult.Id.ChannelId, ChannelTitle = searchResult.Snippet.Title, Description = searchResult.Snippet.Description, ETag = searchResult.Snippet.ETag, LiveBroadcastContent = searchResult.Snippet.LiveBroadcastContent, PublishedAt = searchResult.Snippet.PublishedAt, PublishedAtRaw = searchResult.Snippet.PublishedAtRaw, Title = searchResult.Snippet.Title, Thumbnails = searchResult.Snippet.Thumbnails.Medium.Url, Type = TypeItem.Channel }; listaYoutubeItem.Add(item); break; case "youtube#playlist": item = new YoutubeResult { YoutubeId = searchResult.Id.PlaylistId, ChannelTitle = searchResult.Snippet.Title, Description = searchResult.Snippet.Description, ETag = searchResult.Snippet.ETag, LiveBroadcastContent = searchResult.Snippet.LiveBroadcastContent, PublishedAt = searchResult.Snippet.PublishedAt, PublishedAtRaw = searchResult.Snippet.PublishedAtRaw, Title = searchResult.Snippet.Title, Thumbnails = searchResult.Snippet.Thumbnails.Medium.Url, Type = TypeItem.Playlist }; listaYoutubeItem.Add(item); break; } } return(listaYoutubeItem); } catch { return(null); } }