Exemplo n.º 1
0
        public async Task ChannelInfoCommand([Remainder] string searchTerm)
        {
            Channel?channelListResult;

            using (var youtubeService = new YouTubeService(new BaseClientService.Initializer
            {
                ApiKey = _botCredentials.GoogleApiKey,
                ApplicationName = GetType().ToString()
            }))

            {
                SearchResource.ListRequest searchListRequest = youtubeService.Search.List("snippet");
                searchListRequest.Q          = searchTerm;
                searchListRequest.MaxResults = 1;
                SearchResult?searchListResult = (await searchListRequest.ExecuteAsync()).Items.FirstOrDefault();

                if (searchListResult == null)
                {
                    await SendErrorAsync("Could not find the requested channel!");

                    return;
                }

                ChannelsResource.ListRequest channelListRequest = youtubeService.Channels.List("snippet");
                channelListRequest.Id         = searchListResult.Snippet.ChannelId;
                channelListRequest.MaxResults = 10;
                channelListResult             = (await channelListRequest.ExecuteAsync()).Items.FirstOrDefault();

                if (channelListResult == null)
                {
                    await SendErrorAsync("Could not find the requested channel!");

                    return;
                }
            }

            var builder = new EmbedBuilder()
                          .WithTitle(channelListResult.Snippet.Title)
                          .WithColor(GetColor(Context))
                          .WithFooter(channelListResult.Id)
                          .WithThumbnailUrl(channelListResult.Snippet.Thumbnails.Medium.Url);

            if (!string.IsNullOrEmpty(channelListResult.Snippet.Description))
            {
                builder.AddField("Description", channelListResult.Snippet.Description);
            }

            if (channelListResult.Snippet.Country != null)
            {
                builder.AddField("Country", channelListResult.Snippet.Country, true);
            }

            if (channelListResult.Snippet.PublishedAt != null)
            {
                // date is in format YYYY-MM-DDThh:mm:ssZ - remove the T and Z
                builder.AddField("Created", channelListResult.Snippet.PublishedAt.Replace('T', ' ').Remove(19), true);
            }

            await ReplyAsync(embed : builder.Build());
        }
Exemplo n.º 2
0
        /// <summary>
        /// Return a complete Channel object from the youtube id of the channel
        /// </summary>
        /// <param name="channelID"></param>
        /// <returns></returns>
        public async static Task <Channel> GetChannel(string channelID)
        {
            try
            {
                ChannelsResource.ListRequest request = YoutubeManager.YoutubeService.Channels.List("snippet");
                request.Id = channelID;

                ChannelListResponse response = await request.ExecuteAsync();

                if (response.Items.Count > 0)
                {
                    var result = response.Items[0];
                    return(new Channel(result.Snippet.Title, channelID, result.Snippet.Thumbnails.High.Url));
                }
                else
                {
                    return(null);
                }
            }
            catch
            {
                MainActivity.instance.UnknowError(ErrorCode.CG1);
                return(null);
            }
        }
Exemplo n.º 3
0
        private async Task Run()
        {
            UserCredential credential;
            string         clientSecretsPath = CredentialsManager.GetClientSecretsLocation();

            using (FileStream stream = new FileStream(clientSecretsPath, FileMode.Open, FileAccess.Read))
            {
                // This OAuth 2.0 access scope allows for read-only access to the authenticated
                // user's account, but not other types of account access.
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { YouTubeService.Scope.YoutubeReadonly },
                    "user",
                    CancellationToken.None,
                    new FileDataStore(GetType().ToString())
                    );
            }

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

            ChannelsResource.ListRequest channelsListRequest = youtubeService.Channels.List("contentDetails");
            channelsListRequest.Mine = true;

            // Retrieve the contentDetails part of the channel resource for the authenticated user's channel.
            ChannelListResponse channelsListResponse = await channelsListRequest.ExecuteAsync();

            foreach (Channel channel in channelsListResponse.Items)
            {
                // From the API response, extract the playlist ID that identifies the list
                // of videos uploaded to the authenticated user's channel.
                string uploadsListId = channel.ContentDetails.RelatedPlaylists.Uploads;

                Console.WriteLine("Videos in list {0}", uploadsListId);

                string nextPageToken = "";
                while (nextPageToken != null)
                {
                    PlaylistItemsResource.ListRequest playlistItemsListRequest = youtubeService.PlaylistItems.List("snippet");
                    playlistItemsListRequest.PlaylistId = uploadsListId;
                    playlistItemsListRequest.MaxResults = 50;
                    playlistItemsListRequest.PageToken  = nextPageToken;

                    // Retrieve the list of videos uploaded to the authenticated user's channel.
                    PlaylistItemListResponse playlistItemsListResponse = await playlistItemsListRequest.ExecuteAsync();

                    foreach (PlaylistItem playlistItem in playlistItemsListResponse.Items)
                    {
                        // Print information about each video.
                        Console.WriteLine("{0} ({1})", playlistItem.Snippet.Title, playlistItem.Snippet.ResourceId.VideoId);
                    }

                    nextPageToken = playlistItemsListResponse.NextPageToken;
                }
            }
        }
