Example #1
0
        public static async Task <SearchListResponse> ExecuteAllAsync(this SearchResource.ListRequest request, CancellationToken ct = default(CancellationToken))
        {
            request.MaxResults = request.MaxResults ?? 50;
            var response = await request.ExecuteAsync(ct);

            if (!response.Items.Any())
            {
                return(response);
            }
            var collection = response.Items.ToList();

            while (!ct.IsCancellationRequested)
            {
                if (string.IsNullOrWhiteSpace(response.NextPageToken))
                {
                    break;
                }
                request.PageToken = response.NextPageToken;
                response          = await request.ExecuteAsync(ct);

                if (response.Items.Any())
                {
                    collection.AddRange(response.Items);
                }
            }

            response.Items = collection;
            return(response);
        }
Example #2
0
        private async Task <bool> YoutubeSearch()
        {
            YouTubeService youtube = new YouTubeService(new BaseClientService.Initializer()
            {
                ApplicationName = "...",
                ApiKey          = "..."
            });

            SearchResource.ListRequest listRequest = youtube.Search.List("snippet");
            listRequest.Q          = search;
            listRequest.MaxResults = 1;
            listRequest.Type       = "video";
            SearchListResponse resp = await listRequest.ExecuteAsync();

            if (resp.Items.Count() == 0)
            {
                return(false);
            }
            SearchResult result = resp.Items.ElementAt(0);

            context.Song.VideoId  = result.Id.VideoId;
            context.Song.Title    = result.Snippet.Title;
            context.Song.Provider = MusicProvider.YOUTUBE;
            return(true);
        }
Example #3
0
        public async Task <List <string> > GetUrlsOfTopVideos(string channelId)
        {
            List <string> YoutubeUrls = new List <string>();


            try
            {
                int maxResultCount = 4;

                SearchResource.ListRequest searchListRequest = client.Search.List("snippet");
                //searchListRequest.Q = channelId;
                searchListRequest.MaxResults = maxResultCount;
                searchListRequest.ChannelId  = channelId;
                searchListRequest.Type       = "video";

                SearchListResponse searchListResponse = await searchListRequest.ExecuteAsync();

                foreach (SearchResult searchResult in searchListResponse.Items)
                {
                    string url = "https://www.youtube.com/embed/";
                    url += searchResult.Id.VideoId;
                    YoutubeUrls.Add(url);
                }
            }
            catch (Exception e)
            {
                YoutubeUrls.Add("failure");
            }



            return(YoutubeUrls);
        }
Example #4
0
        internal async Task <IEnumerable <SearchResult> > Search(bool myVideos = false, string keyword = null, int maxResults = 1)
        {
            return(await this.YouTubeServiceWrapper(async() =>
            {
                List <SearchResult> results = new List <SearchResult>();
                string pageToken = null;
                do
                {
                    SearchResource.ListRequest search = this.connection.GoogleYouTubeService.Search.List("snippet");
                    if (myVideos)
                    {
                        search.ForMine = true;
                        search.Order = SearchResource.ListRequest.OrderEnum.Date;
                    }
                    else if (!string.IsNullOrEmpty(keyword))
                    {
                        search.Q = keyword;
                    }
                    search.MaxResults = Math.Min(maxResults, 50);
                    search.Type = "video";
                    search.PageToken = pageToken;

                    SearchListResponse response = await search.ExecuteAsync();
                    results.AddRange(response.Items);
                    maxResults -= response.Items.Count;
                    pageToken = response.NextPageToken;
                } while (maxResults > 0 && !string.IsNullOrEmpty(pageToken));
                return results;
            }));
        }
        private async Task Run(SteamID toID, string[] query, bool room)
        {
            YouTubeService ys = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey          = Options.ChatCommandApi.ApiKey,
                ApplicationName = "Steam Chat Bot"
            });

            SearchResource.ListRequest search = ys.Search.List("snippet");
            string q = "";

            for (int i = 1; i < query.Length; i++)
            {
                q += query[i] + " ";
            }
            q                 = q.Trim();
            search.Q          = q;
            search.MaxResults = 1;

            SearchListResponse response = await search.ExecuteAsync();

            foreach (SearchResult result in response.Items)
            {
                if (result.Id.Kind == "youtube#video")
                {
                    SendMessageAfterDelay(toID, "https://youtube.com/watch?v=" + result.Id.VideoId, room);
                }
                else if (result.Id.Kind == "youtube#channel")
                {
                    SendMessageAfterDelay(toID, "https://youtube.com/channel/" + result.Id.ChannelId, room);
                }
            }
        }
Example #6
0
        public async Task <IList <ResponseSearchItem> > Search(string text)
        {
            var youtube = new Google.Apis.YouTube.v3.YouTubeService(new Google.Apis.Services.BaseClientService.Initializer()
            {
                HttpClientInitializer = Autenticar()
            });

            SearchResource.ListRequest listRequest = youtube.Search.List("snippet");

            listRequest.Q          = text;
            listRequest.MaxResults = 10;
            listRequest.Order      = SearchResource.ListRequest.OrderEnum.Relevance;

            SearchListResponse searchResponse = await listRequest.ExecuteAsync();

            return(searchResponse.Items.Select(item =>
                                               new ResponseSearchItem
            {
                Name = item.Snippet.Title,
                Url = item.Snippet.Thumbnails.Default__.Url,
                Type = item.Id.Kind,
                VideoId = item.Id.VideoId
            }
                                               ).ToList());
        }
Example #7
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());
        }
        /// <summary>
        /// Refreshes the cached data in Cassandra for a given YouTube keyword search.
        /// </summary>
        internal async Task RefreshKeywords(YouTubeVideoSource.VideosWithKeyword keywordSource)
        {
            // Statement for inserting the video into the sample table
            PreparedStatement preparedInsert = await _statementCache.NoContext.GetOrAddAsync(
                "INSERT INTO sample_data_youtube_videos (sourceid, published_at, youtube_video_id, name, description) VALUES (?, ?, ?, ?, ?)");

            bool   getMoreVideos = true;
            string nextPageToken = null;
            var    insertTasks   = new List <Task>();

            do
            {
                // Create search by keywords request
                SearchResource.ListRequest searchRequest = _youTubeService.Search.List("snippet");
                searchRequest.MaxResults = MaxVideosPerRequest;
                searchRequest.Q          = keywordSource.SearchTerms;
                searchRequest.Type       = "video";
                if (string.IsNullOrEmpty(nextPageToken) == false)
                {
                    searchRequest.PageToken = nextPageToken;
                }

                // Get the results and insert as rows in Cassandra
                SearchListResponse searchResults = await searchRequest.ExecuteAsync().ConfigureAwait(false);

                foreach (SearchResult searchResult in searchResults.Items)
                {
                    // If we've reached the max, no need to continue
                    if (insertTasks.Count >= MaxVideosPerSource)
                    {
                        getMoreVideos = false;
                        break;
                    }

                    DateTimeOffset publishedAt = searchResult.Snippet.PublishedAt.HasValue
                                                     ? searchResult.Snippet.PublishedAt.Value.ToUniversalTime()
                                                     : Epoch;

                    Task <RowSet> insertTask = _session.ExecuteAsync(preparedInsert.Bind(keywordSource.UniqueId, publishedAt, searchResult.Id.VideoId,
                                                                                         searchResult.Snippet.Title, searchResult.Snippet.Description));
                    insertTasks.Add(insertTask);
                }

                // If we don't have a next page, we can bail
                nextPageToken = searchResults.NextPageToken;
                if (string.IsNullOrEmpty(nextPageToken))
                {
                    getMoreVideos = false;
                }
            } while (getMoreVideos);

            // Wait for any insert tasks to finish
            if (insertTasks.Count > 0)
            {
                await Task.WhenAll(insertTasks).ConfigureAwait(false);
            }
        }
Example #9
0
        public async Task <IEnumerable <QueryResult> > QueryManyVideos(QueryResult query)
        {
            SearchResource.ListRequest searchRequest = _youTubeApiService.Search.List("snippet");
            searchRequest.Q          = query.Query;
            searchRequest.MaxResults = MaxQueryResults;

            SearchListResponse searchResponse = await searchRequest.ExecuteAsync();

            return((await GetVideos(searchResponse.Items.Where(video => video.Id.Kind.Contains("video")).Select(video => video.Id.VideoId))).Select(video => new QueryResult(query, video)));
        }
Example #10
0
        public async Task <Pagination> SeachAsync(string term, string nextPageToken = "")
        {
            var pagination = new Pagination();

            pagination.Search = term;
            SearchResource.ListRequest listRequest = service.Search.List("snippet");
            listRequest.Q          = term;
            listRequest.Order      = SearchResource.ListRequest.OrderEnum.Relevance;
            listRequest.MaxResults = 5;
            listRequest.PageToken  = nextPageToken;

            SearchListResponse searchResponse = await listRequest.ExecuteAsync();

            foreach (SearchResult searchResult in searchResponse.Items)
            {
                pagination.NextPage = searchResponse.NextPageToken;

                var favorite = new Favorite();
                favorite.Title       = searchResult.Snippet.Title;
                favorite.Description = searchResult.Snippet.Description;
                favorite.PublishedAt = searchResult.Snippet.PublishedAt;

                switch (searchResult.Id.Kind)
                {
                case "youtube#video":
                    favorite.Type = SearchType.Video;
                    favorite.Id   = searchResult.Id.VideoId;
                    break;

                case "youtube#channel":
                    favorite.Type = SearchType.Channel;
                    favorite.Id   = searchResult.Id.ChannelId;
                    break;

                case "youtube#playlist":
                    favorite.Type = SearchType.Playlist;
                    favorite.Id   = searchResult.Id.PlaylistId;

                    break;
                }


                pagination.Favorites.Add(favorite);
            }

            var allfavorites = await this.favoriteRepository.List(term);

            allfavorites.ForEach(x => x.IsFavorite = true);
            var favoritesIds = allfavorites.Select(x => x.Id);

            pagination.Favorites.RemoveAll(x => favoritesIds.Contains(x.Id));
            pagination.Favorites.AddRange(allfavorites);

            return(pagination);
        }
Example #11
0
 public async Task <SearchListResponse> Search(string content, string pageToken = null, int maxResult = 50)
 {
     SearchResource.ListRequest request = _youTubeService.Search.List("snippet");
     request.Q          = content;
     request.MaxResults = maxResult;
     if (!string.IsNullOrEmpty(pageToken) && !string.IsNullOrWhiteSpace(pageToken))
     {
         request.PageToken = pageToken;
     }
     return(await request.ExecuteAsync());
 }
Example #12
0
        public async Task <List <YoutubeSong> > FetchAsync()
        {
            List <YoutubeSong> res;

            if (nextToken != null)
            {
                //not the first time, use the token to get the rest of the search
                _sr.PageToken = nextToken;

                //finds informasjons about tracks
                res = getSearchResult(await _sr.ExecuteAsync());
            }
            else
            {
                //First time
                res = getSearchResult(await _sr.ExecuteAsync());
            }

            return(res);
        }
Example #13
0
        public async Task <SearchListResponse> Search(SearchQuery query)
        {
            SearchResource.ListRequest listRequest = _youtubeService.Search.List(query.Part);
            listRequest.Q          = query.Query;
            listRequest.Order      = query.Order;
            listRequest.PageToken  = query.PageToken;
            listRequest.MaxResults = query.MaxResults;
            listRequest.Type       = query.Type;

            return(await listRequest.ExecuteAsync());
        }
Example #14
0
        public static async Task <List <SearchResult> > Search(string query)
        {
            youtubeSearcher.Q          = query;
            youtubeSearcher.Fields     = "items/id,items/snippet";
            youtubeSearcher.MaxResults = 10;

            // Call the search.list method to retrieve results matching the specified query term.
            var searchListResponse = await youtubeSearcher.ExecuteAsync();

            List <SearchResult> Videos    = new List <SearchResult>();
            List <string>       channels  = new List <string>();
            List <string>       playlists = new List <string>();

            // 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":
                    Videos.Add(searchResult);
                    break;

                case "youtube#channel":
                    channels.Add(string.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.ChannelId));
                    break;

                case "youtube#playlist":
                    playlists.Add(string.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.PlaylistId));
                    break;

                default:
                    break;
                }
            }

            return(Videos);
        }
