コード例 #1
0
        public string GetChannelPlaylist(string channelName)
        {
            // Load the 'uploaded' playlist
            ChannelsResource.ListRequest channelPlaylistIDReq = YouTubeService.Channels.List("contentDetails");
            channelPlaylistIDReq.ForUsername = channelName;
            ChannelListResponse channelPlaylistIDResp = channelPlaylistIDReq.Execute();

            return(channelPlaylistIDResp.Items[0].ContentDetails.RelatedPlaylists.Uploads);
        }
コード例 #2
0
        public static string GetChannelUploadsPlaylistId(Subscription sub)
        {
            ChannelsResource.ListRequest listRequest = Service.Channels.List("contentDetails");
            listRequest.Id = sub.ChannelId;
            ChannelListResponse response = listRequest.Execute();

            if (response.Items.Count <= 0)
            {
                return(null);
            }

            return(response.Items.FirstOrDefault().ContentDetails.RelatedPlaylists.Uploads);
        }
コード例 #3
0
        private IEnumerable <Video> GetSubscriptionLatestVideosAsync(Subscription subscription)
        {
            var latestVideosToGrab = 25;

            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = Credental,
                ApplicationName       = this.GetType().ToString()
            });

            var test1 = new ChannelsResource.ListRequest(youtubeService, "contentDetails");

            test1.MaxResults = 1;
            test1.Id         = subscription.Snippet.ResourceId.ChannelId;
            var test2 = test1.Execute();
            var test3 = test2.Items;

            if (!(test3.Count <= 0))
            {
                var uploadPlaylistId = test3[0].ContentDetails.RelatedPlaylists.Uploads;

                var playlistRequest = youtubeService.PlaylistItems.List("snippet");
                playlistRequest.MaxResults = latestVideosToGrab;
                playlistRequest.PlaylistId = uploadPlaylistId;
                var test4 = playlistRequest.Execute();

                var idList = new List <string>();
                foreach (var pl in test4.Items)
                {
                    idList.Add(pl.Snippet.ResourceId.VideoId);
                }

                var videosRequest = youtubeService.Videos.List("snippet,contentDetails,statistics");
                videosRequest.MaxResults = latestVideosToGrab;
                videosRequest.Id         = string.Join(",", idList);
                var test5 = videosRequest.Execute();

                var videoList = test5.Items;

                return(videoList);
            }
            else
            {
                return(new List <Video>());
            }
        }
コード例 #4
0
        public YoutubeChannelNodeState(YoutubeChannelItem item)
        {
            Info = item.Info as SearchResult;
      
            if (item.Metadata != null)
            {
                ThumbString = System.Convert.ToBase64String(item.Metadata.Thumbnail.ImageData);
            }
            else
            {
                ThumbString = null;
            }

            ChannelsResource.ListRequest listRequest = new ChannelsResource.ListRequest(YoutubeViewModel.Youtube, "statistics");

            listRequest.Id = item.ChannelId;

            ChannelListResponse response = listRequest.Execute();

            if (response.Items.Count > 0)
            {
                Statistics = response.Items[0].Statistics;
            }
        }
コード例 #5
0
        public YoutubeChannelNodeState(YoutubeChannelItem item)
        {
            Info = item.Info as SearchResult;

            if (item.Metadata != null)
            {
                ThumbString = System.Convert.ToBase64String(item.Metadata.Thumbnail.ImageData);
            }
            else
            {
                ThumbString = null;
            }

            ChannelsResource.ListRequest listRequest = new ChannelsResource.ListRequest(YoutubeViewModel.Youtube, "statistics");

            listRequest.Id = item.ChannelId;

            ChannelListResponse response = listRequest.Execute();

            if (response.Items.Count > 0)
            {
                Statistics = response.Items[0].Statistics;
            }
        }
