示例#1
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);
        }
示例#2
0
        public string GetVideoUrl(string artist, string title)
        {
            string apiKey = ConfigurationManager.AppSettings["youtubeKey"];

            if (String.IsNullOrEmpty(apiKey))
            {
                throw new InvalidOperationException("Youtube Key is missing for app configuration!");
            }

            YouTubeService youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey          = apiKey,
                ApplicationName = GetType().ToString()
            });

            var searchListRequest = youtubeService.Search.List("id");

            searchListRequest.Q               = artist + title;
            searchListRequest.Type            = "video";
            searchListRequest.Order           = SearchResource.ListRequest.OrderEnum.Relevance;
            searchListRequest.VideoEmbeddable = SearchResource.ListRequest.VideoEmbeddableEnum.True__;
            searchListRequest.VideoSyndicated = SearchResource.ListRequest.VideoSyndicatedEnum.True__;
            searchListRequest.Alt             = YouTubeBaseServiceRequest <Google.Apis.YouTube.v3.Data.SearchListResponse> .AltEnum.Json;
            searchListRequest.VideoCategoryId = "10";
            searchListRequest.MaxResults      = 1;
            searchListRequest.VideoDefinition = SearchResource.ListRequest.VideoDefinitionEnum.Any;

            SearchListResponse searchListResponse = searchListRequest.ExecuteAsync().Result;

            if (searchListResponse.Items.Count > 0)
            {
                return(searchListResponse.Items[0].Id.VideoId);
            }
            return(String.Empty);
        }
示例#3
0
        /**
         * Request Youtube Api for movie trailer
         * **/
        private string getTrailer(dynamic original_title, dynamic release_date)
        {
            var search = "";

            // Creation of string to search for trailer on Youtube
            try
            {
                search = original_title + " official trailer " + Convert.ToDateTime(release_date).Year;
            }
            catch (FormatException)
            {
                search = original_title + " official trailer ";
            }

            YouTubeService youtube = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey = _movieConfig.YtApiKey
            });

            SearchResource.ListRequest listRequest = youtube.Search.List("snippet");
            listRequest.Q          = search; // search term
            listRequest.Type       = "video";
            listRequest.MaxResults = 1;      // I decided to keep the first result as the chosen one to associate with the movie

            SearchListResponse searchResponse = listRequest.Execute();

            // Handle possible occurrence of no results
            if (searchResponse.Items.Count == 0)
            {
                return("");
            }
            return(searchResponse.Items[0].Id.VideoId);
        }
示例#4
0
        public List <SearchResultModified> BuscarLista(string palabra)
        {
            var ServicioYouTube = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey          = "AIzaSyCENuuzGXhwKTvQVsuG0HyhEYW9DWuXGPg",
                ApplicationName = this.GetType().ToString()
            });

            var BuscarListaSolicitud = ServicioYouTube.Search.List("snippet");

            BuscarListaSolicitud.Q          = palabra; //Buscador
            BuscarListaSolicitud.MaxResults = 5;

            SearchListResponse BuscarListaRespuesta = BuscarListaSolicitud.Execute();
            IList <Google.Apis.YouTube.v3.Data.SearchResult> searchResults = BuscarListaRespuesta.Items;
            List <SearchResultModified> searchResultModifieds = new List <SearchResultModified>();

            foreach (var item in searchResults)
            {
                SearchResultModified searchResultC = new SearchResultModified();
                searchResultC.VideoId  = item.Id.VideoId;
                searchResultC.ImageUrl = item.Snippet.Thumbnails.Default__.Url;
                searchResultC.Title    = item.Snippet.Title;
                searchResultC.Title    = item.Snippet.ChannelTitle;
                searchResultC.Expo     = "Hello";

                searchResultModifieds.Add(searchResultC);
            }
            //return searchResults.ToList();
            return(searchResultModifieds);
        }