Example #15
0
        private async Task <IReadOnlyList <SearchResult> > SearchAsync(string query, int amount, string type = null)
        {
            SearchResource.ListRequest request = this.yt.Search.List("snippet");
            request.Q          = query;
            request.MaxResults = amount;
            if (!string.IsNullOrWhiteSpace(type))
            {
                request.Type = type;
            }

            SearchListResponse response = await request.ExecuteAsync().ConfigureAwait(false);

            return(response.Items.ToList().AsReadOnly());
        }
        private static async Task CheckForNewContentAsync(WatchedChannel watched)
        {
            SearchResource.ListRequest listRequest = YoutubeS.Search.List("snippet");
            listRequest.ChannelId  = watched.ChannelId;
            listRequest.Type       = "video";
            listRequest.Order      = SearchResource.ListRequest.OrderEnum.Date;
            listRequest.MaxResults = 1;
            if (watched.WatchedType == WatchType.Livestream)
            {
                listRequest.EventType = SearchResource.ListRequest.EventTypeEnum.Live;
            }

            SearchListResponse searchResponse;

            try
            {
                searchResponse = await listRequest.ExecuteAsync();
            }
            catch (Exception ex)
            {
                Log.Error(ex, "YoutubeService threw an error");
                return;
            }

            SearchResult data = searchResponse.Items.FirstOrDefault(v => v.Id.Kind == "youtube#video");

            if (data != null && (watched.LastVideoId != null || watched.WatchedType == WatchType.Livestream) && data.Id.VideoId != watched.LastVideoId)
            {
                foreach (var channelId in watched.ChannelsThatAreSubbed)
                {
                    var socketTextChannel = _client.GetChannel(channelId) as SocketTextChannel;
                    if (socketTextChannel != null)
                    {
                        var eb = new EmbedBuilder()
                                 .WithTitle(data.Snippet.Title)
                                 .WithDescription($"{data.Snippet.ChannelTitle} {(watched.WatchedType == WatchType.Livestream ? "just went live!" : "just uploaded a new video!" )}")
                                 .WithUrl($"https://www.youtube.com/watch?v=" + $"{data.Id.VideoId}")
                                 .WithImageUrl(data.Snippet.Thumbnails.High.Url)
                                 .WithColor(new Color(0xb31217));
                        await socketTextChannel.SendMessageAsync("", embed : eb);
                    }
                    else //means we're no longer in the guild that contains this channel, or the channel was deleted
                    {
                        TryRemove(channelId, watched.ChannelId, watched.WatchedType);
                    }
                }
            }
            watched.LastVideoId = data?.Id.VideoId;
        }
Example #17
0
        public async Task YoutubeVideoSearch([Remainder][Summary("String to search YouTube on")] string message)
        {
            SearchResource.ListRequest searchlistRequest = youTubeService.Search.List("snippet");
            searchlistRequest.Q          = MessageParser.RemoveTriggerWord(message); //Search term
            searchlistRequest.MaxResults = 5;

            SearchListResponse searchListResponse = await searchlistRequest.ExecuteAsync();

            List <string> videos = (from response
                                    in searchListResponse.Items
                                    where response.Id.Kind == "youtube#video"
                                    select $"{response.Id.VideoId}").ToList();

            await ReplyAsync($"https://www.youtube.com/watch?v={videos.FirstOrDefault()}");
        }
Example #18
0
        /// <summary>
        /// Searches a channel for a keyword.
        /// </summary>
        /// <param name="keyword">The keyword to search the channel for.</param>
        /// <param name="maxResults">The maximum number of results to retrieve.</param>
        /// <returns></returns>
        public async Task <List <SearchResult> > SearchChannelsAsync(string keyword = "space", int maxResults = 5)
        {
            YouTubeService youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey          = Global.YouTubeAPIKey,
                ApplicationName = this.GetType().ToString()
            });

            SearchResource.ListRequest searchListRequest = youtubeService.Search.List("snippet");
            searchListRequest.Q          = keyword;
            searchListRequest.MaxResults = maxResults;
            SearchListResponse searchListResponse = await searchListRequest.ExecuteAsync();

            return(searchListResponse.Items.ToList());
        }
