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

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

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


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

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

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

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

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

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

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

            videoLength.Text = timeString;


            //status.embeddable	해야할것
            trackBar1.Maximum = timeSeconds;
        }
        public async Task <ActionResult <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 #12
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 #13
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 #14
0
        private async Task UpdateChannels(Dictionary <string, List <UserPost> > newPosts, VideosResource.ListRequest req)
        {
            for (var i = 0; i < newPosts.Keys.Count; i += 50)
            {
                req.Id = string.Join(",", newPosts.Keys.Skip(i).Take(50));
                var response = await req.ExecuteAsync();

                foreach (var vid in response.Items)
                {
                    foreach (var upost in newPosts[vid.Id])
                    {
                        upost.ChannelID   = vid.Snippet.ChannelId;
                        upost.ChannelName = vid.Snippet.ChannelTitle;
                        UserPost.UpdatePost(upost);
                    }
                }
            }
        }
Example #15
0
        private async Task LoadItems()
        {
            if (IsLoading == true)
                return;

            IsLoading = true;
            //ChannelsListRequest.Hl = App.Region.Gl;
            ChannelsListRequest.RegionCode = App.Region.Gl;
            var response = await ChannelsListRequest.ExecuteAsync();

            foreach (var item in response.VideoItems)
            {
                Videos.Add(item);
            }

            NextPageToken = response.NextPageToken;
            IsLoading = false;
        }
Example #16
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 #17
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 #18
0
        public async Task QueuePlaylist(CommandContext ctx, string playlistUrl, [Description("Shuffle the playlist when adding to queue. \"true\" to enable.")] bool shuffle = false)
        {
            if (ctx.Client.GetVoiceNext()?.GetConnection(ctx.Guild)?.Channel != null && ctx.Client.GetVoiceNext().GetConnection(ctx.Guild).Channel.Users.All(e => e.Id != ctx.User.Id))
            {
                throw new OutputException("You must join a voice channel to queue songs.");
            }

            Uri playlistUri;

            try
            {
                playlistUri = new Uri(playlistUrl);
            }
            catch
            {
                throw new OutputException("Invalid url.");
            }

            NameValueCollection query = HttpUtility.ParseQueryString(playlistUri.Query);

            if (!query.AllKeys.Contains("list"))
            {
                throw new OutputException("Url must point to a YouTube playlist, specifically with a \"list=\" query.");
            }

            YouTubeService youtubeService = new YouTubeService(new BaseClientService.Initializer
            {
                ApiKey          = Globals.BotSettings.YoutubeApiKey,
                ApplicationName = this.GetType().ToString()
            });

            PlaylistsResource.ListRequest playlistListRequest = youtubeService.Playlists.List("snippet");
            playlistListRequest.Id         = query["list"];
            playlistListRequest.MaxResults = 1;

            PlaylistListResponse playlistListResponse = playlistListRequest.Execute();

            PlaylistItemsResource.ListRequest playlistItemsListRequest = youtubeService.PlaylistItems.List("snippet");
            playlistItemsListRequest.PlaylistId = query["list"];
            playlistItemsListRequest.MaxResults = 50;

            PlaylistItemListResponse playlistItemsListResponse = playlistItemsListRequest.Execute();

            if (!playlistItemsListResponse.Items.Any())
            {
                throw new OutputException("Unable to retrieve playlist or playlist is empty.");
            }

            if (shuffle)
            {
                playlistItemsListResponse.Items.Shuffle();
            }

            int resultQueueCount = GuildQueues.ContainsKey(ctx.Guild.Id) ? GuildQueues[ctx.Guild.Id].Count + playlistItemsListResponse.Items.Count : playlistItemsListResponse.Items.Count;

            await ctx.RespondAsync($"Queuing {playlistItemsListResponse.Items.Count} songs, please be patient if this is the first items to be added to queue. " +
                                   "(If you try to play music and nothing happens most likely the first song is still pending)");

            if (!GuildMusicStatuses.TryGetValue(ctx.Guild.Id, out MusicStatus musicStatus))
            {
                GuildMusicStatuses.Add(ctx.Guild.Id, new MusicStatus
                {
                    Skip = false
                });
            }

            while (GuildMusicStatuses[ctx.Guild.Id].Queuing)
            {
            }

            GuildMusicStatuses[ctx.Guild.Id].Queuing = true;

            foreach (PlaylistItem playlistItem in playlistItemsListResponse.Items)
            {
                string id = playlistItem.Snippet.ResourceId.VideoId;

                VideosResource.ListRequest idSearch = youtubeService.Videos.List("id,snippet");
                idSearch.Id         = id;
                idSearch.MaxResults = 1;

                VideoListResponse videoListResponse = await idSearch.ExecuteAsync();

                if (videoListResponse.Items.Count == 0)
                {
                    await ctx.RespondAsync("Video link cannot be parsed.");

                    return;
                }

                if (!GuildQueues.ContainsKey(ctx.Guild.Id))
                {
                    GuildQueues.Add(ctx.Guild.Id, new List <JigglySong>());
                }

                Video parsedVideo = videoListResponse.Items.First();

                if (!string.IsNullOrWhiteSpace(parsedVideo.ContentDetails?.Duration) && XmlConvert.ToTimeSpan(parsedVideo.ContentDetails.Duration).Minutes > 15)
                {
                    await ctx.RespondAsync("This video is too long, please try to find something shorter than 15 minutes.");
                }

                Guid guid = Guid.NewGuid();

                AddSong(guid, parsedVideo.Snippet.Title, parsedVideo.Id, parsedVideo.Snippet.ChannelTitle, JigglySong.SongType.Youtube, ctx.Member);

                if (!DownloadHelper.GuildMusicTasks.ContainsKey(ctx.Guild.Id))
                {
                    DownloadHelper.GuildMusicTasks.Add(ctx.Guild.Id, new List <(Guid guid, Func <string> downloadTask)>());
                }

                DownloadHelper.GuildMusicTasks[ctx.Guild.Id].Add((guid, () => DownloadHelper.DownloadFromYouTube(ctx, $"https://www.youtube.com/watch?v={id}")));

                if (!DownloadHelper.IsDownloadLoopRunning)
                {
                    new Thread(() => DownloadHelper.DownloadQueue(ctx.Guild.Id)).Start();
                }
            }

            GuildMusicStatuses[ctx.Guild.Id].Queuing = false;

            DiscordEmbedBuilder confirmationBuilder = new DiscordEmbedBuilder
            {
                Description = $"**✅ Successfully added [{playlistListResponse.Items.First().Snippet.Title}](https://www.youtube.com/playlist?list={query["list"]}) " +
                              $"to queue positions {resultQueueCount + 1 - playlistItemsListResponse.Items.Count}-{resultQueueCount}**"
            };

            await ctx.RespondAsync(null, false, confirmationBuilder.Build());
        }