示例#5
0
        public List <YouTubeChannel> SearchChannels(InputArgument inputArg)
        {
            // Searching channel with matching query [Cost: 100qc]
            var searchListRequest = YouTubeServiceProvider().Search.List("snippet");

            searchListRequest.Type       = "channel";
            searchListRequest.Q          = inputArg.SearchTerm;
            searchListRequest.MaxResults = 3;

            SearchListResponse searchListResponse = searchListRequest.Execute();

            var channels = new List <YouTubeChannel>();

            for (int i = 0; i < searchListResponse.Items.Count; i++)
            {
                channels.Add(new YouTubeChannel
                {
                    Id            = searchListResponse.Items[i].Id.ChannelId,
                    ChannelNumber = i + 1,
                    Title         = searchListResponse.Items[i].Snippet.Title
                });
            }

            return(channels);
        }
示例#6
0
        public String generateRandomVideos(bool onlyOne)
        {
            if (onlyOne)
            {
                log.Debug("Cache is empty; generating video...");
            }
            else
            {
                log.Debug(String.Format("Cache currently contains {0} items; refilling to {1}...", randomCache.Count, PluginSettings.Default.YoutubeCacheSize));
            }
            while (randomCache.Count < PluginSettings.Default.YoutubeCacheSize)
            {
                try {
                    log.Debug("Generating a random video...");
                    VideosResource.ListRequest request = youtubeService.Videos.List("snippet");
                    request.Fields     = "items(id,snippet/title)";
                    request.Chart      = VideosResource.ListRequest.ChartEnum.MostPopular;
                    request.MaxResults = 40;

                    log.Debug("Fetching list of most popular videos...");

                    VideoListResponse response = request.Execute();
                    int count = response.Items.Count;

                    Video  first = response.Items[random.Next(count)];
                    String id    = first.Id;
                    log.Debug("Picked \"" + first.Snippet.Title + "\" as my starting point.");
                    for (int i = 0; i < PluginSettings.Default.YoutubeIterations; i++)
                    {
                        SearchResource.ListRequest relatedRequest = youtubeService.Search.List("snippet");
                        relatedRequest.Fields           = "items(id,snippet/title)";
                        relatedRequest.Type             = "video";
                        relatedRequest.RelatedToVideoId = id;
                        relatedRequest.SafeSearch       = SearchResource.ListRequest.SafeSearchEnum.None;
                        relatedRequest.MaxResults       = 20;

                        SearchListResponse relatedResponse = relatedRequest.Execute();
                        count = relatedResponse.Items.Count;
                        SearchResult result = relatedResponse.Items[random.Next(count)];
                        id = result.Id.VideoId;
                        log.Debug("Next link: " + result.Snippet.Title);
                    }

                    log.Debug("Found my random video!");
                    String url = "https://youtu.be/" + id;

                    if (onlyOne)
                    {
                        return(url);
                    }

                    log.Debug("Adding to cache...");
                    randomCache.Enqueue(url);
                } catch (Exception e) {
                    log.Error("Failed in generating a video.", e);
                }
            }

            return(null);
        }
示例#7
0
        public List <Videos> ObtenerVideos(string name)
        {
            List <Videos>  videos  = new List <Videos>();
            YouTubeService youtube = new YouTubeService(new BaseClientService.Initializer
            {
                ApiKey          = "AIzaSyBhqe3OaIZT7RusiHlV_kBL3z2CExG3Vb4",
                ApplicationName = "Rockola-264715"
            });

            SearchResource.ListRequest searchListRequest = youtube.Search.List("snippet");
            searchListRequest.Q          = name;
            searchListRequest.MaxResults = 40;
            SearchListResponse searchListResponse = searchListRequest.Execute();

            foreach (var item in searchListResponse.Items)
            {
                if (item.Id.Kind == "youtube#video")
                {
                    videos.Add(new Videos
                    {
                        ID        = item.Id.VideoId,
                        Nombre    = item.Snippet.Title,
                        Url       = "https://www.youtube.com/embed/" + item.Id.VideoId,
                        Thumbnail = "http://img.youtube.com/vi/" + item.Id.VideoId + "/hqdefault.jpg"
                    });
                }
            }
            return(videos);
        }
