.NET Code Samples

Los siguientes ejemplos de código, que utilizan la Biblioteca cliente de API de Google para .NET, están disponibles para YouTube Data API.

Recuperar mis videos subidos

El siguiente ejemplo de código invoca el método playlistItems.list de la API para recuperar una lista de videos subidos en el canal asociado a la solicitud. El código también invoca el método channels.list con el parámetro mine establecido en true para recuperar el ID de lista de reproducción que identifica a los videos subidos del canal.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

/*
 * External dependencies, OAuth 2.0 support, and core client libraries are at:
 *   https://developers.google.com/api-client-library/dotnet/apis/
 * Also see the Samples.zip file for the Google.Apis.Samples.Helper classes at:
 *   https://github.com/youtube/api-samples/tree/master/dotnet
 */

using DotNetOpenAuth.OAuth2;

using Google.Apis.Authentication;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Samples.Helper;
using Google.Apis.Services;
using Google.Apis.Util;
using Google.Apis.Youtube.v3;
using Google.Apis.Youtube.v3.Data;

namespace dotnet
{
  class my_uploads
  {
    static void Main(string[] args)
    {
      CommandLine.EnableExceptionHandling();
      CommandLine.DisplayGoogleSampleHeader("YouTube Data API: My Uploads");

      var credentials = PromptingClientCredentials.EnsureFullClientCredentials();
      var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description)
      {
        ClientIdentifier = credentials.ClientId,
        ClientSecret = credentials.ClientSecret
      };
      var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);

      var youtube = new YoutubeService(new BaseClientService.Initializer()
      {
        Authenticator = auth
      });

      var channelsListRequest = youtube.Channels.List("contentDetails");
      channelsListRequest.Mine = true;

      var channelsListResponse = channelsListRequest.Fetch();

      foreach (var channel in channelsListResponse.Items)
      {
        var uploadsListId = channel.ContentDetails.RelatedPlaylists.Uploads;

        CommandLine.WriteLine(String.Format("Videos in list {0}", uploadsListId));

        var nextPageToken = "";
        while (nextPageToken != null)
        {
          var playlistItemsListRequest = youtube.PlaylistItems.List("snippet");
          playlistItemsListRequest.PlaylistId = uploadsListId;
          playlistItemsListRequest.MaxResults = 50;
          playlistItemsListRequest.PageToken = nextPageToken;

          var playlistItemsListResponse = playlistItemsListRequest.Fetch();

          foreach (var playlistItem in playlistItemsListResponse.Items)
          {
            CommandLine.WriteLine(String.Format("{0} ({1})", playlistItem.Snippet.Title, playlistItem.Snippet.ResourceId.VideoId));
          }

          nextPageToken = playlistItemsListResponse.NextPageToken;
        }
      }

      CommandLine.PressAnyKeyToExit();
    }

    private static IAuthorizationState GetAuthorization(NativeApplicationClient client)
    {
      var storage = MethodBase.GetCurrentMethod().DeclaringType.ToString();
      var key = "storage_key";

      IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(storage, key);
      if (state != null)
      {
        client.RefreshToken(state);
      }
      else
      {
        state = AuthorizationMgr.RequestNativeAuthorization(client, YoutubeService.Scopes.YoutubeReadonly.GetStringValue());
        AuthorizationMgr.SetCachedRefreshToken(storage, key, state);
      }

      return state;
    }
  }
}

Crear una lista de reproducción

El siguiente ejemplo de código invoca el método playlists.insert de la API para crear una lista de reproducción privada perteneciente al canal que autoriza la solicitud.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

/*
 * External dependencies, OAuth 2.0 support, and core client libraries are at:
 *   https://developers.google.com/api-client-library/dotnet/apis/
 * Also see the Samples.zip file for the Google.Apis.Samples.Helper classes at:
 *   https://github.com/youtube/api-samples/tree/master/dotnet
 */

using DotNetOpenAuth.OAuth2;

using Google.Apis.Authentication;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Samples.Helper;
using Google.Apis.Services;
using Google.Apis.Util;
using Google.Apis.Youtube.v3;
using Google.Apis.Youtube.v3.Data;

namespace dotnet
{
  class playlist_updates
  {
    static void Main(string[] args)
    {
      CommandLine.EnableExceptionHandling();
      CommandLine.DisplayGoogleSampleHeader("YouTube Data API: Playlist Updates");

      var credentials = PromptingClientCredentials.EnsureFullClientCredentials();
      var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description)
      {
        ClientIdentifier = credentials.ClientId,
        ClientSecret = credentials.ClientSecret
      };
      var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);

      var youtube = new YoutubeService(new BaseClientService.Initializer()
      {
        Authenticator = auth
      });

      var newPlaylist = new Playlist();
      newPlaylist.Snippet = new PlaylistSnippet();
      newPlaylist.Snippet.Title = "Test Playlist";
      newPlaylist.Snippet.Description = "A playlist created with the YouTube API v3";
      newPlaylist.Status = new PlaylistStatus();
      newPlaylist.Status.PrivacyStatus = "public";
      newPlaylist = youtube.Playlists.Insert(newPlaylist, "snippet,status").Fetch();

      var newPlaylistItem = new PlaylistItem();
      newPlaylistItem.Snippet = new PlaylistItemSnippet();
      newPlaylistItem.Snippet.PlaylistId = newPlaylist.Id;
      newPlaylistItem.Snippet.ResourceId = new ResourceId();
      newPlaylistItem.Snippet.ResourceId.Kind = "youtube#video";
      newPlaylistItem.Snippet.ResourceId.VideoId = "GNRMeaz6QRI";
      newPlaylistItem = youtube.PlaylistItems.Insert(newPlaylistItem, "snippet").Fetch();

      CommandLine.WriteLine(String.Format("Playlist item id {0} was added to playlist id {1}.", newPlaylistItem.Id, newPlaylist.Id));

      CommandLine.PressAnyKeyToExit();
    }

    private static IAuthorizationState GetAuthorization(NativeApplicationClient client)
    {
      var storage = MethodBase.GetCurrentMethod().DeclaringType.ToString();
      var key = "storage_key";

      IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(storage, key);
      if (state != null)
      {
        client.RefreshToken(state);
      }
      else
      {
        state = AuthorizationMgr.RequestNativeAuthorization(client, YoutubeService.Scopes.Youtube.GetStringValue());
        AuthorizationMgr.SetCachedRefreshToken(storage, key, state);
      }

      return state;
    }
  }
}

Buscar por palabra clave

El siguiente ejemplo de código invoca el método search.list de la API para recuperar los resultados de búsqueda relacionados con una palabra clave determinada.

using System;
using System.Collections;
using System.Collections.Generic;

/*
 * External dependencies, OAuth 2.0 support, and core client libraries are at:
 *   https://developers.google.com/api-client-library/dotnet/apis/
 * Also see the Samples.zip file for the Google.Apis.Samples.Helper classes at:
 *   https://github.com/youtube/api-samples/tree/master/dotnet
 */

using Google.Apis.Samples.Helper;
using Google.Apis.Services;
using Google.Apis.Youtube.v3;
using Google.Apis.Youtube.v3.Data;

namespace dotnet
{
  class search
  {
    static void Main(string[] args)
    {
      CommandLine.EnableExceptionHandling();
      CommandLine.DisplayGoogleSampleHeader("YouTube Data API: Search");

      SimpleClientCredentials credentials = PromptingClientCredentials.EnsureSimpleClientCredentials();

      YoutubeService youtube = new YoutubeService(new BaseClientService.Initializer() {
        ApiKey = credentials.ApiKey
      });

      SearchResource.ListRequest listRequest = youtube.Search.List("snippet");
      listRequest.Q = CommandLine.RequestUserInput<string>("Search term: ");
      listRequest.Order = SearchResource.Order.Relevance;

      SearchListResponse searchResponse = listRequest.Fetch();

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

      foreach (SearchResult searchResult in searchResponse.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;
        }
      }