Example #19
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 #20
0
        public async Task Queue(CommandContext ctx, [Description("A search query or a direct link to the video."), RemainingText] string queryString)
        {
            if (string.IsNullOrWhiteSpace(queryString))
            {
                if (!GuildQueues.TryGetValue(ctx.Guild.Id, out List <JigglySong> resultSongs))
                {
                    await ctx.RespondAsync("There is nothing currently queued.");

                    return;
                }

                for (int i = 0; i < resultSongs.Count; i += 5)
                {
                    DiscordEmbedBuilder queueBuilder = new DiscordEmbedBuilder
                    {
                        Title = $"Current Queue {i + 1}-{i + 5}",
                        Color = DiscordColor.Aquamarine
                    };

                    string tracks = string.Empty;

                    for (int j = i; j < i + 5; j++)
                    {
                        if (j >= resultSongs.Count)
                        {
                            break;
                        }

                        JigglySong resultSong = resultSongs[j];

                        tracks += $"{j + 1}: [**{resultSong.Title}** by **{resultSong.Artist}**](https://www.youtube.com/watch?v={resultSong.Id})\n";
                    }

                    queueBuilder.Description = tracks;

                    await ctx.RespondAsync(string.Empty, false, queueBuilder.Build());
                }

                return;
            }

            if (ctx.Client.GetVoiceNext()?.GetConnection(ctx.Guild)?.Channel != null && ctx.Client.GetVoiceNext().GetConnection(ctx.Guild).Channel.Users.All(e => e.Id != ctx.User.Id))
            {
                throw new OutputException("You must join a voice channel to queue songs.");
            }

            YouTubeService youtubeService = new YouTubeService(new BaseClientService.Initializer
            {
                ApiKey          = Globals.BotSettings.YoutubeApiKey,
                ApplicationName = this.GetType().ToString()
            });

            try
            {
                Uri uri = new Uri(queryString);

                if (uri.Host != "youtu.be" && !uri.Host.ToLower().Contains("youtube"))
                {
                    throw new ArgumentException();
                }

                NameValueCollection query = HttpUtility.ParseQueryString(uri.Query);

                string id = query.AllKeys.Contains("v") ? query["v"] : uri.Segments.Last();

                VideosResource.ListRequest idSearch = youtubeService.Videos.List("id,snippet");
                idSearch.Id         = id;
                idSearch.MaxResults = 1;

                VideoListResponse videoListResponse = await idSearch.ExecuteAsync();

                if (videoListResponse.Items.Count == 0)
                {
                    await ctx.RespondAsync("Video link cannot be parsed.");

                    return;
                }

                if (!GuildQueues.ContainsKey(ctx.Guild.Id))
                {
                    GuildQueues.Add(ctx.Guild.Id, new List <JigglySong>());
                }

                Video parsedVideo = videoListResponse.Items.First();

                if (!string.IsNullOrWhiteSpace(parsedVideo.ContentDetails?.Duration) && XmlConvert.ToTimeSpan(parsedVideo.ContentDetails.Duration).Minutes > 15)
                {
                    await ctx.RespondAsync("This video is too long, please try to find something shorter than 15 minutes.");
                }

                Guid guid = Guid.NewGuid();

                AddSong(guid, parsedVideo.Snippet.Title, parsedVideo.Id, parsedVideo.Snippet.ChannelTitle, JigglySong.SongType.Youtube, ctx.Member);

                if (!DownloadHelper.GuildMusicTasks.ContainsKey(ctx.Guild.Id))
                {
                    DownloadHelper.GuildMusicTasks.Add(ctx.Guild.Id, new List <(Guid guid, Func <string> downloadTask)>());
                }

                DownloadHelper.GuildMusicTasks[ctx.Guild.Id].Add((guid, () => DownloadHelper.DownloadFromYouTube(ctx, queryString)));

                if (!DownloadHelper.IsDownloadLoopRunning)
                {
                    new Thread(() => DownloadHelper.DownloadQueue(ctx.Guild.Id)).Start();
                }

                DiscordEmbedBuilder confirmationBuilder = new DiscordEmbedBuilder
                {
                    Description = $"**✅ Successfully added [{parsedVideo.Snippet.Title}](https://www.youtube.com/watch?v={parsedVideo.Id}) to queue position {GuildQueues[ctx.Guild.Id].Count}**"
                };

                await ctx.RespondAsync(null, false, confirmationBuilder.Build());
            }
            catch
            {
                SearchResource.ListRequest searchListRequest = youtubeService.Search.List("snippet");
                searchListRequest.Q          = queryString.Replace(" ", "+");
                searchListRequest.MaxResults = 10;
                searchListRequest.Type       = "video";

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

                DiscordEmbedBuilder builder = new DiscordEmbedBuilder
                {
                    Title = "Enter the number of your selection."
                };

                List <JigglySong> videos     = new List <JigglySong>();
                string            selections = string.Empty;

                // Add each result to the appropriate list, and then display the lists of
                // matching videos, channels, and playlists.
                for (int i = 0; i < 5; i++)
                {
                    if (!searchListResponse.Items.Any())
                    {
                        await ctx.RespondAsync("No available tracks less than 15 minutes.");

                        return;
                    }

                    SearchResult searchResult = searchListResponse.Items[i];

                    VideosResource.ListRequest listRequest = youtubeService.Videos.List("snippet");
                    listRequest.Id = searchResult.Id.VideoId;

                    if (!string.IsNullOrWhiteSpace((await listRequest.ExecuteAsync()).Items.First().ContentDetails?.Duration) && XmlConvert.ToTimeSpan((await listRequest.ExecuteAsync()).Items.First().ContentDetails.Duration).Minutes > 15)
                    {
                        searchListResponse.Items.RemoveAt(i);
                        i--;
                        continue;
                    }

                    selections += $"{i + 1}: {searchResult.Snippet.Title}\n";
                    videos.Add(new JigglySong
                    {
                        Title  = searchResult.Snippet.Title,
                        Id     = searchResult.Id.VideoId,
                        Artist = searchResult.Snippet.ChannelTitle,
                        Type   = JigglySong.SongType.Youtube,
                        Queuer = ctx.Member
                    });
                }

                selections += "c: Cancel";

                builder.Description = selections;

                DiscordMessage resultsMessage = await ctx.RespondAsync(string.Empty, false, builder.Build());

                int result = -1;

                MessageContext msgContext = await ctx.Client.GetInteractivity().WaitForMessageAsync(e => e.Author.Id == ctx.Message.Author.Id && (e.Content.ToLower() == "c" || int.TryParse(e.Content, out result) && result > 0 && result <= videos.Count), TimeSpan.FromSeconds(30));

                if (msgContext == null)
                {
                    await ctx.RespondAsync($"🖍*Jigglypuff wrote on {ctx.User.Mention}'s face!*🖍\nMaybe they should have picked a song...");

                    await resultsMessage.DeleteAsync();

                    return;
                }

                result--;

                if (result >= 0)
                {
                    if ((await ctx.Guild.GetMemberAsync(ctx.Client.CurrentUser.Id)).PermissionsIn(ctx.Channel).HasPermission(Permissions.ManageMessages))
                    {
                        await msgContext.Message.DeleteAsync();
                    }

                    if (!GuildQueues.ContainsKey(ctx.Guild.Id))
                    {
                        GuildQueues.Add(ctx.Guild.Id, new List <JigglySong>());
                    }

                    JigglySong selectedSong = videos[result];

                    DiscordEmbedBuilder confirmationBuilder = new DiscordEmbedBuilder
                    {
                        Description = $"**✅ Successfully added [{videos[result].Title}](https://www.youtube.com/watch?v={videos[result].Id}) to queue position {GuildQueues[ctx.Guild.Id].Count + 1}**"
                    };

                    if (GuildQueues[ctx.Guild.Id].Count == 0)
                    {
                        confirmationBuilder.Description += "\nPlease be patient; it takes a bit for the first song to cache.";
                    }

                    await ctx.RespondAsync(string.Empty, false, confirmationBuilder.Build());

                    if (!GuildMusicStatuses.TryGetValue(ctx.Guild.Id, out MusicStatus musicStatus))
                    {
                        GuildMusicStatuses.Add(ctx.Guild.Id, new MusicStatus
                        {
                            Skip = false
                        });
                    }

                    Guid guid = Guid.NewGuid();

                    AddSong(guid, selectedSong.Title, selectedSong.Id, selectedSong.Artist, selectedSong.Type, selectedSong.Queuer);

                    if (!DownloadHelper.GuildMusicTasks.ContainsKey(ctx.Guild.Id))
                    {
                        DownloadHelper.GuildMusicTasks.Add(ctx.Guild.Id, new List <(Guid guid, Func <string> downloadTask)>());
                    }

                    DownloadHelper.GuildMusicTasks[ctx.Guild.Id].Add((guid, () => DownloadHelper.DownloadFromYouTube(ctx, $"https://www.youtube.com/watch?v={videos[result].Id}")));

                    if (!DownloadHelper.IsDownloadLoopRunning)
                    {
                        new Thread(() => DownloadHelper.DownloadQueue(ctx.Guild.Id)).Start();
                    }
                }
                else
                {
                    DiscordEmbedBuilder confirmationBuilder = new DiscordEmbedBuilder
                    {
                        Title = "🚫 Canceled queue."
                    };

                    await ctx.RespondAsync(string.Empty, false, confirmationBuilder.Build());
                }
            }
        }
        public async Task <Chart> GetYouTubeVideoIds(Chart chart)
        {
            string youTubeApiKey;

            try
            {
                youTubeApiKey = ConfigurationManager.AppSettings[YouTubeApiKeyConfigKey];
            }
            catch (ConfigurationErrorsException e)
            {
                Console.WriteLine("Error: " + e.Message);
                return(null);
            }

            // Create the YouTube service
            var youTubeService = new YouTubeService(new BaseClientService.Initializer
            {
                ApiKey          = youTubeApiKey,
                ApplicationName = GetType().ToString(),
            });

            foreach (Song song in chart.Songs)
            {
                var searchListRequest = youTubeService.Search.List("snippet");
                searchListRequest.Q          = song.Keyword;
                searchListRequest.MaxResults = 10;

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

                // Put candidate video ids into a comma-separated string
                StringBuilder videoIdsSb = null;
                foreach (var searchResult in searchListResponse.Items)
                {
                    if (searchResult.Id.Kind != "youtube#video")
                    {
                        continue;
                    }

                    bool ignore = false;
                    foreach (string ignoreItem in IgnoreList)
                    {
                        if (searchResult.Snippet.Title.Contains(ignoreItem))
                        {
                            ignore = true;
                            break;
                        }
                    }
                    if (ignore)
                    {
                        continue;
                    }

                    if (videoIdsSb == null)
                    {
                        videoIdsSb = new StringBuilder();
                    }
                    else
                    {
                        videoIdsSb.Append(',');
                    }
                    videoIdsSb.Append(searchResult.Id.VideoId);
                }

                if (videoIdsSb != null)
                {
                    string videoIds = videoIdsSb.ToString();

                    // Get statistics for video candidats
                    VideosResource.ListRequest videoResourceListRequest = youTubeService.Videos.List("statistics");
                    videoResourceListRequest.Id         = videoIds;
                    videoResourceListRequest.MaxResults = 10;

                    VideoListResponse videoListResponse = await videoResourceListRequest.ExecuteAsync();

                    // Find most popular video (by view count)
                    ulong?maxViewCount = 0;
                    foreach (Video videoResult in videoListResponse.Items)
                    {
                        if (videoResult.Statistics.ViewCount > maxViewCount)
                        {
                            song.VideoId = videoResult.Id;
                            maxViewCount = videoResult.Statistics.ViewCount;
                        }
                    }
                    Debug.WriteLine("Using YouTube service found video id for {0} - {1} song as {2} having {3} views", song.Artist, song.Title, song.VideoId, maxViewCount);
                }
            }

            return(chart);
        }