示例#8
0
        public List <Videos> GetListYoutube(string keyword)
        {
            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey          = "AIzaSyAV7dZdpjsqH9K2IkJ0tlqHWklDay0qMW4",
                ApplicationName = this.GetType().ToString()
            });

            var searchListRequest = youtubeService.Search.List("snippet");

            searchListRequest.Q          = keyword; // Replace with your search term.
            searchListRequest.MaxResults = 10;

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

            IList <SearchResult> searchResults = searchListResponse.Items;
            List <Videos>        listvideos    = new List <Videos>();

            foreach (var item in searchResults)
            {
                listvideos.Add(new Videos {
                    ID = item.Id.VideoId, tittle = item.Snippet.Title
                });
            }
            return(listvideos);
        }
示例#9
0
        public async Task <List <MyVideo> > Run(string apiKey, string searchTerm, int maxResults)
        {
            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey          = apiKey,
                ApplicationName = this.GetType().ToString()
            });

            var searchListRequest = youtubeService.Search.List("snippet");

            searchListRequest.Q          = searchTerm;
            searchListRequest.MaxResults = maxResults;

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

            var videos = new List <MyVideo>();

            //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":
                    var     stats   = GetVideoStats(youtubeService, searchResult.Id.VideoId);
                    MyVideo myVideo = new MyVideo
                    {
                        Id             = searchResult.Id.VideoId,
                        ChannelTitle   = searchResult.Snippet.ChannelTitle,
                        Description    = searchResult.Snippet.Description,
                        PublishedAtRaw = searchResult.Snippet.PublishedAtRaw,
                        PublishedAt    = searchResult.Snippet.PublishedAt,
                        Title          = searchResult.Snippet.Title,

                        CommentCount  = stats.CommentCount,
                        DislikeCount  = stats.DislikeCount,
                        FavoriteCount = stats.FavoriteCount,
                        LikeCount     = stats.LikeCount,
                        ViewCount     = stats.ViewCount
                    };

                    videos.Add(myVideo);
                    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;
                }
            }

            return(videos.OrderByDescending(vd => vd.ViewCount).ToList());
        }
示例#10
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;
            }));
        }
示例#11
0
        public void SearchForVideosByTitle(string searchValue, int maxResultCount)
        {
            SearchResource.ListRequest searchListRequest = client.Search.List("snippet");
            searchListRequest.Q          = searchValue;
            searchListRequest.MaxResults = maxResultCount;

            SearchListResponse searchListResponse = searchListRequest.Execute();

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

            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(String.Format("Videos:\n{0}\n", string.Join("\n", videos)));
            Console.WriteLine(String.Format("Channels:\n{0}\n", string.Join("\n", channels)));
            Console.WriteLine(String.Format("Playlists:\n{0}\n", string.Join("\n", playlists)));
        }
示例#12
0
        public List <SearchResultCustomized> SearchYoutubeVideo(string keyword)
        {
            //Construyendo el servicio de Youtube
            YouTubeService youtube = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey = "AIzaSyA-HQVqE6Smy-oBBk9RPrYx7jL1VwYMXTI"
            });

            SearchResource.ListRequest listRequest = youtube.Search.List("snippet");
            listRequest.Q          = keyword;
            listRequest.MaxResults = 6;


            SearchListResponse            searchResponse          = listRequest.Execute();
            IList <SearchResult>          searchResults           = searchResponse.Items;
            List <SearchResultCustomized> searchResultCustomizeds = new List <SearchResultCustomized>();

            foreach (var item in searchResults.ToList())
            {
                SearchResultCustomized searchResultCustomized = new SearchResultCustomized();
                searchResultCustomized.VideoId  = item.Id.VideoId;
                searchResultCustomized.Title    = item.Snippet.Title;
                searchResultCustomized.ImageURL = item.Snippet.Thumbnails.Default__.Url;
                searchResultCustomizeds.Add(searchResultCustomized);
            }
            return(searchResultCustomizeds);
        }
