Как загрузить видео из моей учетной записи Gmail и приложения ASP. NET MVC 5 без какого-либо разрешения (например, OAuth2.0)? - PullRequest
0 голосов
/ 03 апреля 2020

Я использую приложение ASP. NET MVC, и мне нужно добавить Youtube видео через YouTube YouTube API. Я хочу добавить прямые видео YouTube (из клиентского веб-браузера в мою учетную запись YouTube) из моей учетной записи Google, и это будет исправлено. Я не хочу сначала загружать на свой сервер развертывания, а затем загружать с моего сервера ресурсы / жесткие диски.

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

using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;    
using Google.Apis.Auth.OAuth2;
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
{     
  public class UploadVideoController
  {

    public ActionResult SaveYoutubeVideo(string videoPath)
    {    
      try
      {
        Run(videoPath).Wait();
      }
      catch (AggregateException ex)
      {
        foreach (var e in ex.InnerExceptions)
        {
          Console.WriteLine("Error: " + e.Message);
        }
      }
   }         

    private async Task Run(string videoPath)
    {
      UserCredential credential;
      using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
      {
        credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(stream).Secrets,        
            new[] { YouTubeService.Scope.YoutubeUpload },
            "user",
            CancellationToken.None
        );
      }
      var youtubeService = new YouTubeService(new BaseClientService.Initializer()
      {
        HttpClientInitializer = credential,
        ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
      });

      var video = new Video();
      video.Snippet = new VideoSnippet();
      video.Snippet.Title = "Default Video Title";
      video.Snippet.Description = "Default Video Description";
      video.Snippet.Tags = new string[] { "tag1", "tag2" };
      video.Snippet.CategoryId = "22"; 
      video.Status = new VideoStatus();
      video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
      var filePath = videoPath; // Replace with path to actual movie file.

      using (var fileStream = new FileStream(filePath, FileMode.Open))
      {
        var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
        videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
        videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

        await videosInsertRequest.UploadAsync();
      }
    }

    void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
    {
      switch (progress.Status)
      {
        case UploadStatus.Uploading:
          Console.WriteLine("{0} bytes sent.", progress.BytesSent);
          break;

        case UploadStatus.Failed:
          Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
          break;
      }
    }

    void videosInsertRequest_ResponseReceived(Video video)
    {
      Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
    }
  }
}


----------- client_secrets.json-------------------------------------
    {
      "installed": {
        "client_id": "Your Client Id",
        "client_secret": "your secret",
        "redirect_uri": "urn:ietf:wg:oauth:2.0:oob",
        "access_type": "offline",
        "approval_prompt": "force"
      }
    } 

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

Application built with
{
  "application type": "ASP.NET MVC 5", 
  ".Net framework": "4.5"  ,
  "language" : C#
}

Первая проблема заключается в том, что мне нужно использовать свой собственный аккаунт Google, который не должен ничего разрешать. Для этой первой проблемы, что я могу сделать?

Вторая проблема упоминается ниже и менее важна, и я использую OAuth2.0.

 This app isn't verified
    This app hasn't been verified by Google yet. Only proceed if you know and trust the developer.
    If you’re the developer, submit a verification request to remove this screen. Learn more
    Hide Advanced

    Back to safety
    Google hasn't reviewed this app yet and can't confirm it's authentic. Unverified apps may pose a threat to your personal data. Learn more
    Go to TestVideoRequest (unsafe)

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

...