Example #1
0
        public async Task <ActionResult <string> > LocalizeVideo([Required, FromBody] AppVideoLocalizeRequest body)
        {
            string localizationCountHash = Guid.NewGuid().ToString();

            intStore[localizationCountHash] = 0;

            string[]       videos = body.MineChannelVideoUploadCollection;
            Task <Video>[] tasks  = new Task <Video> [videos.Length];

            string         userId  = User.GetLocalAuthorityNameIdentifier();
            YouTubeService service = await youtubeServiceAccessor.InitializeServiceAsync(userId);

            VideosResource.ListRequest request = service.Videos.List(VIDEO_LOCALIZE_PART);
            request.Id = string.Join(',', videos);

            int i = 0;

            do
            {
                VideoListResponse response = await request.ExecuteAsync();

                IList <Video> items = response.Items;

                foreach (Video item in items)
                {
                    tasks[i++] = LocalizeVideoTask(item, body, localizationCountHash, service); // All other tasks begin their life cycle in a hot state.
                }

                request.PageToken = response.NextPageToken;
            } while (request.PageToken != null);

            _ = Task.WhenAll(tasks); // errors will not be caught because no await

            return(new ActionResult <string>(localizationCountHash));
        }
        /// <summary>
        /// Gets the play list songs internal asynchronous.
        /// </summary>
        /// <param name="userEmail">The user email.</param>
        /// <param name="playListId">The play list identifier.</param>
        private async Task GetPlayListSongsInternalAsync(string userEmail, string playListId, List <string> playListSongs)
        {
            var youtubeService = await GetYouTubeService(userEmail);

            var channelsListRequest = youtubeService.Channels.List("contentDetails");

            channelsListRequest.Mine = true;
            var nextPageToken = "";

            while (nextPageToken != null)
            {
                PlaylistItemsResource.ListRequest listRequest = youtubeService.PlaylistItems.List("contentDetails");
                listRequest.MaxResults = 50;
                listRequest.PlaylistId = playListId;
                listRequest.PageToken  = nextPageToken;
                var response = await listRequest.ExecuteAsync();

                if (playListSongs == null)
                {
                    playListSongs = new List <string>();
                }
                foreach (var playlistItem in response.Items)
                {
                    VideosResource.ListRequest videoR = youtubeService.Videos.List("snippet");
                    videoR.Id = playlistItem.ContentDetails.VideoId;
                    var responseV = await videoR.ExecuteAsync();

                    playListSongs.Add(responseV.Items[0].Snippet.Title);
                }
                nextPageToken = response.NextPageToken;
            }
        }
Example #3
0
        public static async Task <VideoListResponse> ExecuteAllAsync(this VideosResource.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);
        }
        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);
        }