Example #19
0
        /// <summary>
        /// Performs a search for youtube videos
        /// </summary>
        /// <param name="myVideos">Only get videos associated with the connected account</param>
        /// <param name="channelID">The specific ID of the channel to get videos for</param>
        /// <param name="keyword">Keywords to search for in the video</param>
        /// <param name="liveType">The live video type to search for</param>
        /// <param name="maxResults">The maximum results to return</param>
        /// <returns>The list of videos</returns>
        public async Task <IEnumerable <SearchResult> > SearchVideos(bool myVideos = false, string channelID = null, string keyword = null, SearchResource.ListRequest.EventTypeEnum liveType = SearchResource.ListRequest.EventTypeEnum.None, int maxResults = 1)
        {
            if (myVideos && !string.IsNullOrEmpty(channelID))
            {
                Validator.Validate(false, "Only myVideos or channelID can be set");
            }

            return(await this.YouTubeServiceWrapper(async() =>
            {
                List <SearchResult> results = new List <SearchResult>();
                string pageToken = null;
                do
                {
                    SearchResource.ListRequest request = this.connection.GoogleYouTubeService.Search.List("snippet");
                    if (myVideos)
                    {
                        request.ForMine = true;
                    }
                    else if (!string.IsNullOrEmpty(channelID))
                    {
                        request.ChannelId = channelID;
                    }

                    if (!string.IsNullOrEmpty(keyword))
                    {
                        request.Q = keyword;
                    }

                    if (liveType != SearchResource.ListRequest.EventTypeEnum.None)
                    {
                        request.EventType = liveType;
                    }

                    request.Type = "video";
                    request.Order = SearchResource.ListRequest.OrderEnum.Date;
                    request.MaxResults = Math.Min(maxResults, 50);
                    request.PageToken = pageToken;
                    LogRequest(request);

                    SearchListResponse response = await request.ExecuteAsync();
                    LogResponse(request, response);
                    results.AddRange(response.Items);
                    maxResults -= response.Items.Count;
                    pageToken = response.NextPageToken;
                } while (maxResults > 0 && !string.IsNullOrEmpty(pageToken));
                return results;
            }));
        }
Example #20
0
        private async Task <IEnumerable <QueryResult> > QueryVideosPrivate(QueryResult query)
        {
            // Types of query:
            // == Video ==
            // 1. Video title               Ed Sheeran - Perfect (Official Music Video)
            // 2. Full video URL            https://www.youtube.com/watch?v=2Vv-BfVoq4g
            // 3. Video ID                  2Vv-BfVoq4g
            //
            // == Playlist ==
            // 4. Full playlist video URL   https://www.youtube.com/watch?v=2Vv-BfVoq4g&list=PLx0sYbCqOb8TBPRdmBHs5Iftvv9TPboYG
            // 5. Full playlist URL         https://www.youtube.com/playlist?list=PLx0sYbCqOb8TBPRdmBHs5Iftvv9TPboYG
            // 6. Playlist ID               PLx0sYbCqOb8TBPRdmBHs5Iftvv9TPboYG

            // Query type 4
            {
                Match queryMatch = Regex.Match(query.Query, @"watch\?v=[^&]+.+list=(?<PlaylistId>[^&\n]+)");

                if (queryMatch.Success)
                {
                    return((await GetPlaylistVideos(queryMatch.Groups["PlaylistId"].Value)).Select(video => new QueryResult(query, video)));
                }
            }

            SearchResource.ListRequest searchRequest = _youTubeApiService.Search.List("snippet");
            searchRequest.Q          = query.Query;
            searchRequest.MaxResults = 1;

            SearchListResponse searchResponse = await searchRequest.ExecuteAsync();

            SearchResult result = searchResponse.Items.SingleOrDefault();

            if (result != null)
            {
                if (result.Id.Kind.Contains("video")) // Query types 1, 2, 3
                {
                    return(new QueryResult(query, await GetVideo(result.Id.VideoId)).ToEnumerable());
                }

                if (result.Id.Kind.Contains("playlist")) // Query types 5, 6
                {
                    return((await GetPlaylistVideos(result.Id.PlaylistId)).Select(video => new QueryResult(query, video)));
                }
            }

            // Invalid query (for the time being)
            return(Enumerable.Empty <QueryResult>());
        }
Example #21
0
        /// <summary>
        /// Play songs from the channel of your choice.
        /// </summary>
        /// <param name="ChannelID"></param>
        public async static void MixFromChannel(string ChannelID)
        {
            if (!await MainActivity.instance.WaitForYoutube())
            {
                return;
            }

            List <Song> songs = new List <Song>();

            try
            {
                SearchResource.ListRequest searchRequest = YoutubeService.Search.List("snippet");
                searchRequest.Fields     = "items(id/videoId,snippet/title,snippet/thumbnails/high/url,snippet/channelTitle)";
                searchRequest.Type       = "video";
                searchRequest.ChannelId  = ChannelID;
                searchRequest.MaxResults = 20;
                var searchReponse = await searchRequest.ExecuteAsync();


                foreach (var video in searchReponse.Items)
                {
                    Song song = new Song(WebUtility.HtmlDecode(video.Snippet.Title), video.Snippet.ChannelTitle, video.Snippet.Thumbnails.High.Url, video.Id.VideoId, -1, -1, null, true, false)
                    {
                        ChannelID = video.Snippet.ChannelId
                    };
                    songs.Add(song);
                }
            }
            catch (System.Net.Http.HttpRequestException)
            {
                MainActivity.instance.Timout();
            }

            Random r = new Random();

            songs = songs.OrderBy(x => r.Next()).ToList();
            SongManager.Play(songs[0]);
            songs.RemoveAt(0);

            while (MusicPlayer.instance == null)
            {
                await Task.Delay(10);
            }

            MusicPlayer.instance.AddToQueue(songs);
        }
