Beispiel #1
0
 public MusicItem(VideoSearchResult Video)
 {
     Title     = Video.Title;
     Thumbnail = Video.Thumbnails.GetMaxResUrl();
     Author    = Video.Author.ChannelTitle;
     UrlOrId   = Video.Id;
     Duration  = Video.Duration ?? TimeSpan.Zero;
     PublicUrl = Video.Url;
     IsYouTube = true;
 }
        public IActionResult VideoSearch(string key, string index)
        {
            key = key.Trim();
            if (string.IsNullOrEmpty(key))
            {
                return(Redirect("/video"));
            }
            int.TryParse(index, out int currentIndex);
            currentIndex = currentIndex < 1 ? 1 : currentIndex;
            var pageSize = 10;

            var searchKey    = $"VideoSearch_{key}_{currentIndex}";
            var searchResult = _redisService.Get <VideoSearchResult>(searchKey);

            if (searchResult == null)
            {
                long totalCount = 0;
                searchResult = new VideoSearchResult()
                {
                    PageIndex = currentIndex, PageSize = pageSize
                };
                var result = _videoService.SearchVideo(key, currentIndex, pageSize, out totalCount);
                searchResult.Result     = result;
                searchResult.TotalCount = totalCount;
                searchResult.Key        = key;
                if (result != null && result.Count > 0)
                {
                    _redisService.Set(searchKey, searchResult, 10);
                }
            }
            ViewData["VideoSearchResult"] = searchResult;

            //总榜
            var totalRankingKey = "VideoSearch_TotalRankingKey";

            if (!_memoryCache.TryGetValue(totalRankingKey, out List <VideoRank> totalRankingList))
            {
                totalRankingList = new List <VideoRank>();
                var totalRanking = _videoRankingService.GetTotalRanking(1, 20);
                var rankingList  = _videoService.GetVideoList(totalRanking.Select(x => Convert.ToInt64(x.Key)));
                totalRanking.ForEach(item =>
                {
                    var totalRankingItem = rankingList.FirstOrDefault(x => x.Id == Convert.ToInt64(item.Key));
                    if (totalRankingItem != null)
                    {
                        totalRankingList.Add(ConvertVideoToVideoRank(totalRankingItem, item.Value));
                    }
                });
                _memoryCache.Set(totalRankingKey, totalRankingList, new DateTimeOffset(DateTime.Now.AddHours(1)));//1小时
            }
            ViewData["VideoSearch_TotalRanking"] = totalRankingList;
            return(View());
        }
Beispiel #3
0
        public override MediaServiceSearchResult GetSearchResult(object entity, Item accountItem)
        {
            Asset             asset  = (Asset)entity;
            VideoSearchResult result = base.GetSearchResult <VideoSearchResult>(Constants.IndexName, accountItem, i => i.TemplateId == Templates.Video.TemplateID && i.UniqueID == asset.UniqueId);

            if ((result != null) && (result.UniqueID == asset.UniqueId))
            {
                return(result);
            }

            return(null);
        }
Beispiel #4
0
        private async Task EnqueueVideo(VideoSearchResult video, EmbedBuilder Builder)
        {
            Client.Enqueue(video);

            if (Client.State < PlayerState.Playing)
            {
                await Client.PlayAsync(Context);
            }
            else
            {
                Builder.Url         = video.Url;
                Builder.Description = GetEntry("YTVideoEnqueued");
                Builder.AddField(GetEntry("TitleUploadedBy"), video.Title + " | " + video.Author.ChannelTitle);
                Builder.ThumbnailUrl = video.Thumbnails.GetMaxResUrl();

                await Context.Channel.SendMessageAsync("", embed : Builder.Build());
            }
        }
        public IActionResult VideoList(string classify, string index)
        {
            if (string.IsNullOrEmpty(classify))
            {
                return(Redirect("/video"));
            }
            var name = VideoCommonService.GetVideoRealClassify(classify, out string type);

            if (name == null)
            {
                return(Redirect("/video"));
            }
            int.TryParse(index, out int currentIndex);
            currentIndex = currentIndex < 1 ? 1 : currentIndex;
            var pageSize = 18;
            var listKey  = $"VideoList_{name}_{currentIndex}";

            if (!_memoryCache.TryGetValue(listKey, out VideoSearchResult result))
            {
                long totalCount = 0;
                result = new VideoSearchResult()
                {
                    PageIndex = currentIndex, PageSize = pageSize
                };
                var list = _videoService.GetVideoByClassify(name, currentIndex, pageSize, out totalCount);
                result.Result     = list;
                result.TotalCount = totalCount;
                result.Key        = name;
                if (list != null && list.Count > 0)
                {
                    _memoryCache.Set(listKey, result, new DateTimeOffset(DateTime.Now.AddMinutes(20)));
                }
            }
            ViewData["VideoType"] = type;
            ViewData["VideoList"] = result;
            return(View());
        }
        protected override List <ID> GetReference(PlayList entity, Item accountItem)
        {
            if (entity.VideoIds == null || entity.VideoIds.Count == 0)
            {
                return(new List <ID>(0));
            }
            Expression <Func <VideoSearchResult, bool> > ancestorFilter = ContentSearchUtil.GetAncestorFilter <VideoSearchResult>(accountItem, TemplateIDs.Video);
            Expression <Func <VideoSearchResult, bool> > second         = Enumerable.Aggregate <string, Expression <Func <VideoSearchResult, bool> > >((IEnumerable <string>)entity.VideoIds, PredicateBuilder.False <VideoSearchResult>(), (Func <Expression <Func <VideoSearchResult, bool> >, string, Expression <Func <VideoSearchResult, bool> > >)((current, tmp) => PredicateBuilder.Or <VideoSearchResult>(current, (Expression <Func <VideoSearchResult, bool> >)(i => i.Id == tmp))));
            List <VideoSearchResult> all = ContentSearchUtil.FindAll <VideoSearchResult>(Configuration.Settings.IndexName, PredicateBuilder.And <VideoSearchResult>(ancestorFilter, second));

            if (all.Count < entity.VideoIds.Count)
            {
                IItemSynchronizer itemSynchronizer1 = MediaFrameworkContext.GetItemSynchronizer(typeof(Video));
                if (itemSynchronizer1 != null)
                {
                    foreach (string str in entity.VideoIds)
                    {
                        string videoId = str;
                        if (!Enumerable.Any <VideoSearchResult>((IEnumerable <VideoSearchResult>)all, (Func <VideoSearchResult, bool>)(i => i.Id == videoId)))
                        {
                            IItemSynchronizer itemSynchronizer2 = itemSynchronizer1;
                            Video             video1            = new Video();
                            video1.Id = videoId;
                            Video             video2            = video1;
                            Item              accountItem1      = accountItem;
                            VideoSearchResult videoSearchResult = itemSynchronizer2.Fallback((object)video2, accountItem1) as VideoSearchResult;
                            if (videoSearchResult != null)
                            {
                                all.Add(videoSearchResult);
                            }
                        }
                    }
                }
            }
            return(Enumerable.ToList <ID>(Enumerable.Select <VideoSearchResult, ID>((IEnumerable <VideoSearchResult>)all, (Func <VideoSearchResult, ID>)(i => i.ItemId))));
        }