示例#13
0
        /// <summary>
        ///     Gets a list of songs of size <c>int SongCount</c>
        /// </summary>
        /// <param name="song"></param>
        public static async Task <int> QueryVideoListAsync(string song)
        {
            //Catches timeouts
            try
            {
                var service   = GoogleServices.YoutubeService;
                var musicList = service.Search.List("snippet");
                musicList.Q          = song; // Replace with your search term.
                musicList.MaxResults = SongCount;
                musicList.Type       = "video";

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

                //Search for topic songs
                musicList.Q          = song + " topic"; // Replace with your search term.
                musicList.MaxResults = 1;
                musicList.Type       = "video";
                var topicResponse = await musicList.ExecuteAsync();

                SongSearchListResponse.Items.Insert(0, topicResponse.Items[0]);
            }
            catch
            {
                Console.WriteLine("Timed out");
            }

            //TopicSearchListResponse = await musicList.ExecuteAsync();
            return(1);
        }
示例#14
0
        public override List <VideoHosting> Parse()

        {
            var youtubeService = new YouTubeService(new BaseClientService.Initializer
            {
                ApplicationName = "Youtube parser",
                ApiKey          = "AIzaSyCtrxWvxLLF33phNIi6TTWjekgG9NiLpsw",
            });

            int maxResults = 20;

            SearchResource.ListRequest searchListByKeywordRequest = youtubeService.Search.List("snippet");
            searchListByKeywordRequest.MaxResults        = maxResults;
            searchListByKeywordRequest.Q                 = GetUrlLink();
            searchListByKeywordRequest.Type              = "video";
            searchListByKeywordRequest.RelevanceLanguage = "ru";

            SearchListResponse response = searchListByKeywordRequest.Execute();

            var result = response.Items.Select(t =>
                                               new VideoHosting
            {
                NameVideo   = t.Snippet.Title,
                NameHosting = HostNames.Youtube,
                Time        = DateTime.Now
            }).ToList();

            return(result);
        }
示例#15
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());
        }
示例#16
0
        public VideosEntry SearchVideos(string query)
        {
            SearchResource.ListRequest listRequest = _service.Search.List("snippet");
            listRequest.Q          = query;
            listRequest.MaxResults = 5;
            listRequest.Type       = "video";

            SearchListResponse resp = listRequest.Execute();

            List <VideoInfo> pool = new List <VideoInfo>();

            foreach (var result in resp.Items)
            {
                pool.Add(new VideoInfo {
                    id        = result.Id.VideoId,
                    title     = result.Snippet.Title,
                    thumbnail = result.Snippet.Thumbnails.Default__.Url
                });
            }
            VideosEntry videos = new VideosEntry {
                selected = pool[0],
                pool     = pool
            };

            return(videos);
        }
示例#17
0
        private void ParseYouTubeSearchResults(YouTubeSearchRequest searchRequest, SearchListResponse searchResults)
        //================================================================================================================
        // Parse the given YouTube search results into a search results list
        //
        // Parameters
        //      searchRequest: YouTube search request data
        //      searchResults: YouTube search results data
        //
        // Outputs
        //      The SearchResults list in the searchRequest object is populated
        //================================================================================================================
        {
            int resultCount = 0;

            foreach (SearchResult searchResult in searchResults.Items)
            {
                // Bump the result count
                resultCount++;

                // Create and initialize a new YouTube search result
                YouTubeSearchResult item = new YouTubeSearchResult
                {
                    SessionKey     = searchRequest.SessionKey,
                    ResultNo       = resultCount,
                    YouTubeVideoId = searchResult.Id.VideoId,
                    Title          = searchResult.Snippet.Title,
                    Description    = searchResult.Snippet.Description,
                    ThumbnailURL   = searchResult.Snippet.Thumbnails.Default__.Url,
                    YouTubeURL     = string.Format(YOU_TUBE_LINK, searchResult.Id.VideoId)
                };

                // Add this result to the collection
                searchRequest.SearchResults.Add(item);
            }
        }
示例#18
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);
        }