Example #22
0
        public static async Task <dynamic> Search(AppSettings appSettings, JObject requestBody)
        {
            string  methodName = "Search";
            dynamic result     = new ExpandoObject();

            try
            {
                // https://developers.google.com/youtube/v3/docs/search/list
                // https://developers.google.com/youtube/v3/code_samples/dotnet#search_by_keyword
                YouTubeService youtubeService = new YouTubeService(new BaseClientService.Initializer()
                {
                    ApiKey = requestBody["apikey"]?.ToString()
                });
                SearchResource.ListRequest listRequest = youtubeService.Search.List("snippet");
                listRequest.Q          = requestBody["q"]?.ToString();
                listRequest.MaxResults = 50;
                listRequest.Type       = requestBody["type"]?.ToString() ?? "video"; // Accepted values: channel, playlist, video
                if (requestBody["channelId"] != null)
                {
                    listRequest.ChannelId = requestBody["channelId"].ToString();
                }
                if (requestBody["order"] != null)
                {
                    //Accepted values: date, rating, relevance, title, videoCount, viewCount
                    listRequest.Order = Enum.Parse <SearchResource.ListRequest.OrderEnum>(requestBody["order"].ToString());
                }
                if (requestBody["publishedAfter"] != null)
                {
                    listRequest.PublishedAfter = DateTime.ParseExact(requestBody["publishedAfter"].ToString(), "yyyy-MM-dd", CultureInfo.InvariantCulture).ToString();
                }
                if (requestBody["publishedBefore"] != null)
                {
                    listRequest.PublishedBefore = DateTime.ParseExact(requestBody["publishedBefore"].ToString(), "yyyy-MM-dd", CultureInfo.InvariantCulture).ToString();
                }
                SearchListResponse listResponse = await listRequest.ExecuteAsync();

                return(listResponse);
            }
            catch (Exception e)
            {
                Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {JsonConvert.SerializeObject(requestBody)}");
                Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {e.Source + Environment.NewLine + e.Message + Environment.NewLine + e.StackTrace}");
                throw e;
            }
        }
        public async Task SetIdAndUrlVideo(string videoName, string channelName)
        {
            VideoSearch items          = new VideoSearch();
            var         youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey          = apiKey,
                ApplicationName = GetType().ToString()
            });

            SearchResource.ListRequest searchListRequest = youtubeService.Search.List("snippet");
            searchListRequest.Q          = channelName + " " + videoName;
            searchListRequest.MaxResults = 30;
            SearchListResponse searchListResponse = await searchListRequest.ExecuteAsync();

            SearchResult searchResponse = searchListResponse.Items.FirstOrDefault(c => c.Snippet.ChannelTitle.ToLower().Replace(" ", "") == channelName);

            Id  = searchResponse.Id.VideoId;
            Url = "https://www.youtube.com/watch?v=" + Id;
        }