Example #5
0
 VideosResource.ListRequest CreateVideoResouceListResouceGetYVideoFromId(string id)
 {
     VideosResource.ListRequest request = CreateClient().Videos.List("snippet,statistics");
     request.Id         = id;
     request.MaxResults = 1;
     return(request);
 }
        /// <summary>
        /// Gets the play list songs internal asynchronous.
        /// </summary>
        /// <param name="userEmail">The user email.</param>
        /// <param name="playListId">The play list identifier.</param>
        private async Task GetPlayListSongsInternalAsync(string userEmail, string playListId, List <IYouTubeSong> playListSongs)
        {
            var youtubeService = await this.GetYouTubeService(userEmail);

            var channelsListRequest = youtubeService.Channels.List("contentDetails");

            channelsListRequest.Mine = true;
            var nextPageToken = "";

            while (nextPageToken != null)
            {
                PlaylistItemsResource.ListRequest listRequest = youtubeService.PlaylistItems.List("contentDetails");
                listRequest.MaxResults = 50;
                listRequest.PlaylistId = playListId;
                listRequest.PageToken  = nextPageToken;
                var response = await listRequest.ExecuteAsync();

                if (playListSongs == null)
                {
                    playListSongs = new List <IYouTubeSong>();
                }
                foreach (var playlistItem in response.Items)
                {
                    VideosResource.ListRequest videoR = youtubeService.Videos.List("snippet");
                    videoR.Id = playlistItem.ContentDetails.VideoId;
                    var responseV = await videoR.ExecuteAsync();

                    KeyValuePair <string, string> parsedSong = SongTitleParser.ParseTitle(responseV.Items[0].Snippet.Title);
                    IYouTubeSong currentSong = new YouTubeSong(parsedSong.Key, parsedSong.Value, responseV.Items[0].Id, playlistItem.Id, null);
                    playListSongs.Add(currentSong);
                    Debug.WriteLine(playlistItem.Snippet.Title);
                }
                nextPageToken = response.NextPageToken;
            }
        }
        internal async Task <string> GetVideoId(string videoId)
        {
            try
            {
                var uri       = new Uri(videoId);
                var queryDict = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(uri.Query);
                videoId = queryDict["v"];
            }
            catch
            {
            }

            YouTubeService t = GetYoutubeService();

            VideosResource.ListRequest request = t.Videos.List("id");
            request.Id = videoId;
            VideoListResponse response = await request.ExecuteAsync();

            if (response.Items.Count > 0)
            {
                return(videoId);
            }
            else
            {
                return(null);
            }
        }
Example #8
0
        /// <summary>
        /// Gets the videos for the specified IDs
        /// </summary>
        /// <param name="ids">The IDs of the videos</param>
        /// <param name="isOwned">Indicates whether the video is owned by the currently authenticated user and includes additional details if so</param>
        /// <returns>The video information</returns>
        public async Task <IEnumerable <Video> > GetVideosByID(IEnumerable <string> ids, bool isOwned = false)
        {
            Validator.ValidateList(ids, "ids");
            return(await this.YouTubeServiceWrapper(async() =>
            {
                List <Video> results = new List <Video>();
                List <string> searchIDs = new List <string>(ids);
                string pageToken = null;
                do
                {
                    int searchAmount = Math.Min(searchIDs.Count, 50);

                    string parts = "snippet,contentDetails,statistics,liveStreamingDetails,recordingDetails,status,topicDetails";
                    if (isOwned)
                    {
                        parts += ",fileDetails,processingDetails";
                    }
                    VideosResource.ListRequest request = this.connection.GoogleYouTubeService.Videos.List(parts);
                    request.MaxResults = searchAmount;
                    request.Id = string.Join(",", searchIDs.Take(searchAmount));
                    request.PageToken = pageToken;

                    VideoListResponse response = await request.ExecuteAsync();
                    results.AddRange(response.Items);
                    searchIDs = new List <string>(searchIDs.Skip(searchAmount));
                    pageToken = response.NextPageToken;
                } while (searchIDs.Count > 0 && !string.IsNullOrEmpty(pageToken));
                return results;
            }));
        }
Example #9
0
        public SongRequest(string videoId, string whoRequested)
        {
            VideosResource.ListRequest list = youtubeService.Videos.List("snippet,contentDetails,statistics,status");
            requester = whoRequested;
            list.Id   = videoId;
            id        = videoId;
            VideoListResponse response = list.Execute();

            title      = response.Items.First().Snippet.Title;
            uploader   = response.Items.First().Snippet.ChannelTitle;
            views      = response.Items.First().Statistics.ViewCount;
            thumbUrl   = response.Items.First().Snippet.Thumbnails.Default__.Url;
            embeddable = response.Items.First().Status.Embeddable;
            duration   = new TimeSpan();

            Regex r = new Regex(@"PT((?<hours>\d+)H)?((?<minutes>\d+)M)?((?<seconds>\d+)S)?");
            Match m = r.Match(response.Items.First().ContentDetails.Duration);

            if (m.Groups["hours"].Value != "")
            {
                duration = duration.Add(new TimeSpan(Int32.Parse(m.Groups["hours"].Value), 0, 0));
            }
            if (m.Groups["minutes"].Value != "")
            {
                duration = duration.Add(new TimeSpan(0, Int32.Parse(m.Groups["minutes"].Value), 0));
            }
            if (m.Groups["seconds"].Value != "")
            {
                duration = duration.Add(new TimeSpan(0, 0, Int32.Parse(m.Groups["seconds"].Value)));
            }
        }