コード例 #6
0
        public void Process()
        {
            try
            {
                ChannelsResource.ListRequest channelListRequest = _youtube.Channels.List("id");

                // Test if user put user name instead of channel id
                channelListRequest.ForUsername = _channelId;
                ChannelListResponse channelsListResponse = channelListRequest.Execute();

                string channelId = "0";
                if (channelsListResponse.Items.Count != 0)
                {
                    channelId = channelsListResponse.Items[0].Id;
                }

                //User put correct channel ID
                SearchResource.ListRequest listRequest = _youtube.Search.List("snippet");
                if (channelId == "0")                   // cant find channel id from user name
                {
                    listRequest.ChannelId = _channelId; //
                }
                else // cand find channel id from user name
                {
                    listRequest.ChannelId = channelId;
                }

                listRequest.MaxResults      = 50;
                listRequest.Type            = "video";
                listRequest.PublishedAfter  = _assessment.StartDate;
                listRequest.PublishedBefore = _assessment.EndDate;


                // Get all uploaded videos and store to uploadedVideos
                SearchListResponse   resp           = listRequest.Execute();
                IList <SearchResult> uploadedVideos = resp.Items;
                string nextPageToken = resp.NextPageToken;
                while (nextPageToken != null)
                {
                    listRequest.PageToken = nextPageToken;
                    SearchListResponse respPage = listRequest.Execute();
                    var resultsPage             = respPage.Items;
                    foreach (SearchResult i in resultsPage)
                    {
                        uploadedVideos.Add(i);
                    }
                    nextPageToken = respPage.NextPageToken;
                    if (uploadedVideos.Count == Int32.Parse(Properties.Resources._api_youtube_maximum_videos))// Prevent excessive use of API calls
                    {
                        break;
                    }
                }


                // Aggregate data
                foreach (SearchResult video in uploadedVideos)
                {
                    // video.Id
                    VideosResource.ListRequest vidReq = _youtube.Videos.List("statistics");
                    vidReq.Id = video.Id.VideoId;
                    VideoListResponse vidResp = vidReq.Execute();
                    Video             item;
                    if (vidResp.Items.Count != 0)
                    {
                        item = vidResp.Items[0];
                        if (item.Statistics.LikeCount != null)
                        {
                            _totalLikes += (ulong)item.Statistics.LikeCount;
                        }
                        if (item.Statistics.DislikeCount != null)
                        {
                            _totalDislikes += (ulong)item.Statistics.DislikeCount;
                        }
                        if (item.Statistics.ViewCount != null)
                        {
                            _totalViews += (ulong)item.Statistics.ViewCount;
                        }
                    }
                }
                _totalVideos += uploadedVideos.Count;
                // Grab number of subscribers
                ChannelsResource.ListRequest channelReq = _youtube.Channels.List("statistics");
                channelReq.Id = channelId;
                ChannelListResponse channelResp = channelReq.Execute();
                if (channelResp.Items.Count != 0)
                {
                    if (channelResp.Items[0].Statistics.SubscriberCount != null)
                    {
                        _subscribers += (ulong)channelResp.Items[0].Statistics.SubscriberCount;
                    }
                }

                // Save to Excel
                SaveToExcelPackage();
            }
            catch (Exception ex)
            {
                Log.LogError(this.GetType().Name + " - " + System.Reflection.MethodBase.GetCurrentMethod().Name, ex);
                throw ex;
            }
        }
コード例 #7
0
        /// <summary>
        /// Test the time elapsed in different API operations, in order to evaluate performance.
        /// </summary>
        /// <param name="maxItemsQuantity"></param>
        /// <returns></returns>
        public TimeElapsedResult TestOperationsTimeElapsed(int maxItemsQuantity, string searchTerm)
        {
            // Counters
            TimeElapsedResult result = new TimeElapsedResult();

            var youtube = new YouTubeService(new BaseClientService.Initializer());

            SearchResource.ListRequest listRequest = youtube.Search.List("snippet");
            listRequest.Fields     = "items(id, snippet(title, description, publishedAt, thumbnails, channelId, channelTitle))";
            listRequest.Key        = API_KEY;
            listRequest.Type       = ResourceTypes.Video;
            listRequest.MaxResults = MAX_RESULTS_PER_PAGE;

            if (!string.IsNullOrEmpty(LOCATION))
            {
                listRequest.Location = LOCATION;
            }
            if (!string.IsNullOrEmpty(LOCATION_RADIUS))
            {
                listRequest.LocationRadius = LOCATION_RADIUS;
            }
            listRequest.Q     = searchTerm;
            listRequest.Order = SearchResource.ListRequest.OrderEnum.Date;

            var stopwatch = Stopwatch.StartNew();
            SearchListResponse searchResponse = listRequest.Execute();

            result.ElapsedSearch.Add(stopwatch.ElapsedMilliseconds);
            List <SearchResult> results    = new List <SearchResult>();
            List <string>       videosIds  = new List <string>();
            List <string>       channelIds = new List <string>();
            int currentCounter             = 0;

            while (searchResponse.Items.Count > 0 && currentCounter < maxItemsQuantity)
            {
                videosIds.AddRange(searchResponse.Items.Select(v => v.Id.VideoId));
                channelIds.AddRange(searchResponse.Items.Select(v => v.Snippet.ChannelId));
                results.AddRange(searchResponse.Items);
                // Gets oldest element
                var oldest = searchResponse.Items.OrderBy(i => i.Snippet.PublishedAt).FirstOrDefault();
                // Avoids getting the oldest again
                listRequest.PublishedBefore = oldest.Snippet.PublishedAt.Value.AddSeconds(-1);
                currentCounter += searchResponse.Items.Count;
                if (currentCounter < maxItemsQuantity)
                {
                    // Performs the search
                    stopwatch      = Stopwatch.StartNew();
                    searchResponse = listRequest.Execute();
                    result.ElapsedSearch.Add(stopwatch.ElapsedMilliseconds);
                }
            }

            // Retrieves videos recording details (location)
            List <string> videosToRetrieve = videosIds.Take(50).ToList();

            videosIds = videosIds.Skip(50).ToList();
            while (videosToRetrieve.Count > 0)
            {
                VideosResource.ListRequest videosRequest = youtube.Videos.List("recordingDetails");
                videosRequest.Key        = API_KEY;
                videosRequest.MaxResults = MAX_RESULTS_PER_PAGE;
                videosRequest.Id         = string.Join(",", videosToRetrieve.ToArray());

                stopwatch = Stopwatch.StartNew();
                VideoListResponse videosResponse = videosRequest.Execute();
                result.ElapsedVideo.Add(stopwatch.ElapsedMilliseconds);

                videosToRetrieve = videosIds.Take(50).ToList();
                videosIds        = videosIds.Skip(50).ToList();
            }

            // Retrieves channels
            List <string> channelsToRetrieve = channelIds.Take(50).ToList();

            channelIds = channelIds.Skip(50).ToList();
            while (channelsToRetrieve.Count > 0)
            {
                ChannelsResource.ListRequest channelRequest = youtube.Channels.List("snippet");
                channelRequest.Key        = API_KEY;
                channelRequest.MaxResults = MAX_RESULTS_PER_PAGE;
                channelRequest.Id         = string.Join(",", channelsToRetrieve.ToArray());

                stopwatch = Stopwatch.StartNew();
                ChannelListResponse channelsResponse = channelRequest.Execute();
                result.ElapsedChannel.Add(stopwatch.ElapsedMilliseconds);

                channelsToRetrieve = channelIds.Take(50).ToList();
                channelIds         = channelIds.Skip(50).ToList();
            }

            result.Results = results;

            return(result);
        }