示例#19
0
        public List <YouTubeVideo> SearchVideos(InputArgument inputArg)
        {
            // Searching video with matching query [Cost: 100qc]
            var searchListRequest = YouTubeServiceProvider().Search.List("snippet");

            searchListRequest.Type       = "video";
            searchListRequest.Q          = inputArg.SearchTerm;
            searchListRequest.MaxResults = inputArg.QueryLimit;
            searchListRequest.Order      = SearchResource.ListRequest.OrderEnum.Date;

            if (inputArg.FilterForToday)
            {
                searchListRequest.PublishedAfter = DateTime.Now.AddDays(-1);
            }

            SearchListResponse searchListResponse = searchListRequest.Execute();

            // Fetching duration of these videos [Cost: 1qc]
            var videoListRequest = YouTubeServiceProvider().Videos.List("contentDetails");

            videoListRequest.Id = string.Join(",", searchListResponse.Items.Select(x => x.Id.VideoId));
            var videoListResponse = videoListRequest.Execute();

            var videos = searchListResponse.Items.Zip(videoListResponse.Items, (x, y) => new YouTubeVideo
            {
                Id           = x.Id.VideoId,
                Title        = x.Snippet.Title,
                ChannelTitle = x.Snippet.ChannelTitle,
                Duration     = XmlConvert.ToTimeSpan(y.ContentDetails.Duration),
                PublishedAt  = DateTime.Parse(x.Snippet.PublishedAt)
            }).ToList();

            return(videos);
        }
示例#20
0
        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);
                }
            }
        }
        /// <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);
            }
        }
示例#22
0
        public async Task <IEnumerable <Models.Video> > ListVideosBySearchAsync(DateTime fromDate)
        {
            List <Models.Video> videos = new List <Models.Video>();

            while (_credential == null || _youtubeService == null)
            {
                Thread.Sleep(1000);
            }

            _logger.LogTrace(JsonSerializer.Serialize(_settings));


            foreach (var channel in _settings.YoutubeChannels)
            {
                var request = _youtubeService.Search.List("snippet");
                request.ChannelId      = channel;
                request.Order          = SearchResource.ListRequest.OrderEnum.Date;
                request.PublishedAfter = fromDate;

                SearchListResponse response = null;
                try
                {
                    _logger.LogTrace("Analyze channel {channel}", channel);
                    response = await request.ExecuteAsync();
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.Message);

                    if (ex.Message.Contains("Request had insufficient authentication scope"))
                    {
                        await _credential.RevokeTokenAsync(CancellationToken.None);
                        await Init();

                        response = await request.ExecuteAsync();
                    }
                }

                if (response == null)
                {
                    continue;
                }

                videos.AddRange(response.Items
                                .Where(s => !string.IsNullOrEmpty(s.Id.VideoId))
                                .Select(video => new Models.Video
                {
                    ListId    = video.Id.PlaylistId,
                    Title     = video.Snippet.Title,
                    VideoId   = video.Id.VideoId,
                    ChannelId = video.Snippet.ChannelId
                }));
            }


            return(videos);
        }
示例#23
0
        public async void Search(string basedOnVideoId, string query = null)
        {
            YouTubeService service;

            service = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = App._CRED, ApplicationName = "EwTewb"
            });


            var pls = service.Search.List("snippet");

            pls.Type = "video"; pls.MaxResults = 10;
            if (basedOnVideoId != null)
            {
                pls.RelatedToVideoId = basedOnVideoId;
            }
            if (query != null)
            {
                pls.Q = query;
            }

            SearchListResponse plRes = null;

            try { plRes = await pls.ExecuteAsync(); }
            catch (Exception ex)
            { }


            VideoListItems = new ObservableCollection <VideoUIItem>();

            foreach (var res in plRes.Items)
            {
                if (res.Id.Kind != "youtube#video")
                {
                    continue;
                }

                var evid = new DBVideo
                {
                    VideoId      = res.Id.VideoId,
                    ChannelId    = res.Snippet.ChannelId,
                    ChannelTitle = res.Snippet.ChannelTitle,
                    Description  = res.Snippet.Description,
                    Date         = res.Snippet.PublishedAt ?? default(DateTime),
                    Thumb        = res.Snippet.Thumbnails == null ? "" : (res.Snippet.Thumbnails.Medium?.Url ?? res.Snippet.Thumbnails.Default__?.Url ?? res.Snippet.Thumbnails.Standard?.Url),
                    Title        = res.Snippet.Title,
                };

                var uivid = new VideoUIItem(this, evid)
                {
                };

                VideoListItems.Add(uivid);
            }
        }