Example #10
0
 VideosResource.ListRequest CreateVideoResouceListResouceNewReleases(int count)
 {
     VideosResource.ListRequest request = CreateClient().Videos.List("snippet");
     request.Chart           = VideosResource.ListRequest.ChartEnum.MostPopular;
     request.VideoCategoryId = "10";
     request.MaxResults      = count;
     return(request);
 }
Example #11
0
        public async Task <VideoListResponse> GetVideoInfo(VideoQuery query)
        {
            VideosResource.ListRequest listRequest = _youtubeService.Videos.List(query.Part);
            listRequest.Id         = query.Id;
            listRequest.MaxResults = query.MaxResults;

            return(await listRequest.ExecuteAsync());
        }
Example #12
0
        public async Task <DateTime> getPublishedAt(YouTubeService youtubeService, String videoId)
        {
            VideosResource.ListRequest videosListRequest = youtubeService.Videos.List("snippet, contentDetails");
            videosListRequest.Id = videoId;
            VideoListResponse videosListResponse = await videosListRequest.ExecuteAsync();

            DateTime publishedAt = (DateTime)videosListResponse.Items[0].Snippet.PublishedAt;

            return(publishedAt);
        }
Example #13
0
        public void GetVideoDetails(string videoId)
        {
            VideosResource.ListRequest request = client.Videos.List("statistics, snippet");
            request.Id = videoId;

            VideoListResponse response = request.Execute();

            ulong?views = response.Items[0].Statistics.ViewCount;

            Console.WriteLine($"Video Name: {response.Items[0].Snippet.Title} Views: {views}");
        }
Example #14
0
        /// <summary>
        /// See whether a video is embeddable or not
        /// NB! THis dos not always work see: http://stackoverflow.com/questions/17099980/v3-api-returns-blocked-content-even-with-videoembedable-true
        /// for more information.
        /// </summary>
        /// <param name="VideoID"></param>
        /// <returns></returns>
        public static bool isEmbeddable(string VideoID, YouTubeService ys)
        {
            VideosResource.ListRequest lr = ys.Videos.List("status");
            lr.Id = VideoID;
            VideoListResponse searchResponse = lr.Execute();

            if (searchResponse.Items.Count == 0)
            {
                throw new ArgumentException("Didn't find a video with id", "VideoID");
            }
            return((bool)searchResponse.Items[0].Status.Embeddable);
        }