Beispiel #7
0
        public async Task PlayAsync(params string[] Args)
        {
            if (Client.State == PlayerState.Paused)
            {
                Client.State = PlayerState.Playing;
                return;
            }
            EmbedBuilder Builder = new EmbedBuilder()
            {
                Color = Client.Color,
                Title = GetEntry("Enqueue")
            };

            if (Args.Length > 0)
            {
                if (Args[0] == "soundcloud" && Args.Length > 1)
                {
                    if (Args[1] == "playlist" && Args.Length > 2)
                    {
                        List <Models.SoundCloud.Playlist> playlists = Client.SearchSoundCloudPlaylist(string.Join(" ", Args.Skip(2)));

                        Models.SoundCloud.Playlist playlist = await Global.MusicHandler.Select(Client, playlists, Context, Language);

                        if (playlist == null)
                        {
                            Builder.Description = GetEntry("SCPlaylistCancelled");
                            await Context.Channel.SendMessageAsync("", embed : Builder.Build());
                        }
                        else
                        {
                            Client.Enqueue(playlist);

                            Builder.Url         = playlist.Url;
                            Builder.Description = GetEntry("SCPlaylistEnqueued");
                            Builder.AddField(GetEntry("TitleTrackCount"), playlist.Title + " | " + playlist.TrackCount);
                            Builder.AddField(GetEntry("PlaylistMadeBy"), playlist.User.Username);
                            Builder.ThumbnailUrl = playlist.ThumbnailUrl;

                            await Context.Channel.SendMessageAsync("", embed : Builder.Build());

                            if (Client.State < PlayerState.Playing)
                            {
                                await Client.PlayAsync(Context);
                            }
                        }
                    }
                    else
                    {
                        List <Models.SoundCloud.Track> tracks = Client.SearchSoundCloudTrack(string.Join(" ", Args.Skip(1)));

                        Models.SoundCloud.Track track = await Global.MusicHandler.Select(Client, tracks, Context, Language);

                        if (track == null)
                        {
                            Builder.Description = GetEntry("SCTrackCancelled");
                            await Context.Channel.SendMessageAsync("", embed : Builder.Build());
                        }
                        else
                        {
                            Client.Enqueue(track);
                            if (Client.State < PlayerState.Playing)
                            {
                                await Client.PlayAsync(Context);
                            }
                            else
                            {
                                Builder.Url         = track.Url;
                                Builder.Description = GetEntry("SCTrackEnqueued");
                                Builder.AddField(GetEntry("TitleUploadedBy"), track.Title + " | " + track.User.Username);
                                Builder.ThumbnailUrl = track.ThumbnailUrl;

                                await Context.Channel.SendMessageAsync("", embed : Builder.Build());
                            }
                        }
                    }
                }
                else if (Args[0].ToLower() == "listen.moe")
                {
                    Client.EnqueueLISTENmoe(Args.Length > 1 && Args[1].ToLower() == "kpop");
                    Builder.Description = "LISTEN.moe";
                    await Context.Channel.SendMessageAsync("", embed : Builder.Build());

                    if (Client.State < PlayerState.Playing)
                    {
                        await Client.PlayAsync(Context);
                    }
                }
                else
                {
                    string        url    = string.Join(" ", Args);
                    YoutubeClient client = new YoutubeClient();
                    PlaylistId?   id     = PlaylistId.TryParse(url);
                    if (id.HasValue)
                    {
                        List <PlaylistVideo> videos = await client.Playlists.GetVideosAsync(id.Value).ToListAsync();

                        if (videos.Count == 0)
                        {
                            Builder.Description = GetEntry("YTPlaylistEmpty");
                            await Context.Channel.SendMessageAsync("", embed : Builder.Build());
                        }
                        else
                        {
                            YoutubeExplode.Playlists.Playlist playlist = await client.Playlists.GetAsync(id.Value);

                            Client.Enqueue(playlist);

                            if (Client.State < PlayerState.Playing)
                            {
                                await Client.PlayAsync(Context);
                            }
                            else
                            {
                                Builder.Url         = playlist.Url;
                                Builder.Description = GetEntry("YTPlaylistEnqueued");
                                Builder.AddField(GetEntry("TitleUploadedBy"), playlist.Title + " | " + playlist.Author);
                                Builder.ThumbnailUrl = videos[0].Thumbnails.GetMaxResUrl();

                                await Context.Channel.SendMessageAsync("", embed : Builder.Build());
                            }
                        }
                    }
                    VideoId?vid = VideoId.TryParse(url);
                    if (vid.HasValue)
                    {
                        Video video = await client.Videos.GetAsync(vid.Value);
                        await EnqueueVideo(video, Builder);
                    }
                    else
                    {
                        List <VideoSearchResult> videos = await Client.SearchYouTubeVideoAsync(url);

                        VideoSearchResult video = await Global.MusicHandler.Select(Client, videos, Context, Language);

                        if (video == null)
                        {
                            Builder.Description = GetEntry("YTVideoCancelled");
                            await Context.Channel.SendMessageAsync("", embed : Builder.Build());
                        }
                        else
                        {
                            await EnqueueVideo(video, Builder);
                        }
                    }
                }
            }
            else
            {
                if (Client.Queue.Count != 0 && Client.State < PlayerState.Playing)
                {
                    await Client.PlayAsync(Context);
                }
                else
                {
                    await Context.Channel.SendMessageAsync(GetEntry("Empty"));
                }
            }
        }
Beispiel #8
0
 public void Enqueue(VideoSearchResult Video)
 {
     Queue.Add(new MusicItem(Video));
     PropertyChanged?.Invoke();
 }
Beispiel #9
0
    /// <summary>
    /// Enumerates batches of search results returned by the specified query.
    /// </summary>
    public async IAsyncEnumerable <Batch <ISearchResult> > GetResultBatchesAsync(
        string searchQuery,
        SearchFilter searchFilter,
        [EnumeratorCancellation] CancellationToken cancellationToken = default)
    {
        var encounteredIds    = new HashSet <string>(StringComparer.Ordinal);
        var continuationToken = default(string?);

        do
        {
            var results = new List <ISearchResult>();

            var searchResults = await _controller.GetSearchResultsAsync(
                searchQuery,
                searchFilter,
                continuationToken,
                cancellationToken
                );

            foreach (var videoExtractor in searchResults.GetVideos())
            {
                if (searchFilter is not SearchFilter.None and not SearchFilter.Video)
                {
                    Debug.Fail("Did not expect videos in search results.");
                    break;
                }

                var id =
                    videoExtractor.TryGetVideoId() ??
                    throw new YoutubeExplodeException("Could not extract video ID.");

                // Don't yield the same result twice
                if (!encounteredIds.Add(id))
                {
                    continue;
                }

                var title =
                    videoExtractor.TryGetVideoTitle() ??
                    throw new YoutubeExplodeException("Could not extract video title.");

                var channelTitle =
                    videoExtractor.TryGetVideoAuthor() ??
                    throw new YoutubeExplodeException("Could not extract video author.");

                var channelId =
                    videoExtractor.TryGetVideoChannelId() ??
                    throw new YoutubeExplodeException("Could not extract video channel ID.");

                var duration = videoExtractor.TryGetVideoDuration();

                var thumbnails = new List <Thumbnail>();

                thumbnails.AddRange(Thumbnail.GetDefaultSet(id));

                foreach (var thumbnailExtractor in videoExtractor.GetVideoThumbnails())
                {
                    var thumbnailUrl =
                        thumbnailExtractor.TryGetUrl() ??
                        throw new YoutubeExplodeException("Could not extract thumbnail URL.");

                    var thumbnailWidth =
                        thumbnailExtractor.TryGetWidth() ??
                        throw new YoutubeExplodeException("Could not extract thumbnail width.");

                    var thumbnailHeight =
                        thumbnailExtractor.TryGetHeight() ??
                        throw new YoutubeExplodeException("Could not extract thumbnail height.");

                    var thumbnailResolution = new Resolution(thumbnailWidth, thumbnailHeight);
                    var thumbnail           = new Thumbnail(thumbnailUrl, thumbnailResolution);
                    thumbnails.Add(thumbnail);
                }

                var video = new VideoSearchResult(
                    id,
                    title,
                    new Author(channelId, channelTitle),
                    duration,
                    thumbnails
                    );

                results.Add(video);
            }

            foreach (var playlistExtractor in searchResults.GetPlaylists())
            {
                if (searchFilter is not SearchFilter.None and not SearchFilter.Playlist)
                {
                    Debug.Fail("Did not expect playlists in search results.");
                    break;
                }

                var id =
                    playlistExtractor.TryGetPlaylistId() ??
                    throw new YoutubeExplodeException("Could not extract playlist ID.");

                // Don't yield the same result twice
                if (!encounteredIds.Add(id))
                {
                    continue;
                }

                var title =
                    playlistExtractor.TryGetPlaylistTitle() ??
                    throw new YoutubeExplodeException("Could not extract playlist title.");

                // System playlists have no author
                var channelId    = playlistExtractor.TryGetPlaylistChannelId();
                var channelTitle = playlistExtractor.TryGetPlaylistAuthor();
                var author       = channelId is not null && channelTitle is not null
                    ? new Author(channelId, channelTitle)
                    : null;

                var thumbnails = new List <Thumbnail>();

                foreach (var thumbnailExtractor in playlistExtractor.GetPlaylistThumbnails())
                {
                    var thumbnailUrl =
                        thumbnailExtractor.TryGetUrl() ??
                        throw new YoutubeExplodeException("Could not extract thumbnail URL.");

                    var thumbnailWidth =
                        thumbnailExtractor.TryGetWidth() ??
                        throw new YoutubeExplodeException("Could not extract thumbnail width.");

                    var thumbnailHeight =
                        thumbnailExtractor.TryGetHeight() ??
                        throw new YoutubeExplodeException("Could not extract thumbnail height.");

                    var thumbnailResolution = new Resolution(thumbnailWidth, thumbnailHeight);
                    var thumbnail           = new Thumbnail(thumbnailUrl, thumbnailResolution);
                    thumbnails.Add(thumbnail);
                }

                var playlist = new PlaylistSearchResult(id, title, author, thumbnails);
                results.Add(playlist);
            }

            foreach (var channelExtractor in searchResults.GetChannels())
            {
                if (searchFilter is not SearchFilter.None and not SearchFilter.Channel)
                {
                    Debug.Fail("Did not expect channels in search results.");
                    break;
                }

                var channelId =
                    channelExtractor.TryGetChannelId() ??
                    throw new YoutubeExplodeException("Could not extract channel ID.");

                var title =
                    channelExtractor.TryGetChannelTitle() ??
                    throw new YoutubeExplodeException("Could not extract channel title.");

                var thumbnails = new List <Thumbnail>();

                foreach (var thumbnailExtractor in channelExtractor.GetChannelThumbnails())
                {
                    var thumbnailUrl =
                        thumbnailExtractor.TryGetUrl() ??
                        throw new YoutubeExplodeException("Could not extract thumbnail URL.");

                    var thumbnailWidth =
                        thumbnailExtractor.TryGetWidth() ??
                        throw new YoutubeExplodeException("Could not extract thumbnail width.");

                    var thumbnailHeight =
                        thumbnailExtractor.TryGetHeight() ??
                        throw new YoutubeExplodeException("Could not extract thumbnail height.");

                    var thumbnailResolution = new Resolution(thumbnailWidth, thumbnailHeight);
                    var thumbnail           = new Thumbnail(thumbnailUrl, thumbnailResolution);
                    thumbnails.Add(thumbnail);
                }

                var channel = new ChannelSearchResult(channelId, title, thumbnails);
                results.Add(channel);
            }

            yield return(Batch.Create(results));

            continuationToken = searchResults.TryGetContinuationToken();
        } while (!string.IsNullOrWhiteSpace(continuationToken));
    }