示例#24
0
        /// <summary>
        /// Retrieves Videos Feeds from YouTube using API KEY.
        /// </summary>
        /// <returns></returns>
        public List <SearchResult> RetriveVideosUsingAPIKey(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(PUBLISHED_FROM_DATE))
            {
                listRequest.PublishedAfter = DateTime.ParseExact(PUBLISHED_FROM_DATE, "yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture);
            }
            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>();

            results.AddRange(searchResponse.Items);

            string nextPageToken = searchResponse.NextPageToken;

            int amountWithoutChannelTitle = 0;
            int amountWithoutChannelId    = 0;

            while (searchResponse.Items.Count == MAX_RESULTS_PER_PAGE && !string.IsNullOrEmpty(nextPageToken))
            {
                foreach (var item in searchResponse.Items)
                {
                    if (string.IsNullOrEmpty(item.Snippet.ChannelTitle))
                    {
                        amountWithoutChannelTitle++;
                    }
                    if (string.IsNullOrEmpty(item.Snippet.ChannelId))
                    {
                        amountWithoutChannelId++;
                    }
                }
                listRequest.PageToken = nextPageToken;
                searchResponse        = listRequest.Execute();
                results.AddRange(searchResponse.Items);
                nextPageToken = searchResponse.NextPageToken;
            }

            return(results);
        }
示例#25
0
        private SearchListResponse GetSearch(string query)
        {
            SearchResource.ListRequest listRequest = youTubeService.Search.List("snippet");
            listRequest.Q          = query;
            listRequest.MaxResults = 1;

            SearchListResponse search = listRequest.Execute();

            return(search);
        }
示例#26
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)));
        }
示例#27
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);
        }
示例#28
0
        /// <summary>
        /// Retrieves Videos Feeds from YouTube using OAuth 2.0.
        /// </summary>
        /// <returns></returns>
        public List <SearchResult> RetriveVideosUsingOAuth(string searchTerm)
        {
            String serviceAccountEmail = OAUTH_SERVICE_ACCOUNT_EMAIL;

            var certificate = new X509Certificate2(OAUTH_LOCAL_KEY_FILE, OAUTH_PASSWORD, X509KeyStorageFlags.Exportable);

            ServiceAccountCredential credential = new ServiceAccountCredential(
                new ServiceAccountCredential.Initializer(serviceAccountEmail)
            {
                Scopes = new[] { YouTubeService.Scope.YoutubeReadonly }
            }.FromCertificate(certificate));

            // Create the service.
            var service = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "YouTube API Sample",
            });

            SearchResource.ListRequest listRequest = service.Search.List("snippet");
            listRequest.Fields     = "items(id,snippet(title, description, publishedAt, thumbnails, channelId, channelTitle))";
            listRequest.Type       = ResourceTypes.Video;
            listRequest.MaxResults = MAX_RESULTS_PER_PAGE;
            if (!string.IsNullOrEmpty(PUBLISHED_FROM_DATE))
            {
                listRequest.PublishedAfter = DateTime.ParseExact(PUBLISHED_FROM_DATE, "yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture);
            }
            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>();

            results.AddRange(searchResponse.Items);

            string nextPageToken = searchResponse.NextPageToken;

            while (searchResponse.Items.Count == MAX_RESULTS_PER_PAGE)
            {
                listRequest.PageToken = nextPageToken;
                searchResponse        = listRequest.Execute();
                results.AddRange(searchResponse.Items);
                nextPageToken = searchResponse.NextPageToken;
            }

            return(results);
        }