Example #15
0
        // Youtube 에서 제공하는 API, 영상 제목, 영상 정보, 영상 길이, 영상 조회수, 영상 설명, 영상 좋아요,싫어요 수, 댓글 수 게시자 채널명, 해당 채널 구독자 수,
        async void YoutubeAPi()
        {
            //비동기, 동기
            //비동기 : 해결 속도 동기 보다 느림, 대신 이 명령어 하고 있을 때 다른 일을 동시에 해결 할 수 있음
            //동기 : 비동기보다 빠르고 대신 이 명령어를 하는 동안 다른 명령어를 수행못함

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

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


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

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

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

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

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

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

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

            videoLength.Text = timeString;


            //status.embeddable	해야할것
            trackBar1.Maximum = timeSeconds;
        }
        internal async Task <VideoDto> GetVideoInfo(YouTubeService ytService, string videoId, bool getScheduledTime = false, bool getActualEndTime = false)
        {
            try
            {
                VideosResource.ListRequest request = ytService.Videos.List("snippet,id,liveStreamingDetails,statistics");
                request.Id = videoId;
                VideoListResponse result = await request.ExecuteAsync();

                Video livestream = result.Items.FirstOrDefault();

                if (livestream == null)
                {
                    return(null);
                }

                DateTime startTime = default;
                DateTime endTime   = default;

                if (getScheduledTime)
                {
                    DateTime.TryParse(livestream.LiveStreamingDetails.ScheduledStartTime, null, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out startTime);
                }
                else
                if (!DateTime.TryParse(livestream.LiveStreamingDetails.ActualStartTime, null, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out startTime))
                {
                    throw new StartCapturingTooSoonException(videoId);
                }

                if (getActualEndTime)
                {
                    if (!DateTime.TryParse(livestream.LiveStreamingDetails.ActualEndTime, null, styles: DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out endTime))
                    {
                        throw new NoActualEndtimeException(videoId);
                    }
                }

                return(new VideoDto()
                {
                    VideoId = livestream?.Id,
                    VideoTitle = livestream.Snippet.Title,
                    Misc = JsonConvert.SerializeObject(livestream),
                    StartTime = startTime,
                    EndTime = endTime,
                });
            }
            catch (Exception ex)
            {
                logger.LogError(ex, nameof(GetVideoInfo));
                throw;
            }
        }
        public async Task <ActionResult <VideoListResponse> > List([Required, FromQuery] AppVideoListRequest request)
        {
            YouTubeService service = await serviceAccessor.InitializeServiceAsync();

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

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

                return(new ActionResult <VideoListResponse>(response));
            } catch (GoogleApiException ex) {
                return(StatusCode((int)ex.HttpStatusCode, ex.Message));
            }
        }
Example #18
0
        public VideoStatistics GetVideoStats(YouTubeService youtubeService, string videoId)
        {
            VideosResource.ListRequest listRequest = youtubeService.Videos.List("statistics");
            listRequest.Id = videoId;
            VideoListResponse videoListResponse = listRequest.Execute();
            IList <Video>     items             = videoListResponse.Items;

            if (items.Count > 0)
            {
                return(items[0].Statistics);
            }

            return(null);
        }
Example #19
0
        private async Task <List <string> > enqueueUrlsFromPlaylist(ulong serverId, string play)
        {
            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey          = "AIzaSyAaTefrLXSr6d2-fHTZRH6Tv7QhzTdFqSw",
                ApplicationName = "DiscordBot"
            });

            Console.WriteLine("Got youtube service.");


            var nextPageToken = "";

            while (nextPageToken != null)
            {
                AudioInfo aI = audioInfos.Where(x => x.id.Equals(serverId)).FirstOrDefault();

                var playListItems = youtubeService.PlaylistItems.List("snippet,contentDetails");
                playListItems.PlaylistId = play;
                playListItems.MaxResults = 50;
                playListItems.PageToken  = nextPageToken;


                var playListResponse = await playListItems.ExecuteAsync();

                Console.WriteLine("Got playlist response.");



                foreach (PlaylistItem vidId in playListResponse.Items)
                {
                    Console.WriteLine("Starting to process video id.");
                    VideosResource.ListRequest videoR = youtubeService.Videos.List("snippet");
                    videoR.Id = vidId.ContentDetails.VideoId;
                    Console.WriteLine("Getting video details.");
                    var responseV = await videoR.ExecuteAsync();

                    string videoId = responseV.Items[0].Id;

                    aI.QueuedSongs.Enqueue("https://www.youtube.com/watch?v=" + videoId);
                    aI.SongNames.Enqueue(responseV.Items[0].Snippet.Title);
                    Console.WriteLine("Enqueued " + "https://www.youtube.com/watch?v=" + videoId);
                }
                nextPageToken = playListResponse.NextPageToken;
            }
            Console.WriteLine("finished getting playlist");
            return(null);
        }