Example #22
0
        private async Task AccessPlaylist()
        {
            UserCredential credential;

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

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

            var playlists = youtubeService.Playlists.List("snippet");

            playlists.PageToken  = "";
            playlists.MaxResults = 50;
            playlists.Mine       = true;
            PlaylistListResponse presponse = await playlists.ExecuteAsync();

            foreach (var currentPlayList in presponse.Items)
            {
                if (currentPlayList.Snippet.Title.Equals("Songs"))
                {
                    PlaylistItemsResource.ListRequest listRequest = youtubeService.PlaylistItems.List("contentDetails");
                    listRequest.MaxResults = 50;
                    listRequest.PlaylistId = currentPlayList.Id;
                    listRequest.PageToken  = playlists.PageToken;
                    var response = await listRequest.ExecuteAsync();

                    var index = 1;
                    foreach (var playlistItem in response.Items)
                    {
                        VideosResource.ListRequest videoR = youtubeService.Videos.List("snippet, contentDetails, status");
                        videoR.Id = playlistItem.ContentDetails.VideoId;
                        var responseV = await videoR.ExecuteAsync();

                        if (responseV.Items.Count > 0)
                        {
                            string link = String.Format("https://www.youtube.com/watch?v={0}&list={1}&index={2}", videoR.Id, currentPlayList.Id, index);
                            IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(link);

                            try
                            {
                                VideoInfo video = videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 0 && !String.IsNullOrEmpty(info.Title));
                                Console.WriteLine("Downloading {0}", video.Title);
                                if (video.RequiresDecryption)
                                {
                                    DownloadUrlResolver.DecryptDownloadUrl(video);
                                }

                                using (var progress = new ProgressBar())
                                {
                                    for (int i = 0; i <= 100; i++)
                                    {
                                        progress.Report((double)i / 100);
                                        Thread.Sleep(20);
                                    }
                                }
                                var audioDownloader = new VideoDownloader(video, Path.Combine(@"C:\Users\prsangat\Desktop\Songs", video.Title + ".mp3"));
                                using (var progress = new ProgressBar())
                                {
                                    audioDownloader.DownloadProgressChanged += (sender, args) => progress.Report(args.ProgressPercentage);
                                }
                                //audioDownloader.DownloadProgressChanged += (sender, args) => progre//Console.Write( "\r{0}% ", Math.Round(args.ProgressPercentage));
                                audioDownloader.Execute();
                                Console.WriteLine("Download Complete.");
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine();
                                Console.WriteLine(ex.ToString());
                                Console.WriteLine();
                                // throw;
                            }

                            index++;
                        }
                    }
                    playlists.PageToken = response.NextPageToken;
                }
            }
        }