Example #1
0
        internal async Task <IEnumerable <Playlist> > GetPlaylists(Channel channel = null, bool myPlaylists = false, string id = null, int maxResults = 1)
        {
            return(await this.YouTubeServiceWrapper(async() =>
            {
                List <Playlist> results = new List <Playlist>();
                string pageToken = null;
                do
                {
                    PlaylistsResource.ListRequest request = this.connection.GoogleYouTubeService.Playlists.List("snippet,contentDetails");
                    if (channel != null)
                    {
                        request.ChannelId = channel.Id;
                    }
                    else if (myPlaylists)
                    {
                        request.Mine = true;
                    }
                    else if (!string.IsNullOrEmpty(id))
                    {
                        request.Id = id;
                    }
                    request.MaxResults = Math.Min(maxResults, 50);
                    request.PageToken = pageToken;

                    PlaylistListResponse response = await request.ExecuteAsync();
                    results.AddRange(response.Items);
                    maxResults -= response.Items.Count;
                    pageToken = response.NextPageToken;
                } while (maxResults > 0 && !string.IsNullOrEmpty(pageToken));
                return results;
            }));
        }
Example #2
0
        public async Task <PlaylistListResponse> GetPlaylistInfo(PlaylistQuery query)
        {
            PlaylistsResource.ListRequest listRequest = _youtubeService.Playlists.List(query.Part);
            listRequest.Id         = query.Id;
            listRequest.MaxResults = query.MaxResults;

            return(await listRequest.ExecuteAsync());
        }
