Example #1
0
    /// <summary>
    /// Gets the metadata associated with the specified video.
    /// </summary>
    public async ValueTask <Video> GetAsync(
        VideoId videoId,
        CancellationToken cancellationToken = default)
    {
        var watchPage = await _controller.GetVideoWatchPageAsync(videoId, cancellationToken);

        var playerResponse =
            watchPage.TryGetPlayerResponse() ??
            await _controller.GetPlayerResponseAsync(videoId, cancellationToken);

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

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

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

        var uploadDate =
            playerResponse.TryGetVideoUploadDate() ??
            throw new YoutubeExplodeException("Could not extract video upload date.");

        var description = playerResponse.TryGetVideoDescription() ?? "";
        var duration    = playerResponse.TryGetVideoDuration();

        var thumbnails = playerResponse
                         .GetVideoThumbnails()
                         .Select(t =>
        {
            var thumbnailUrl =
                t.TryGetUrl() ??
                throw new YoutubeExplodeException("Could not extract thumbnail URL.");

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

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

            var thumbnailResolution = new Resolution(thumbnailWidth, thumbnailHeight);

            return(new Thumbnail(thumbnailUrl, thumbnailResolution));
        })
                         .Concat(Thumbnail.GetDefaultSet(videoId))
                         .ToArray();

        var keywords = playerResponse.GetVideoKeywords();

        // Engagement statistics may be hidden
        var viewCount    = playerResponse.TryGetVideoViewCount() ?? 0;
        var likeCount    = watchPage.TryGetVideoLikeCount() ?? 0;
        var dislikeCount = watchPage.TryGetVideoDislikeCount() ?? 0;

        return(new Video(
                   videoId,
                   title,
                   new Author(channelId, channelTitle),
                   uploadDate,
                   description,
                   duration,
                   thumbnails,
                   keywords,
                   new Engagement(viewCount, likeCount, dislikeCount)
                   ));
    }