Jump to content

Como ler metadados de vídeos publicados no youtube


Recommended Posts

Posted (edited)

Boas,

 

Criei uma aplicação em .Net Core com Blazor, em que um dos requisitos é o de ler metadados de vídeos alojados no youtube. Ao inserir o link de um vídeo numa caixa de texto, o form com o resto dados é preenchido com:

  • Ano de edição
  • Título do vídeo
  • Título do canal
  • Duração
  • Descrição
  • Thumbnail

Fica aqui o código, caso alguém esteja interessado; foi adaptado a partir de trechos de código que encontrei na net. Se merecer algum comentário da vossa parte, façam-no!

Caso estejam interessados no form onde os dados são usados, enviem-me o pedido através de uma MP. 

 

Cumprimentos, 

Fausto


    == MODELOS ==
    

    public class YouTubeVideoDetails
    {
        public string VideoId { get; set; }
        public string Description { get; set; }
        public string Title { get; set; }
        public string ChannelTitle { get; set; }
        public string Duration { get; set; }
        public DateTime? PublicationDate { get; set; }
        public string Thumbnail { get; set; }
    }

    public static class Keys
    {
        public static string YouTubeApiKey = "<Chave da API>";
        public static string YouTubeApplicationName = "MediaOrganizer";
        public static string ClientId = "<Id do cliente>";
        public static string SecretClientId = "<chave secreta>";
        
    }
    
        
    using Google.Apis.Services;
    using Google.Apis.YouTube.v3;
    using MediaOrganizerApp.Domain.Entities;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Web.Blazor.Static;

	== Interface para injeção de dependências ==
      
    public interface IGetYoutubeVideoMetadata
    {
        Task<YouTubeVideoDetails> GetAlbumArtistMetadata(string searchRequest_query);
        Task<YouTubeVideoDetails> GetSingleVideoMetadata(string searchRequest_query);
        Task<YouTubeVideoDetails> GetVideoMetadata(string searchRequest_Id);
    }

    == Implementação ==
    
    public class GetYoutubeVideoMetadata : IGetYoutubeVideoMetadata
    {
        public async Task<YouTubeVideoDetails> GetVideoMetadata(string searchRequest_Id)
        {
            using (var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey = Keys.YouTubeApiKey,
                ApplicationName = Keys.YouTubeApplicationName,
            }))
            {
                var searchRequest = youtubeService.Videos.List("snippet,contentDetails");
                searchRequest.Id = searchRequest_Id;

                var searchResponse = await searchRequest.ExecuteAsync();
                var youTubeVideo = searchResponse.Items.FirstOrDefault();

                if (youTubeVideo != null)
                {
                    TimeSpan YouTubeDuration = System.Xml.XmlConvert.ToTimeSpan(youTubeVideo.ContentDetails.Duration);
                    string sDuration = YouTubeDuration.ToString();

                    YouTubeVideoDetails videoDetails = new YouTubeVideoDetails()
                    {
                        VideoId = youTubeVideo.Id,
                        Description = youTubeVideo.Snippet.Description,
                        Title = youTubeVideo.Snippet.Title,
                        ChannelTitle = youTubeVideo.Snippet.ChannelTitle,
                        PublicationDate = youTubeVideo.Snippet.PublishedAt,
                        Duration = sDuration,
                        Thumbnail = youTubeVideo.Snippet.Thumbnails.Standard is not null ?
                            youTubeVideo.Snippet.Thumbnails.Standard.Url :
                            youTubeVideo.Snippet.Thumbnails.Medium is not null ?
                            youTubeVideo.Snippet.Thumbnails.Medium.Url :
                            youTubeVideo.Snippet.Thumbnails.Maxres is not null ?
                            youTubeVideo.Snippet.Thumbnails.Maxres.Url : "Images/No-image-available.png"
                    };
                    return videoDetails;
                }

                return null;
            }
        }

        public async Task<YouTubeVideoDetails> GetAlbumArtistMetadata(string searchRequest_query)
        {
            using (var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey = Keys.YouTubeApiKey,
                ApplicationName = Keys.YouTubeApplicationName

            }))
            {
                var searchListRequest = youtubeService.Search.List("snippet");
                searchListRequest.Q = searchRequest_query;
                searchListRequest.MaxResults = 10;

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

                var searchListResponse = await searchListRequest.ExecuteAsync();

                // Adiciona cada resultado à lista apropriada e, em seguida, 
                // exibe as listas de vídeos, canais e listas de reprodução correspondentes.
                foreach (var searchResult in searchListResponse.Items)
                {
                    switch (searchResult.Id.Kind)
                    {
                        case "youtube#video":
                            videos.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.VideoId));
                            break;

                        case "youtube#channel":
                            channels.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.ChannelId));
                            break;

                        case "youtube#playlist":
                            playlists.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.PlaylistId));
                            break;
                    }
                }

                var youTubeVideo = searchListResponse.Items.FirstOrDefault();
                YouTubeVideoDetails videoDetails = new YouTubeVideoDetails()
                {
                    VideoId = youTubeVideo.Id.VideoId,
                    Description = youTubeVideo.Snippet.Description,
                    Title = youTubeVideo.Snippet.Title,
                    ChannelTitle = youTubeVideo.Snippet.ChannelTitle,
                    PublicationDate = youTubeVideo.Snippet.PublishedAt,
                    Thumbnail = youTubeVideo.Snippet.Thumbnails.Standard is not null ?
                                youTubeVideo.Snippet.Thumbnails.Standard.Url :
                                youTubeVideo.Snippet.Thumbnails.Medium is not null ?
                                youTubeVideo.Snippet.Thumbnails.Medium.Url :
                                youTubeVideo.Snippet.Thumbnails.Maxres is not null ?
                                youTubeVideo.Snippet.Thumbnails.Maxres.Url : "Images/No-image-available.png"
                };

                return videoDetails;

            }
        }

        public async Task<YouTubeVideoDetails> GetSingleVideoMetadata(string searchRequest_query)
        {
            try
            {
                using (var YouTubeService = new YouTubeService(new BaseClientService.Initializer()
                {
                    ApiKey = Keys.YouTubeApiKey,
                    ApplicationName = Keys.YouTubeApplicationName

                }))
                {
                    var searchListRequest = YouTubeService.Videos.List("snippet");
                    searchListRequest.Id = searchRequest_query;
                    searchListRequest.MaxResults = 1;

                    var searchListResponse = await searchListRequest.ExecuteAsync();

                    var youTubeVideo = searchListResponse.Items.FirstOrDefault(); // redundante ? (MaxResults = 1...)
                    if (youTubeVideo is not null)
                    {
                        YouTubeVideoDetails videoDetail = new YouTubeVideoDetails()
                        {
                            VideoId = youTubeVideo.Id,
                            Description = youTubeVideo.Snippet.Description,
                            Title = youTubeVideo.Snippet.Title,
                            ChannelTitle = youTubeVideo.Snippet.ChannelTitle,
                            PublicationDate = youTubeVideo.Snippet.PublishedAt,
                            Thumbnail = youTubeVideo.Snippet.Thumbnails.Standard is not null ?
                                        youTubeVideo.Snippet.Thumbnails.Standard.Url :
                                        youTubeVideo.Snippet.Thumbnails.Medium is not null ?
                                        youTubeVideo.Snippet.Thumbnails.Medium.Url :
                                        youTubeVideo.Snippet.Thumbnails.Maxres is not null ?
                                        youTubeVideo.Snippet.Thumbnails.Maxres.Url : "Images/No-image-available.png"
                        };

                        return videoDetail;
                    }
                    else
                        return null;

                }

            }
            catch
            {

                throw;
            }
        }
    }
Edited by Fausto Luís

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.