Example #20
0
 public VideosResource.ListRequest ToActualRequest(YouTubeService service)
 {
     VideosResource.ListRequest actual = service.Videos.List(Part);
     actual.VideoCategoryId        = VideoCategoryId;
     actual.RegionCode             = RegionCode;
     actual.PageToken              = PageToken;
     actual.OnBehalfOfContentOwner = OnBehalfOfContentOwner;
     actual.MyRating   = MyRating;
     actual.MaxWidth   = MaxWidth;
     actual.MaxResults = MaxResults;
     actual.MaxHeight  = MaxHeight;
     actual.Locale     = Locale;
     actual.Id         = Id;
     actual.Hl         = Hl;
     actual.Chart      = Chart;
     return(actual);
 }
Example #21
0
        private async Task <YouTubeVideo> GetVideo(string id)
        {
            VideosResource.ListRequest videoRequest = _youTubeApiService.Videos.List("snippet");
            videoRequest.Id = id;

            VideoListResponse videoResponse = await videoRequest.ExecuteAsync();

            Video video = videoResponse.Items.First();

            string statistics = await _httpClient.GetStringAsync($"https://www.googleapis.com/youtube/v3/videos?id={video.Id}&key=AIzaSyA6F0Qqlul32ly5jSbnK9FYPL2Ge8Q7nQM&part=statistics");

            return(new YouTubeVideo(video, JsonConvert.DeserializeObject <VideoListResponse>(statistics)
                                    .Items
                                    .Single()
                                    .Statistics
                                    .ViewCount));
        }
Example #22
0
        private async void HomePage_Loaded(object sender, RoutedEventArgs e)
        {
            ChannelsListRequest = App.YoutubeClient.Videos.List(VideosResource.ListRequest.Parts.Snippet + 
                VideosResource.ListRequest.Parts.ContentDetails +
                VideosResource.ListRequest.Parts.Statistics,
                new VideosResource.ListRequest.Filters(VideosResource.ListRequest.Filters.Charts.MostPopular));
            ChannelsListRequest.MaxResults = 50;
            await LoadItems();

            scrollViewer = MainGrid.GetFirstDescendantOfType<ScrollViewer>();
            if (scrollViewer == null)
                return;

            scrollViewer.IsScrollInertiaEnabled = true;
            scrollViewer.ViewChanged += ScrollViewer_ViewChanged;
            scrollViewer.ViewChanged += ScrollViewer_FirstTimeChanged;                  
        }
Example #23
0
        public void SetInfoInVideoList(List <string> videoIdList)
        {
            int savedCount = 0;

            logger.Info("/-----Youtube Service Save Statistics Update Start-----/");
            try
            {
                if (videoIdList.Count > 0)
                {
                    foreach (string videoId in videoIdList)
                    {
                        VideosResource.ListRequest listRequest = youtube.Videos.List("statistics");
                        listRequest.Id = videoId;

                        VideoListResponse videoResponse = listRequest.Execute();

                        foreach (Video videoResult in videoResponse.Items)
                        {
                            switch (videoResult.Kind)
                            {
                            case "youtube#video":
                                // 데이터 저장
                                YoutubeT entity = new YoutubeT()
                                {
                                    YoutubeId    = videoResult.Id,
                                    ViewCount    = videoResult.Statistics.ViewCount,
                                    LikeCount    = videoResult.Statistics.LikeCount,
                                    DislikeCount = videoResult.Statistics.DislikeCount,
                                    CommentCount = videoResult.Statistics.CommentCount
                                };
                                youtubeRepository.UpdateYoutubeData(entity);
                                savedCount++;
                                break;
                            }
                        }
                    }
                }
                logger.Info("/-----Youtube Service Save Statistics Update End! Saved Count : " + savedCount + " -----/");
            }
            catch (Exception e)
            {
                logger.Error(e, "Youtube Service Step 2 Error");
            }
        }
