Example #1
0
        /// <summary>
        /// Get the specified most recent videos IDs from a channel.
        /// </summary>
        /// <param name="channelID">ID of the channel to get videos IDs for.</param>
        public List <string> RecentVideoIDs(string channelID)
        {
            try {
                // https://developers.google.com/youtube/v3/docs/search/list
                API.SearchResource.ListRequest channelSearch = APIService.Search.List("id");
                channelSearch.ChannelId   = channelID;
                channelSearch.Order       = API.SearchResource.ListRequest.OrderEnum.Date;
                channelSearch.SafeSearch  = API.SearchResource.ListRequest.SafeSearchEnum.None;
                channelSearch.MaxResults  = 20;
                channelSearch.PrettyPrint = false;

                List <string> ids = channelSearch.Execute().Items.ToList().Where(x => x.Id.Kind == "youtube#video").Select(x => x.Id.VideoId).ToList();

                LoggingManager.Log.Info($"Videos retrieved for '{channelID}' with {ids.Count} results.");
                return(ids);
            } catch (Exception ex) {
                LoggingManager.Log.Error(ex, $"Failed to get videos for '{channelID}'.");
                return(new List <string>());
            }
        }
Example #2
0
        /// <summary>
        /// Search for a channel by its name, or a multitude of other information.
        /// </summary>
        /// <param name="channelName">The name, or any other data about the channel to search for.</param>
        public List <Database.Types.Channel> Search(string channelName)
        {
            try {
                // https://developers.google.com/youtube/v3/docs/search/list
                API.SearchResource.ListRequest channelSearch = APIService.Search.List("id,snippet");
                channelSearch.Q           = channelName;
                channelSearch.Type        = "channel";
                channelSearch.Order       = API.SearchResource.ListRequest.OrderEnum.Relevance;
                channelSearch.MaxResults  = 10;
                channelSearch.PrettyPrint = false;

                List <Database.Types.Channel> results = new List <Database.Types.Channel>();

                foreach (API.Data.SearchResult item in channelSearch.Execute().Items)
                {
                    if (item.Id.Kind == "youtube#channel")
                    {
                        API.Data.SearchResultSnippet channel = item.Snippet;

                        Database.Types.Channel channelInfo = new Database.Types.Channel {
                            ID           = channel.ChannelId,
                            Title        = channel.Title,
                            Description  = channel.Description,
                            ThumbnailURL = GetBestThumbnail(channel.Thumbnails)
                        };

                        results.Add(channelInfo);
                        LoggingManager.Log.Info($"Information processed for '{channelInfo.ID}'.");
                    }
                }

                return(results);
            } catch (Exception ex) {
                LoggingManager.Log.Error(ex, $"Failed to search for '{channelName}'.");
                return(new List <Database.Types.Channel>());
            }
        }
Example #3
0
        public YoutubeRequest BuildRequest(YoutubeSearchOption searchOption)
        {
            YouTubeService youtube = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey = ApiKey
            });

            YoutubeRequest listRequest = youtube.Search.List("snippet");

            listRequest.Q = searchOption.Query;

            if (searchOption.UseDateSearch)
            {
                listRequest.PublishedAfter  = searchOption.DateRange.Since;
                listRequest.PublishedBefore = searchOption.DateRange.Until;
            }

            listRequest.Order = OrderEnum.Relevance;

            listRequest.VideoDuration = VideoDurationEnum.Short__;

            int count = searchOption.SearchCount;

            listRequest.MaxResults = count <= 50 ? count : 50;
            listRequest.SafeSearch = SafeSearchEnum.Strict;

            listRequest.VideoDuration = (VideoDurationEnum)searchOption.YoutubeVideoDuration;

            listRequest.Order = (OrderEnum)searchOption.YoutubeSortOrder;

            if (searchOption.RegionCode != RegionCode.All)
            {
                listRequest.RegionCode = searchOption.RegionCode.ToString();
            }

            return(listRequest);
        }
Example #4
0
        /// <summary>
        /// Youtube를 이용해 검색을 실시합니다.
        /// </summary>
        /// <param name="searchOption">Youtube의 검색 옵션입니다.</param>
        /// <returns></returns>
        public override IEnumerable <YoutubeSearchResult> Search(YoutubeSearchOption searchOption)
        {
            try
            {
                YoutubeRequest listRequest = BuildRequest(searchOption);
                var            list        = new List <YoutubeSearchResult>();

                // TODO: 100개 이상일시에 count가 오류 생길 것으로 추측, 수정 필요
                // TODO: NextPageToken 확인 부분이 의심스러움. 확인 필요

                int remain = searchOption.SearchCount;
                int count  = 1;

                string nextToken = string.Empty;

                while (true)
                {
                    if (!nextToken.IsNullOrEmpty())
                    {
                        listRequest.PageToken = nextToken;
                    }

                    SearchListResponse searchResponse = listRequest.Execute();

                    nextToken = searchResponse.NextPageToken;

                    var videos = new List <SearchResult>();

                    foreach (SearchResult searchResult in searchResponse.Items)
                    {
                        OnChangeInfoMessage(this, new MessageEventArgs("비디오 타입을 분석중입니다."));
                        if (searchResult.Id.Kind == "youtube#video")
                        {
                            videos.Add(searchResult);
                            remain--;
                            OnSearchProgressChanged(this, new ProgressEventArgs(searchOption.SearchCount, count++));
                        }
                        if (remain <= 0)
                        {
                            break;
                        }
                    }

                    count = 1;

                    videos.AsParallel().ForAll(s =>
                    {
                        OnChangeInfoMessage(this, new MessageEventArgs("설명을 가져오는 중입니다."));
                        OnSearchProgressChanged(this, new ProgressEventArgs(searchOption.SearchCount, count++));

                        string title       = s.Snippet.Title;
                        string description = s.Snippet.Description;

                        if (description.EndsWith("..."))
                        {
                            description = GetFullDescription(s.Id.VideoId);
                        }

                        var itm = new YoutubeSearchResult()
                        {
                            Title         = title,
                            OriginalURL   = $"{"http:"}//youtube.com/watch?v={s.Id.VideoId}",
                            PublishedDate = s.Snippet.PublishedAt,
                            ChannelTitle  = s.Snippet.ChannelTitle,
                            Description   = description,
                            ChannelId     = s.Snippet.ChannelId,
                            VideoId       = s.Id.VideoId,
                            Keyword       = searchOption.Query,
                        };

                        OnSearchItemFound(this, new SearchResultEventArgs(itm, ServiceKind.Youtube));

                        list.Add(itm);
                    });

                    if (remain <= 0)
                    {
                        break;
                    }
                }
                OnSearchFinished(this, new SearchFinishedEventArgs(ServiceKind.Youtube));

                return(list);
            }
            catch (GoogleApiException ex)
            {
                if (ex.Message.ToLower().Contains("keyinvalid"))
                {
                    throw new CredentialsTypeException("키가 올바르게 입력되지 않았습니다.");
                }
                else if (ex.Message.ToLower().Contains("keyexpired"))
                {
                    throw new CredentialsTypeException("이 키는 사용이 만료되었습니다.");
                }
                else
                {
                    throw ex;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }