Как создать список воспроизведения YouTube в приложении c# do tnet с помощью API YouTube? - PullRequest
0 голосов
/ 27 марта 2020

Я использую приложение ASP. NET MVC, и мне нужно добавить плейлист Youtube через YouTube API3.

Я хочу добавить плейлист в свой аккаунт YouTube через OAuth2.0 .

Пожалуйста, посмотрите мой пример ниже

using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;

using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Responses;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;

namespace Google.Apis.YouTube.Samples
{
  /// <summary>
  /// </summary>
  internal class PlaylistUpdates
  {
    [STAThread]
    static void Main(string[] args)
    {
      Console.WriteLine("YouTube Data API: Playlist Updates");
      Console.WriteLine("==================================");

      try
      {
        new PlaylistUpdates().Run().Wait();
      }
      catch (AggregateException ex)
      {
        foreach (var e in ex.InnerExceptions)
        {
          Console.WriteLine("Error: " + e.Message);
        }
      }

      Console.WriteLine("Press any key to continue...");
      Console.ReadKey();
    }

    private async Task Run()
    {
            UserCredential credential;           

            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
              credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                  GoogleClientSecrets.Load(stream).Secrets,
                  // This OAuth 2.0 access scope allows for full read/write access to the
                  // authenticated user's account.
                  new[] { YouTubeService.Scope.Youtube },
                  "user",
                  CancellationToken.None,
                  new FileDataStore(this.GetType().ToString())
              );
            }      
            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
              HttpClientInitializer = credential,
              ApplicationName = this.GetType().ToString()
            });            
            // Create a new, private playlist in the authorized user's channel.
            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 = await youtubeService.Playlists.Insert(newPlaylist, "snippet,status").ExecuteAsync();

      // Add a video to the newly created playlist.
      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 = await youtubeService.PlaylistItems.Insert(newPlaylistItem, "snippet").ExecuteAsync();

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

------------ client_secrets. json ----------- --------------------------

{
  "web": {
    "client_id": "yourClientId",
    "project_id": "myproject",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://oauth2.googleapis.com/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_secret": "Your Secret",
    "redirect_uris": [ "http://localhost:44373" ]
  }
}

Я новичок ie с API YouTube. Что мне делать в моем коде?

Я взял пример кода для меню и карт отсюда: https://github.com/youtube/api-samples/tree/master/dotnet

Приложение, построенное с

{
  "application type": "console application", 
  ".Net framework": "4.5"  ,
  "language" : C#
}

Проблема, с которой я сталкиваюсь, связана с ошибкой в ​​следующей функции:

using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
        {
          credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
              GoogleClientSecrets.Load(stream).Secrets,
              // This OAuth 2.0 access scope allows for full read/write access to the
              // authenticated user's account.
              new[] { YouTubeService.Scope.Youtube },
              "user",
              CancellationToken.None,
              new FileDataStore(this.GetType().ToString())
          );
        }   

Выше отображается ошибка ниже:

    400. That’s an error.

    Error: redirect_uri_mismatch
    The redirect URI in the request, http://127.0.0.1:1492/authorize/, does not match the ones authorized for the OAuth client. To update the authorized redirect URIs, visit: https://console.developers.google.com/apis/credentials/oauthclient/yourclientid.apps.googleusercontent.com?project=96215660321
    Learn more
    Request Details
    access_type=offline
response_type=code
client_id=96215660321-yourclientid.apps.googleusercontent.com
redirect_uri=http://127.0.0.1:1492/authorize/
scope=https://www.googleapis.com/auth/youtube

Я пытался следовать статьям Google и посмотрел примеры реализации, но не смог решить / объяснить проблему хорошо.

Более того, я добавил идентификаторы клиента OAuth 2.0 через Create Credentails и затем выбрал тип приложения в качестве веб-приложения.

Затем я добавил http://localhost: 44373 под URI авторизованного перенаправления и нажал кнопку сохранения

...