Example #24
0
        private async Task <Video> GetVideoMetadataInternalAsync(string videoId, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogTrace($"{GetType()} - BEGIN {nameof(GetVideoMetadataInternalAsync)}");
                YouTubeService ytService = await _ytServiceProvider.CreateServiceAsync(cancellationToken);

                VideosResource.ListRequest req = ytService.Videos.List(SNIPPET_PART_PARAM);
                req.Id = videoId;

                VideoListResponse res = await req.ExecuteAsync(cancellationToken);

                return(res?.Items?.FirstOrDefault());
            }
            catch (Exception e)
            {
                _logger.LogError("An error occurred while retrieving video metadata", e);
                throw;
            }
        }
Example #25
0
        public void Process()
        {
            try
            {
                ChannelsResource.ListRequest channelListRequest = _youtube.Channels.List("id");

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

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

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

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


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


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

                // Save to Excel
                SaveToExcelPackage();
            }
            catch (Exception ex)
            {
                Log.LogError(this.GetType().Name + " - " + System.Reflection.MethodBase.GetCurrentMethod().Name, ex);
                throw ex;
            }
        }
Example #26
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);
        }
Example #27
0
        public static async Task <FeatureRequest <Response.YouTube, Error.YouTube> > SearchYouTube(string[] args, YouTubeService service)
        {
            if (service == null)
            {
                return(new FeatureRequest <Response.YouTube, Error.YouTube>(null, Error.YouTube.InvalidApiKey));
            }
            if (args.Length == 0)
            {
                return(new FeatureRequest <Response.YouTube, Error.YouTube>(null, Error.YouTube.Help));
            }
            string id    = null;
            Match  match = Regex.Match(args[0], "https:\\/\\/www.youtube.com\\/watch\\?v=([^&]+)");

            if (match.Success)
            {
                id = match.Groups[1].Value;
            }
            match = Regex.Match(args[0], "https:\\/\\/youtu.be\\/([^&]+)");
            if (match.Success)
            {
                id = match.Groups[1].Value;
            }
            else if (Regex.Match(args[0], "^[0-9a-zA-Z_-]{11}$").Success)
            {
                id = args[0];
            }
            if (id != null)
            {
                VideosResource.ListRequest r = service.Videos.List("snippet");
                r.Id = id;
                var resp = (await r.ExecuteAsync()).Items;
                if (resp.Count() == 0)
                {
                    return(new FeatureRequest <Response.YouTube, Error.YouTube>(null, Error.YouTube.NotFound));
                }
                return(new FeatureRequest <Response.YouTube, Error.YouTube>(new Response.YouTube()
                {
                    url = "https://www.youtube.com/watch?v=" + resp[0].Id,
                    name = resp[0].Snippet.Title,
                    imageUrl = resp[0].Snippet.Thumbnails.High.Url
                }, Error.YouTube.None));
            }
            SearchResource.ListRequest listRequest = service.Search.List("snippet");
            listRequest.Q          = Utilities.AddArgs(args);
            listRequest.MaxResults = 5;
            IList <SearchResult> searchListResponse = (await listRequest.ExecuteAsync()).Items;

            if (searchListResponse.Count == 0)
            {
                return(new FeatureRequest <Response.YouTube, Error.YouTube>(null, Error.YouTube.NotFound));
            }
            IEnumerable <SearchResult> correctVideos = searchListResponse.Where(x => x.Id.Kind == "youtube#video");

            if (correctVideos.Count() == 0)
            {
                return(new FeatureRequest <Response.YouTube, Error.YouTube>(null, Error.YouTube.NotFound));
            }
            VideosResource.ListRequest videoRequest = service.Videos.List("snippet,statistics");
            videoRequest.Id = string.Join(",", correctVideos.Select(x => x.Id.VideoId));
            IList <Video> videoResponse = (await videoRequest.ExecuteAsync()).Items;
            Video         biggest       = null;
            ulong         likes         = ulong.MinValue;

            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 || biggest == null)
                {
                    likes   = likeCount;
                    biggest = res;
                }
            }
            return(new FeatureRequest <Response.YouTube, Error.YouTube>(new Response.YouTube()
            {
                url = "https://www.youtube.com/watch?v=" + biggest.Id,
                name = biggest.Snippet.Title,
                imageUrl = biggest.Snippet.Thumbnails.High.Url
            }, Error.YouTube.None));
        }