Example #24
0
        private async Task Run()
        {
            BaseClientService.Initializer baseClientServiceInitializer = new BaseClientService.Initializer
            {
                ApiKey          = CredentialsManager.GetApiKey(),
                ApplicationName = GetType().ToString()
            };
            YouTubeService youtubeService = new YouTubeService(baseClientServiceInitializer);

            SearchResource.ListRequest searchListRequest = youtubeService.Search.List("snippet");
            searchListRequest.Q          = "Google"; // Replace with your search term.
            searchListRequest.MaxResults = 50;

            // Call the search.list method to retrieve results matching the specified query term.
            SearchListResponse searchListResponse = await searchListRequest.ExecuteAsync();

            List <string> videos    = new List <string>();
            List <string> channels  = new List <string>();
            List <string> playlists = new List <string>();

            // Add each result to the appropriate list, and then display the lists of
            // matching videos, channels, and playlists.
            foreach (SearchResult searchResult in searchListResponse.Items)
            {
                switch (searchResult.Id.Kind)
                {
                case "youtube#video":
                    videos.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.VideoId));
                    break;

                case "youtube#channel":
                    channels.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.ChannelId));
                    break;

                case "youtube#playlist":
                    playlists.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.PlaylistId));
                    break;
                }
            }
            Console.WriteLine("Videos:\n{0}\n", string.Join("\n", videos));
            Console.WriteLine("Channels:\n{0}\n", string.Join("\n", channels));
            Console.WriteLine("Playlists:\n{0}\n", string.Join("\n", playlists));
        }
        private async Task <VideoDto> GetUpcomingLiveStream()
        {
            YouTubeService t = GetYoutubeService();

            SearchResource.ListRequest request = t.Search.List("id");
            request.ChannelId  = "UC_a1ZYZ8ZTXpjg9xUY9sj8w";
            request.EventType  = SearchResource.ListRequest.EventTypeEnum.Live;
            request.MaxResults = 1;
            request.Type       = "video";
            request.Fields     = "items(id(videoId))";
            SearchListResponse result = await request.ExecuteAsync();

            SearchResult livestream = result.Items.FirstOrDefault();

            return(new VideoDto()
            {
                VideoId = livestream?.Id.VideoId,
                StartTime = TimeZoneInfo.ConvertTimeToUtc(DateTime.Parse(livestream.Snippet.PublishedAt))
            });
        }
        internal async Task <string> GetLiveStream(YouTubeService ytService, string eventType)
        {
            try
            {
                SearchResource.ListRequest request = ytService.Search.List("id");
                request.ChannelId  = "UC_a1ZYZ8ZTXpjg9xUY9sj8w";
                request.EventType  = eventType.ToEnum <SearchResource.ListRequest.EventTypeEnum>();
                request.MaxResults = 1;
                request.Type       = "video";
                request.Fields     = "items(id(videoId))";
                SearchListResponse result = await request.ExecuteAsync();

                SearchResult livestream = result.Items.FirstOrDefault();
                return(livestream?.Id.VideoId);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, nameof(GetLiveStream));
                return(null);
            }
        }
Example #27
0
        public async Task <IActionResult> Get([FromQuery] string query, [FromQuery] string pageToken)
        {
            if (string.IsNullOrEmpty(query))
            {
                return(BadRequest("Please type a query to search"));
            }

            YouTubeService youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey = _youtubeApiSettingsOptions.ApiKey
            });

            SearchResource.ListRequest listRequest = youtubeService.Search.List("snippet");
            listRequest.Q          = query;
            listRequest.PageToken  = pageToken;
            listRequest.MaxResults = 24;
            listRequest.Order      = SearchResource.ListRequest.OrderEnum.Relevance;
            listRequest.Type       = "video";


            VideoSearchDto result = new VideoSearchDto();

            SearchListResponse searchResponse = await listRequest.ExecuteAsync();

            result.NextPage = searchResponse.NextPageToken;

            foreach (SearchResult searchResult in searchResponse.Items)
            {
                YoutubeVideo video = new YoutubeVideo
                {
                    Id        = searchResult.Id.VideoId,
                    Title     = searchResult.Snippet.Title,
                    Thumbnail = searchResult.Snippet.Thumbnails.Medium.Url
                };

                result.Videos.Add(video);
            }

            return(Ok(result));
        }
        private async Task <VideoDto> GetCurrentLiveStream()
        {
            YouTubeService t = new YouTubeService(new Google.Apis.Services.BaseClientService.Initializer()
            {
                ApiKey          = ApiKey,
                ApplicationName = "TimeStampBot"
            });

            SearchResource.ListRequest request = t.Search.List("id");
            request.ChannelId  = "UC_a1ZYZ8ZTXpjg9xUY9sj8w";
            request.EventType  = SearchResource.ListRequest.EventTypeEnum.Live;
            request.MaxResults = 1;
            request.Type       = "video";
            request.Fields     = "items(id(videoId))";
            SearchListResponse result = await request.ExecuteAsync();

            SearchResult livestream = result.Items.FirstOrDefault();

            return(new VideoDto()
            {
                VideoId = livestream?.Id.VideoId,
                StartTime = TimeZoneInfo.ConvertTimeToUtc(DateTime.Parse(livestream.Snippet.PublishedAt))
            });
        }