Exemplo n.º 4
0
        public async Task <ChannelListResponse> GetChannelInfo(ChannelQuery query)
        {
            ChannelsResource.ListRequest listRequest = _youtubeService.Channels.List(query.Part);
            listRequest.Id         = query.Id;
            listRequest.MaxResults = query.MaxResults;

            return(await listRequest.ExecuteAsync());
        }
Exemplo n.º 5
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);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Gets the channels associated with the specified IDs.
        /// </summary>
        /// <param name="ids">The IDs to search for</param>
        /// <returns>The channel information</returns>
        public async Task <IEnumerable <Channel> > GetChannelsByID(IEnumerable <string> ids)
        {
            Validator.ValidateList(ids, "ids");
            return(await this.YouTubeServiceWrapper(async() =>
            {
                ChannelsResource.ListRequest search = this.connection.GoogleYouTubeService.Channels.List("snippet,statistics,contentDetails");
                search.Id = string.Join(",", ids);
                search.MaxResults = ids.Count();

                ChannelListResponse response = await search.ExecuteAsync();
                return response.Items;
            }));
        }
        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);
        }
Exemplo n.º 8
0
        // Youtube 에서 제공하는 API, 영상 제목, 영상 정보, 영상 길이, 영상 조회수, 영상 설명, 영상 좋아요,싫어요 수, 댓글 수 게시자 채널명, 해당 채널 구독자 수,
        async void YoutubeAPi()
        {
            //비동기, 동기
            //비동기 : 해결 속도 동기 보다 느림, 대신 이 명령어 하고 있을 때 다른 일을 동시에 해결 할 수 있음
            //동기 : 비동기보다 빠르고 대신 이 명령어를 하는 동안 다른 명령어를 수행못함

            // viewCount,likecount, dislikecount, commentcount
            VideosResource.ListRequest count_like_dislike_view = youtube.Videos.List("statistics");//Videos statistics 연결
            count_like_dislike_view.Id = $"{this.Id}";
            VideoListResponse countview_res = await count_like_dislike_view.ExecuteAsync();

            viewCount.Text    = Convert.ToString(countview_res.Items[0].Statistics.ViewCount);//
            likeCount.Text    = Convert.ToString(countview_res.Items[0].Statistics.LikeCount);
            dislikeCount.Text = Convert.ToString(countview_res.Items[0].Statistics.DislikeCount);
            commentCount.Text = Convert.ToString(countview_res.Items[0].Statistics.CommentCount);


            // title, description, channelId, chnnelTitle, publichedAt
            VideosResource.ListRequest snippet = youtube.Videos.List("snippet");//Videos statistics 연결
            snippet.Id = $"{this.Id}";
            VideoListResponse snippet_res = await snippet.ExecuteAsync();

            this.stitle         = Convert.ToString(snippet_res.Items[0].Snippet.Title);
            title.Text          = this.stitle;
            descriptionBox.Text = "\n\n" + Convert.ToString(snippet_res.Items[0].Snippet.Description.Replace("\n", "\r\n"));
            ChannelsResource.ListRequest yChannnelId = youtube.Channels.List("statistics");
            string channelId = snippet_res.Items[0].Snippet.ChannelId;

            yChannnelId.Id = channelId;
            ChannelListResponse yChnnelId_res = await yChannnelId.ExecuteAsync();

            // 구독자 수
            godog.Text = " 채널 구독자 수: " + Convert.ToString(yChnnelId_res.Items[0].Statistics.SubscriberCount) + " 명";

            channelTitle.Text = Convert.ToString(snippet_res.Items[0].Snippet.ChannelTitle);

            this.channelUrl = "https://www.youtube.com/channel/" + channelId;
            // title, description, channelId, chnnelTitle, publichedAt
            VideosResource.ListRequest contentDetials = youtube.Videos.List("contentDetails");//Videos statistics 연결
            contentDetials.Id = $"{this.Id}";
            VideoListResponse contentDetails_res = await contentDetials.ExecuteAsync();

            int    timeSeconds = TimeSeconds(contentDetails_res.Items[0].ContentDetails.Duration);
            string timeString  = TimeString(contentDetails_res.Items[0].ContentDetails.Duration);

            videoLength.Text = timeString;


            //status.embeddable	해야할것
            trackBar1.Maximum = timeSeconds;
        }
        public async Task <ActionResult <ChannelListResponse> > List([Required, FromQuery] AppChannelListRequest request)
        {
            YouTubeService service = await serviceAccessor.InitializeServiceAsync();

            ChannelsResource.ListRequest requestActual = request.ToActualRequest(service);

            try {
                ChannelListResponse response = await requestActual.ExecuteAsync();

                return(new ActionResult <ChannelListResponse>(response));
            } catch (GoogleApiException ex) {
                return(StatusCode((int)ex.HttpStatusCode, ex.ToString()));
            }
        }
 public ChannelsResource.ListRequest ToActualRequest(YouTubeService service)
 {
     ChannelsResource.ListRequest actual = service.Channels.List(Part);
     actual.CategoryId             = CategoryId;
     actual.ForUsername            = ForUsername;
     actual.Hl                     = Hl;
     actual.Id                     = Id;
     actual.ManagedByMe            = ManagedByMe;
     actual.MaxResults             = MaxResults;
     actual.Mine                   = Mine;
     actual.MySubscribers          = MySubscribers;
     actual.OnBehalfOfContentOwner = OnBehalfOfContentOwner;
     actual.PageToken              = PageToken;
     return(actual);
 }