      CommandLine.WriteLine(String.Format("Videos:\n{0}\n", String.Join("\n", videos.ToArray())));
      CommandLine.WriteLine(String.Format("Channels:\n{0}\n", String.Join("\n", channels.ToArray())));
      CommandLine.WriteLine(String.Format("Playlists:\n{0}\n", String.Join("\n", playlists.ToArray())));

      CommandLine.PressAnyKeyToExit();
    }
  }
}

Subir un video

El siguiente ejemplo de código invoca el método videos.insert de la API para subir un video en el canal asociado a la solicitud.

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;

/*
 * External dependencies, OAuth 2.0 support, and core client libraries are at:
 *   https://developers.google.com/api-client-library/dotnet/apis/
 * Also see the Samples.zip file for the Google.Apis.Samples.Helper classes at:
 *   https://github.com/youtube/api-samples/tree/master/dotnet
 */

using DotNetOpenAuth.OAuth2;

using Google.Apis.Authentication;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Samples.Helper;
using Google.Apis.Services;
using Google.Apis.Util;
using Google.Apis.Youtube.v3;
using Google.Apis.Youtube.v3.Data;

namespace dotnet
{
  class upload_video
  {
    static void Main(string[] args)
    {
      CommandLine.EnableExceptionHandling();
      CommandLine.DisplayGoogleSampleHeader("YouTube Data API: Upload Video");

      var credentials = PromptingClientCredentials.EnsureFullClientCredentials();
      var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description)
      {
        ClientIdentifier = credentials.ClientId,
        ClientSecret = credentials.ClientSecret
      };
      var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);

      var youtube = new YoutubeService(new BaseClientService.Initializer()
      {
        Authenticator = auth
      });

      var video = new Video();
      video.Snippet = new VideoSnippet();
      video.Snippet.Title = CommandLine.RequestUserInput<string>("Video title");
      video.Snippet.Description = CommandLine.RequestUserInput<string>("Video description");
      video.Snippet.Tags = new string[] { "tag1", "tag2" };
      // See https://developers.google.com/youtube/v3/docs/videoCategories/list
      video.Snippet.CategoryId = "22";
      video.Status = new VideoStatus();
      video.Status.PrivacyStatus = CommandLine.RequestUserInput<string>("Video privacy (public, private, or unlisted)");
      var filePath = CommandLine.RequestUserInput<string>("Path to local video file");
      var fileStream = new FileStream(filePath, FileMode.Open);

      var videosInsertRequest = youtube.Videos.Insert(video, "snippet,status", fileStream, "video/*");
      videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
      videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

      var uploadThread = new Thread(() => videosInsertRequest.Upload());
      uploadThread.Start();
      uploadThread.Join();

      CommandLine.PressAnyKeyToExit();
    }

    static void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress obj)
    {
      CommandLine.WriteLine(String.Format("{0} bytes sent.", obj.BytesSent));
    }

    static void videosInsertRequest_ResponseReceived(Video obj)
    {
      CommandLine.WriteLine(String.Format("Video id {0} was successfully uploaded.", obj.Id));
    }

    private static IAuthorizationState GetAuthorization(NativeApplicationClient client)
    {
      var storage = MethodBase.GetCurrentMethod().DeclaringType.ToString();
      var key = "storage_key";

      IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(storage, key);
      if (state != null)
      {
        client.RefreshToken(state);
      }
      else
      {
        state = AuthorizationMgr.RequestNativeAuthorization(client, YoutubeService.Scopes.YoutubeUpload.GetStringValue());
        AuthorizationMgr.SetCachedRefreshToken(storage, key, state);
      }

      return state;
    }
  }
}