Example #29
0
        private async Task <string> SearchVideo(string name)
        {
            var youtubeService = new YouTubeService(new BaseClientService.Initializer
            {
                ApiKey          = _settings.YoutubeApiKey,
                ApplicationName = GetType()
                                  .ToString()
            });

            SearchResource.ListRequest searchListRequest = youtubeService.Search.List("snippet");
            searchListRequest.Q          = name;
            searchListRequest.MaxResults = 1;
            searchListRequest.Type       = "video";

            SearchListResponse searchListResponse = await searchListRequest.ExecuteAsync();

            SearchResult trailer = searchListResponse.Items.FirstOrDefault();

            if (trailer == null)
            {
                return(null);
            }
            return($"https://www.youtube.com/watch?v={trailer.Id.VideoId}");
        }
Example #30
0
        // We split this into another function because it's also used by the Radio
        public static async Task <Video> GetYoutubeVideoAsync(string search)
        {
            // Check if the search given in an URL
            string id    = null;
            Match  match = Regex.Match(search, "https:\\/\\/www.youtube.com\\/watch\\?v=([^&]+)");

            if (match.Success)
            {
                id = match.Groups[1].Value;
            }
            else
            {
                match = Regex.Match(search, "https:\\/\\/youtu.be\\/([^&]+)");
                if (match.Success)
                {
                    id = match.Groups[1].Value;
                }
                else // If the search is an ID
                {
                    match = Regex.Match(search, "^[0-9a-zA-Z_-]{11}$");
                    if (match.Success && match.Value.Length == 11)
                    {
                        id = search;
                    }
                }
            }

            Video result = null;

            if (id != null) // If managed to get the Id of the video thanks to the previous REGEX
            {
                VideosResource.ListRequest r = StaticObjects.YouTube.Videos.List("snippet,statistics,contentDetails");
                r.Id = id;
                var resp = (await r.ExecuteAsync()).Items;
                if (resp.Count != 0)
                {
                    result = resp[0];
                }
            }
            if (result == null)
            {
                SearchResource.ListRequest listRequest = StaticObjects.YouTube.Search.List("snippet");
                listRequest.Q          = search;
                listRequest.MaxResults = 5;
                var searchListResponse = (await listRequest.ExecuteAsync()).Items;
                if (searchListResponse.Count == 0) // The search returned no result
                {
                    throw new CommandFailed($"There is no video with these search terms.");
                }

                var correctVideos = searchListResponse.Where(x => x.Id.Kind == "youtube#video"); // We remove things that aren't videos from the search (like playlists)
                if (correctVideos.Count() == 0)
                {
                    throw new CommandFailed($"There is no video with these search terms.");
                }

                // For each video, we contact the statistics endpoint
                VideosResource.ListRequest videoRequest = StaticObjects.YouTube.Videos.List("snippet,statistics,contentDetails");
                videoRequest.Id = string.Join(",", correctVideos.Select(x => x.Id.VideoId));
                var   videoResponse = (await videoRequest.ExecuteAsync()).Items;
                ulong likes         = ulong.MinValue;
                // Sometimes the first result isn't the one we want, so compare the differents results and take the one with the best like/dislike ratio
                bool isExactSearch = false;
                var  lowerSearch   = search.ToLowerInvariant();
                foreach (Video res in videoResponse)
                {
                    ulong likeCount = ulong.MinValue;
                    if (res.Statistics.LikeCount != null)
                    {
                        likeCount = res.Statistics.LikeCount.Value;
                    }
                    if (res.Statistics.DislikeCount != null)
                    {
                        likeCount -= res.Statistics.DislikeCount.Value;
                    }
                    if (likeCount > likes || result == null)
                    {
                        // We get the best ratio if possible, but if the title match then it's more important
                        var lowerTitle = res.Snippet.Title.ToLowerInvariant();
                        if (isExactSearch && !lowerTitle.Contains(lowerSearch))
                        {
                            continue;
                        }
                        likes  = likeCount;
                        result = res;
                        if (!isExactSearch && lowerTitle.Contains(lowerSearch))
                        {
                            isExactSearch = true;
                        }
                    }
                }
            }
            return(result);
        }