示例#29
0
        private static async Task RunYoutubeSearch()
        {
            try
            {
                Console.Write("Searching YouTube for new videos... ");
                var youtube = new YouTubeService(new BaseClientService.Initializer()
                {
                    ApplicationName = ConfigurationManager.AppSettings["YoutubeApiAppName"],
                    ApiKey          = ConfigurationManager.AppSettings["YoutubeApiToken"]
                });

                SearchResource.ListRequest listRequest = youtube.Search.List("snippet");
                listRequest.ChannelId  = ConfigurationManager.AppSettings["YoutubeChannelId"];
                listRequest.MaxResults = 5;
                listRequest.Order      = SearchResource.ListRequest.OrderEnum.Date;
                listRequest.Type       = "video";
                SearchListResponse resp = listRequest.Execute();

                DateTime mostRecent = DateTime.MinValue.ToUniversalTime();

                var youtubeRootDir         = Path.Combine(Environment.CurrentDirectory, string.Format("data/youtube/"));
                var channelSubscribersPath = Path.Combine(youtubeRootDir,
                                                          string.Format("{0}.txt", listRequest.ChannelId));

                CreateIfMissing(Path.Combine(Environment.CurrentDirectory, string.Format("data/youtube/")));

                if (File.Exists(channelSubscribersPath))
                {
                    var  dateStr = File.ReadAllText(channelSubscribersPath);
                    long ticks   = long.Parse(dateStr);
                    mostRecent = DateTime.SpecifyKind(new DateTime(ticks), DateTimeKind.Utc);
                }

                Console.WriteLine("Done.");

                var newItems =
                    resp.Items.Where(
                        obj => obj.Snippet.PublishedAt.HasValue && obj.Snippet.PublishedAt.Value > mostRecent)
                    .ToList();

                if (newItems.Any())
                {
                    Console.WriteLine("Found New Videos! Notifying clients.");
                    var latestEp = newItems.OrderByDescending(obj => obj.Snippet.PublishedAt.Value)
                                   .FirstOrDefault();
                    File.WriteAllText(channelSubscribersPath, latestEp.Snippet.PublishedAt.Value.Ticks.ToString());
                    await NotifyChats(newItems);
                }
            }
            catch (Exception ex)
            {
                // No nothing, just don't crash the app if service is down, or some unknown error.
                Console.WriteLine(ex.ToString());
            }
        }
示例#30
0
 /// <summary>
 ///     Fills the YouTube Results into SongModel Collection
 /// </summary>
 /// <param name="searchResponse"></param>
 /// <returns> Returns an Collection of SearchResults </returns>
 private static List <ItemModel> AddResults(SearchListResponse searchResponse)
 {
     return(searchResponse?.Items.Select(result => new ItemModel {
         SongName = result.Snippet.Title.Length >= 50
             ? result.Snippet.Title.Remove(50, result.Snippet.Title.Length - 50) + "..."
             : result.Snippet.Title,
         ArtistName = result.Snippet.ChannelTitle,
         CoverImage = result.Snippet.Thumbnails.Medium.Url,
         YouTubeUri = string.IsNullOrEmpty(result.Id.VideoId) ? string.Empty : YouTubeUri + result.Id.VideoId
     }).ToList());
 }
示例#31
0
        private Resultado GenerarResultado(SearchListResponse resp)
        {
            var resultado = new Resultado();
            var listvRequest = _youtube.Videos.List("contentDetails");
            listvRequest.Id = string.Join(",", resp.Items.Select(x => x.Id.VideoId));
            //listvRequest.MaxResults = 20;
            var resp2 = listvRequest.Execute();

            foreach (var result in resp.Items)
            {
                var content = resp2.Items.FirstOrDefault(x => x.Id == result.Id.VideoId);
                resultado.Temas.Add(item: new Tema
                {
                    Nombre = result.Snippet.Title.Truncate(90),
                    //Autor = result.Snippet.Description.Truncate(60),
                    Id = result.Id.VideoId,
                    Duracion = content != null ? XmlConvert.ToTimeSpan(content.ContentDetails.Duration) : new TimeSpan()
                });
            }
            resultado.Siguiente = resp.NextPageToken;
            resultado.Anterior = resp.PrevPageToken;
            return resultado;
        }
 public YuotubeQueryResponse(SearchListResponse listResponse)
 {
     listResponse.Items.ToList().ForEach(item => videos.Add(new SearchResult(item.Id.VideoId, item.Snippet.Title,item.Snippet.Thumbnails.Default.Url,item.Snippet.Description)));
 }