コード例 #8
0
        /// <summary>
        /// Retrieves a certain quantity of videos using oldest publish date criteria.
        /// </summary>
        /// <param name="maxItemsQuantity"></param>
        /// <returns></returns>
        public List <SearchResult> RetrieveVideosWithoutAPIPaging(int maxItemsQuantity, string searchTerm)
        {
            var youtube = new YouTubeService(new BaseClientService.Initializer());

            SearchResource.ListRequest listRequest = youtube.Search.List("snippet");
            listRequest.Fields     = "items(id, snippet(title, description, publishedAt, thumbnails, channelId, channelTitle))";
            listRequest.Key        = API_KEY;
            listRequest.Type       = ResourceTypes.Video;
            listRequest.MaxResults = MAX_RESULTS_PER_PAGE;

            if (!string.IsNullOrEmpty(LOCATION))
            {
                listRequest.Location = LOCATION;
            }
            if (!string.IsNullOrEmpty(LOCATION_RADIUS))
            {
                listRequest.LocationRadius = LOCATION_RADIUS;
            }
            listRequest.Q     = searchTerm;
            listRequest.Order = SearchResource.ListRequest.OrderEnum.Date;

            SearchListResponse  searchResponse      = listRequest.Execute();
            List <SearchResult> results             = new List <SearchResult>();
            List <string>       videosIds           = new List <string>();
            List <string>       channelsWithoutName = new List <string>();
            int amountWithoutChannelTitle           = 0;
            int amountWithoutChannelId = 0;
            int currentCounter         = 0;

            while (searchResponse.Items.Count > 0 && currentCounter < maxItemsQuantity)
            {
                foreach (var item in searchResponse.Items)
                {
                    videosIds.Add(item.Id.VideoId);
                    if (string.IsNullOrEmpty(item.Snippet.ChannelTitle))
                    {
                        channelsWithoutName.Add(item.Snippet.ChannelId);
                        amountWithoutChannelTitle++;
                    }
                    if (string.IsNullOrEmpty(item.Snippet.ChannelId))
                    {
                        amountWithoutChannelId++;
                    }
                }

                results.AddRange(searchResponse.Items);
                // Gets oldest element
                var oldest = searchResponse.Items.OrderBy(i => i.Snippet.PublishedAt).FirstOrDefault();
                // Avoids getting the oldest again
                listRequest.PublishedBefore = oldest.Snippet.PublishedAt.Value.AddSeconds(-1);
                currentCounter += searchResponse.Items.Count;
                if (currentCounter < maxItemsQuantity)
                {
                    // Performs the search
                    searchResponse = listRequest.Execute();
                }
            }

            // Retrieves videos recording details (location)
            VideosResource.ListRequest videosRequest = youtube.Videos.List("recordingDetails");
            videosRequest.Key        = API_KEY;
            videosRequest.MaxResults = MAX_RESULTS_PER_PAGE;
            videosRequest.Id         = string.Join(",", videosIds.Take(50).ToArray());
            VideoListResponse videosResponse = videosRequest.Execute();

            // Retrieves channels that don't have name
            List <string> channelsToRetrieve = channelsWithoutName.Take(50).ToList();

            channelsWithoutName = channelsWithoutName.Skip(50).ToList();
            while (channelsToRetrieve.Count > 0)
            {
                ChannelsResource.ListRequest channelRequest = youtube.Channels.List("snippet");
                channelRequest.Key        = API_KEY;
                channelRequest.MaxResults = MAX_RESULTS_PER_PAGE;
                channelRequest.Id         = string.Join(",", channelsToRetrieve.ToArray());
                ChannelListResponse channelsResponse = channelRequest.Execute();
                channelsToRetrieve  = channelsWithoutName.Take(50).ToList();
                channelsWithoutName = channelsWithoutName.Skip(50).ToList();
            }

            return(results);
        }