Example #28
0
        /// <summary>
        /// Test the time elapsed in different API operations, in order to evaluate performance.
        /// </summary>
        /// <param name="maxItemsQuantity"></param>
        /// <returns></returns>
        public TimeElapsedResult TestOperationsTimeElapsed(int maxItemsQuantity, string searchTerm)
        {
            // Counters
            TimeElapsedResult result = new TimeElapsedResult();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            result.Results = results;

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

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

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

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

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

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

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

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

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

            return(results);
        }
Example #30
0
        //show videos by region code.
        public async Task <ResponseModel> GetVideoList(string regionCode)
        {
            try
            {
                var ApiKey         = "AIzaSyA8hPK8F-8BbO-8H6tQZuiopY5nYES1UR0";
                var model          = new EditVideoPageModel();
                var youtubeService = new YouTubeService(new BaseClientService.Initializer()
                {
                    ApiKey          = ApiKey,
                    ApplicationName = this.GetType().ToString()
                });

                // get category of US region
                //var categories = youtubeService.VideoCategories.List("snippet");
                //var languages = youtubeService.I18nLanguages.List("snippet");
                //var playList = youtubeService.Playlists.List("snippet");
                //var contents = youtubeService..List("snippet");
                //gapi.client.youtube.videos.list({ part: 'snippet,id', chart: 'mostPopular', regionCode: 'RU', maxResults: 8 })
                //playList.Callbac = true;


                VideosResource.ListRequest search_response = youtubeService.Videos.List("snippet,contentDetails,statistics");
                //search_response.Type = "video";
                search_response.RegionCode = regionCode;
                search_response.Chart      = VideosResource.ListRequest.ChartEnum.MostPopular;
                search_response.MaxResults = 50;
                //search_response.ChannelId = channelId;
                VideoListResponse searchresponse = search_response.Execute();

                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.
                List <YoutubeModel> searchmodel = new List <YoutubeModel>();
                YoutubeModel        obj         = null;
                foreach (var searchResult in searchresponse.Items)
                {
                    obj               = new YoutubeModel();
                    obj.title         = searchResult.Snippet.Title;
                    obj.regionCode    = regionCode;
                    obj.url           = "https://youtu.be/" + searchResult.Id;
                    obj.description   = searchResult.Snippet.Description;
                    obj.picture       = GetMainImg(searchResult.Snippet.Thumbnails);
                    obj.thumbnail     = GetThumbnailImg(searchResult.Snippet.Thumbnails);
                    obj.publishedAt   = searchResult.Snippet.PublishedAt;
                    obj.channelId     = searchResult.Snippet.ChannelId;
                    obj.channelTitle  = searchResult.Snippet.ChannelTitle;
                    obj.duration      = GetDuration(searchResult.ContentDetails.Duration);
                    obj.viewCount     = searchResult.Statistics.ViewCount.ToString();
                    obj.likeCount     = searchResult.Statistics.LikeCount.ToString();
                    obj.dislikeCount  = searchResult.Statistics.DislikeCount.ToString();
                    obj.favoriteCount = searchResult.Statistics.FavoriteCount.ToString();
                    obj.commentCount  = searchResult.Statistics.CommentCount.ToString();

                    searchmodel.Add(obj);
                    videos.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, "https://youtu.be/" + searchResult.Id));
                }
                response.Data = searchmodel;
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
            }
            response.Status_Code = 200;
            response.Success     = true;
            return(response);
        }