Exemplo n.º 11
0
        /// <summary>
        /// Gets the channel associated with the account.
        /// </summary>
        /// <returns>The channel information</returns>
        public async Task <Channel> GetMyChannel()
        {
            return(await this.YouTubeServiceWrapper(async() =>
            {
                ChannelsResource.ListRequest search = this.connection.GoogleYouTubeService.Channels.List("snippet,statistics,contentDetails");
                search.Mine = true;
                search.MaxResults = 1;

                ChannelListResponse response = await search.ExecuteAsync();
                if (response.Items.Count > 0)
                {
                    return response.Items.First();
                }
                return null;
            }));
        }
Exemplo n.º 12
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>());
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Gets the channel associated with the specified username.
        /// </summary>
        /// <param name="username">The username to search for</param>
        /// <returns>The channel information</returns>
        public async Task <Channel> GetChannelByUsername(string username)
        {
            Validator.ValidateString(username, "username");
            return(await this.YouTubeServiceWrapper(async() =>
            {
                ChannelsResource.ListRequest search = this.connection.GoogleYouTubeService.Channels.List("snippet,statistics");
                search.ForUsername = username;
                search.MaxResults = 1;

                ChannelListResponse response = await search.ExecuteAsync();
                if (response.Items.Count > 0)
                {
                    return response.Items.First();
                }
                return null;
            }));
        }
Exemplo n.º 14
0
        /// <summary>
        /// Return a list of complete Channel objects from the youtube ids of the channels
        /// </summary>
        /// <param name="channelID"></param>
        /// <returns></returns>
        public async static Task <IEnumerable <Channel> > GetChannels(IEnumerable <string> channelIDs)
        {
            ChannelsResource.ListRequest request = YoutubeManager.YoutubeService.Channels.List("snippet");
            request.Id = string.Join(";", channelIDs);

            ChannelListResponse response = await request.ExecuteAsync();

            if (response.Items.Count > 0)
            {
                List <Channel> channels = new List <Channel>();
                foreach (var result in response.Items)
                {
                    channels.Add(new Channel(result.Snippet.Title, result.Id, result.Snippet.Thumbnails.High.Url));
                }

                return(channels);
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 15
0
        public async Task loadChannelStatistics()
        {
            String channelIds = "";

            lock (channelLock)
            {
                if (Children.Count == 0)
                {
                    return;
                }

                channelIds = (Children[0] as YoutubeChannelNode).ChannelId;

                for (int i = 1; i < Children.Count; i++)
                {
                    channelIds += "," + (Children[i] as YoutubeChannelNode).ChannelId;
                }
            }

            Google.Apis.YouTube.v3.ChannelsResource.ListRequest listRequest = new ChannelsResource.ListRequest(YoutubeViewModel.Youtube, "statistics");

            listRequest.Id = channelIds;

            ChannelListResponse response = await listRequest.ExecuteAsync();

            lock (channelLock)
            {
                foreach (Channel item in response.Items)
                {
                    YoutubeChannelNode node = getChannelWithId(item.Id);

                    if (node != null)
                    {
                        node.updateStatistics(item.Statistics);
                    }
                }
            }
        }
Exemplo n.º 16
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;
            }
        }
        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;
            }
        }
Exemplo n.º 18
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;
            }
        }
Exemplo n.º 19
0
        public async Task loadChannelStatistics()
        {
            String channelIds = "";

            lock (channelLock)
            {
                if (Children.Count == 0) return;

                channelIds = (Children[0] as YoutubeChannelNode).ChannelId;

                for (int i = 1; i < Children.Count; i++)
                {
                    channelIds += "," + (Children[i] as YoutubeChannelNode).ChannelId;
                }
            }
          
            Google.Apis.YouTube.v3.ChannelsResource.ListRequest listRequest = new ChannelsResource.ListRequest(YoutubeViewModel.Youtube, "statistics");

            listRequest.Id = channelIds;
          
            ChannelListResponse response = await listRequest.ExecuteAsync();

            lock (channelLock)
            {
                foreach (Channel item in response.Items)
                {
                    YoutubeChannelNode node = getChannelWithId(item.Id);

                    if (node != null)
                    {
                        node.updateStatistics(item.Statistics);
                    }
                }
            }

        }
Exemplo n.º 20
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);
        }
Exemplo n.º 21
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);
        }