Example #3
0
        private async Task search(IClientServiceRequest request, String searchInfo, bool isNextPage, CancellationToken token)
        {
            SearchListResponse       searchResponse       = null;
            PlaylistItemListResponse playlistItemResponse = null;
            PlaylistListResponse     playlistResponse     = null;

            SearchResource.ListRequest        searchRequest        = request as SearchResource.ListRequest;
            PlaylistItemsResource.ListRequest playlistItemsRequest = request as PlaylistItemsResource.ListRequest;
            PlaylistsResource.ListRequest     playlistRequest      = request as PlaylistsResource.ListRequest;

            List <YoutubeItem> items = new List <YoutubeItem>();
            int relevance;

            if (isNextPage)
            {
                if (NextPageToken == null)
                {
                    // Final page
                    return;
                }

                if (searchRequest != null)
                {
                    searchRequest.PageToken = NextPageToken;
                }
                else if (playlistItemsRequest != null)
                {
                    playlistItemsRequest.PageToken = NextPageToken;
                }
                else if (playlistRequest != null)
                {
                    playlistRequest.PageToken = NextPageToken;
                }

                relevance = MediaState.UIMediaCollection.Count;
            }
            else
            {
                MediaState.clearUIState(searchInfo, DateTime.Now, MediaStateType.SearchResult);

                CurrentQuery = request;
                relevance    = 0;
            }

            // Call the search.list method to retrieve results matching the specified query term.
            if (searchRequest != null)
            {
                searchResponse = await searchRequest.ExecuteAsync(token);

                NextPageToken = searchResponse.NextPageToken;

                foreach (SearchResult searchResult in searchResponse.Items)
                {
                    YoutubeItem newItem = null;

                    switch (searchResult.Id.Kind)
                    {
                    case "youtube#video":
                        newItem = new YoutubeVideoItem(searchResult, relevance);
                        break;

                    case "youtube#channel":
                        newItem = new YoutubeChannelItem(searchResult, relevance);
                        break;

                    case "youtube#playlist":
                        newItem = new YoutubePlaylistItem(searchResult, relevance);
                        break;

                    default:
                        break;
                    }

                    if (newItem == null || MediaState.UIMediaCollection.Contains(newItem))
                    {
                        continue;
                    }

                    items.Add(newItem);

                    relevance++;
                }
            }

            if (playlistItemsRequest != null)
            {
                playlistItemResponse = await playlistItemsRequest.ExecuteAsync(token);

                NextPageToken = playlistItemResponse.NextPageToken;

                foreach (PlaylistItem playlistItem in playlistItemResponse.Items)
                {
                    YoutubeVideoItem newItem = new YoutubeVideoItem(playlistItem, relevance);

                    items.Add(newItem);

                    relevance++;
                }
            }

            if (playlistRequest != null)
            {
                playlistResponse = await playlistRequest.ExecuteAsync(token);

                NextPageToken = playlistResponse.NextPageToken;

                foreach (Playlist playlist in playlistResponse.Items)
                {
                    YoutubePlaylistItem newItem = new YoutubePlaylistItem(playlist, relevance);

                    if (!items.Contains(newItem))
                    {
                        items.Add(newItem);
                    }

                    relevance++;
                }
            }

            // Add each result to the appropriate list, and then display the lists of
            // matching videos, channels, and playlists.
            MediaState.addUIState(items);
        }
        private async Task <Chart> GetOrCreatePlaylist(Chart chart)
        {
            int chartNameWithPrefixLen = chart.NameWithPrefix.Length;

            UserCredential credential;

            try
            {
                using (FileStream stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
                {
                    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        // This OAuth 2.0 access scope allows for full read/write access to the
                        // authenticated user's account.
                        new[] { YouTubeService.Scope.Youtube },
                        "user",
                        CancellationToken.None,
                        new FileDataStore(GetType().ToString())
                        );
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
                return(null);
            }

            var youTubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = GetType().ToString()
            });

            // Find playlist by chart name
            PlaylistsResource.ListRequest playlistReq = youTubeService.Playlists.List("snippet");
            playlistReq.Mine       = true;
            playlistReq.MaxResults = 10;
            PlaylistListResponse playlistResp = await playlistReq.ExecuteAsync();

            Playlist playlist = null;

            foreach (Playlist playlistCandidate in playlistResp.Items)
            {
                string playlistTitle = playlistCandidate.Snippet.Title;
                if (playlistTitle.Length > chartNameWithPrefixLen && playlistTitle.Substring(0, chartNameWithPrefixLen) == chart.NameWithPrefix)
                {
                    playlist = playlistCandidate;
                    Debug.WriteLine("Playlist for {0} already exists as {1}", chart.Name, playlist.Snippet.Title);
                    break;
                }
            }

            if (playlist == null)
            {
                // Create a new, private playlist in the authorized user's channel
                playlist = new Playlist
                {
                    Snippet = new PlaylistSnippet
                    {
                        Title       = chart.PlaylistName,
                        Description = $"Source: {chart.Url}\n\nPlaylist created with the YouTube Playlist Builder https://github.com/RDultsin/YouTubePlaylistBuilder"
                    },
                    Status = new PlaylistStatus
                    {
                        PrivacyStatus = "public"
                    }
                };
                playlist = await youTubeService.Playlists.Insert(playlist, "snippet,status").ExecuteAsync();

                Debug.WriteLine("Created playlist {0}", (object)playlist.Snippet.Title);
            }
            else
            {
                // Update title of playlist
                playlist.Snippet.Title       = chart.PlaylistName;
                playlist.Snippet.Description = $"Source: {chart.Url}\n\nPlaylist updated with the YouTube Playlist Builder https://github.com/RDultsin/YouTubePlaylistBuilder";
                playlist = await youTubeService.Playlists.Update(playlist, "snippet").ExecuteAsync();

                Debug.WriteLine("Updated playlist {0}", (object)playlist.Snippet.Title);

                // Remove all videos from playlist
                PlaylistItemsResource.ListRequest playlistItemReq = youTubeService.PlaylistItems.List("snippet");
                playlistItemReq.PlaylistId = playlist.Id;
                playlistItemReq.MaxResults = 50;
                PlaylistItemListResponse playlistItemResp = await playlistItemReq.ExecuteAsync();

                foreach (PlaylistItem playlistItem in playlistItemResp.Items)
                {
                    await youTubeService.PlaylistItems.Delete(playlistItem.Id).ExecuteAsync();

                    Debug.WriteLine("Removed playlist item {0} from playlist {1}", playlistItem.Snippet.Title, playlist.Snippet.Title);
                }
            }

            // Add a videos to the playlist
            foreach (Song song in chart.Songs)
            {
                PlaylistItem playlistItem = new PlaylistItem
                {
                    Snippet = new PlaylistItemSnippet
                    {
                        PlaylistId = playlist.Id,
                        ResourceId = new ResourceId
                        {
                            Kind    = "youtube#video",
                            VideoId = song.VideoId
                        }
                    }
                };
                playlistItem = await youTubeService.PlaylistItems.Insert(playlistItem, "snippet").ExecuteAsync();

                Debug.WriteLine("Added playlist item {0} to playlist {1}", playlistItem.Snippet.Title, playlist.Snippet.Title);
            }

            return(chart);
        }