示例#33
0
        protected void Search(string SearchTerm, string PageToken)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new VoidDelegate2String(Search), new string[] { SearchTerm, PageToken });
            }
            else
            {
                // Check that no unnecessary searches are made
                if (SearchBox.Text != CurrentSearchTerm)
                {
                    CurrentSearchTerm = SearchBox.Text;

                    #region Request
                    // Build the request (videos and playlists)
                    SearchResource.ListRequest Request = Globals.Youtube.Search.List("snippet");
                    Request.Q = SearchTerm;
                    Request.Key = Globals.Key;
                    Request.Order = SearchResource.ListRequest.OrderEnum.Relevance;
                    if (!string.IsNullOrWhiteSpace(PageToken))
                    {
                        Request.PageToken = PageToken;
                    }
                    Request.MaxResults = (int)SearchResults.Value;
                    Request.PrettyPrint = true;
                    Request.Type = "video,playlist";
                    #endregion

                    #region Response
                    // Acquire response
                    Response = Request.Execute();
                    #endregion

                    #region Commands
                    // Remove old commands
                    string CommandName = "SearchResults";
                    for (int x = 0; x < CommandReceiver.Commands.Count; x++)
                    {
                        try
                        {
                            if (CommandReceiver.Commands[x].Name.Substring(0, CommandName.Length) == CommandName)
                            {
                                // SearchResults command - remove it
                                CommandReceiver.UnloadCommand(x);
                            }
                        }
                        catch
                        {
                            // Ignore
                        }
                    }
                    // Add new commands (from 0 to the number of results on the page)
                    for (int x = 0; x <= SearchResults.Value; x++)
                    {
                        int X = x;
                        List<string> SearchResultsCommands = new List<string>();
                        SearchResultsCommands.Add((X + 1) + (X == 0 ? " result" : " results"));
                        SearchResultsCommands.Add("Set " + (X + 1) + (X == 0 ? " result" : " results"));

                        this.CommandReceiver.AddCommand(new Command("SearchResults" + (X + 1), () =>
                        {
                            SearchResultsQuantity = X;
                            SetSearchResults();
                        }, SearchResultsCommands));
                    }
                    #endregion

                    #region Cleanup
                    // Remove all current videos
                    for (int x = 0; x < Videos.Items.Count; x++)
                    {
                        // Remove commands with names in the pattern "PlayX" or "SelectX"
                        CommandReceiver.UnloadCommand("Play" + (x + 1));
                        CommandReceiver.UnloadCommand("Select" + (x + 1));
                        Videos.Items.RemoveAt(x);
                    }
                    #endregion

                    #region New Videos
                    // Process response
                    for (int x = 0; x < Response.Items.Count; x++)
                    {
                        VideoListViewItem NewItem = new VideoListViewItem();

                        #region Attribute transfer
                        // Store the description
                        NewItem.Description = Response.Items[x].Snippet.Description;

                        // Store the number
                        NewItem.Text = Convert.ToString(x + 1);

                        // Store the thumbnail url
                        NewItem.ThumbnailUrl = Response.Items[x].Snippet.Thumbnails.Default.Url;
                        #endregion

                        #region Commands
                        // Add a command to select this video
                        int X = x;
                        CommandReceiver.AddCommand(new Command("Select" + (x + 1), new Action(() =>
                        {
                            SelectVideo(X);
                        }), new List<string>() { "Select " + (x + 1), "Choose " + (x + 1), "Click " + (x + 1) }));

                        // Add a command to play this video
                        CommandReceiver.AddCommand(new Command("Play" + (x + 1), () =>
                        {
                            Play(X);
                        }, new List<string>() { "Play " + (x + 1), "Run " + (x + 1), "Watch " + (x + 1) }));

                        #endregion

                        switch (Response.Items[x].Id.Kind)
                        {
                            case "youtube#video":
                                NewItem.VideoUrl = Response.Items[x].Id.VideoId;
                                NewItem.SubItems.Add(Response.Items[x].Snippet.Title);
                                NewItem.SubItems.Add("Video");
                                break;

                            case "youtube#playlist":
                                NewItem.PlaylistUrl = Response.Items[x].Id.PlaylistId;
                                NewItem.SubItems.Add(Response.Items[x].Snippet.Title);
                                NewItem.SubItems.Add("Playlist");
                                break;
                        }

                        NewItem.SubItems.Add(Response.Items[x].Snippet.ChannelTitle);

                        Videos.Items.Add(NewItem);
                    }
                    #endregion
                }
            }
        }