如何使用UserCredential revoke上传到youtube帐户特定帐户?

时间:2015-09-02 15:53:00

标签: c# .net google-api google-oauth google-api-dotnet-client

在我的课程中,我正在使用上传到youtube的视频文件,并且工作正常上传我想在表单设计器上创建一些东西,当我点击此按钮时,它将有一个gmail帐户的按钮做两件事:

  1. 将视频文件上传到此按钮的帐户。 例如,按钮上的文字是test@gmail.com
  2. 所以,当我点击按钮时,它会检查并且是否已经有一个用户连接到PC上的gmail帐户,如果它不是test@gmail.com,那么首先撤销然后连接到test@gmail.com并上传视频文件。

    但是如果PC上没有连接gmail帐户,那么用户将进入一个gmail帐户,它将连接到它并上传。

    1. 将撤销。
    2. 现在的问题是我有一个按钮,它所做的就是撤销。 我需要更改浏览器,在这种情况下chrome gmail帐户或登录到gmail帐户然后重新运行我的程序然后它将显示这个屏幕我需要接受该acocunt的授权然后它将上传它是视频文件。

      我想通过Chrome浏览器将每次登录的部分传递给另一个gmail,并且每次更改帐户时都需要重新接受。

      using System;
      using System.Collections.Generic;
      using System.ComponentModel;
      using System.Data;
      using System.Drawing;
      using System.Linq;
      using System.Text;
      using System.Threading.Tasks;
      using System.Windows.Forms;
      using Google.Apis.Auth.OAuth2;
      using Google.Apis.Auth.OAuth2.Flows;
      using Google.Apis.Services;
      using Google.Apis.Upload;
      using Google.Apis.Util.Store;
      using Google.Apis.YouTube.v3;
      using Google.Apis.YouTube.v3.Data;
      using Google.GData.Client;
      using Google.GData.Extensions;
      using System.Reflection;
      using System.IO;
      using System.Threading;
      using System.Net;
      using Google.Apis.YouTube;
      using Google.Apis.Requests;
      using Google.Apis.Gmail.v1.Data;
      using Google.Apis.Gmail.v1;
      using Google.Apis.Gmail;
      using MailBee;
      
      namespace test
      {
          public partial class testing : Form
          {
              public class ComboboxItem
              {
                  public string Text { get; set; }
                  public object Value { get; set; }
      
                  public override string ToString()
                  {
                      return Text;
                  }
              }
      
              YouTubeService service;
      
              string apiKey = "myapikey";
              string FileNameToUpload = "";
              string[] stringProgressReport = new string[5];
              long totalBytes = 0;
              DateTime dt;
              public static string fileuploadedsuccess = "";
      
              public Youtube_Uploader(string filetoupload)
              {
                  InitializeComponent();
      
                  FileNameToUpload = @"C:\Users\test\Videos\test.mp4";
                  service = AuthenticateOauth(apiKey);
                  var videoCatagories = service.VideoCategories.List("snippet");
                  videoCatagories.RegionCode = "IL";
                  var result = videoCatagories.Execute();
                  UserCredentials();
                  UserYoutubeService();
                  MakeRequest();
                  backgroundWorker1.RunWorkerAsync();
              }
      
              public static string uploadstatus = "";
              Video objects = null;
              private void videosInsertRequest_ResponseReceived(Video obj)
              {
                  System.Timers.Timer aTimer;
                  aTimer = new System.Timers.Timer();
                  aTimer.Elapsed += aTimer_Elapsed;
                  aTimer.Interval = 10000;
                  aTimer.Enabled = false;
                  uploadstatus = obj.Status.UploadStatus;
                  if (uploadstatus == "uploaded")
                  {
                      fileuploadedsuccess = "file uploaded successfully";
                  }
                  if (uploadstatus == "Completed")
                  {
                      fileuploadedsuccess = "completed";
                  }
                  objects = obj;
              }
      
              double mbSent = 0;
              int percentComplete = 0;
              VideoProcessingDetailsProcessingProgress vp = new VideoProcessingDetailsProcessingProgress();
              private void videosInsertRequest_ProgressChanged(IUploadProgress obj)
              {            
                  ulong? ul = vp.TimeLeftMs;
                  stringProgressReport[1] = obj.Status.ToString();
                  mbSent = ((double)obj.BytesSent) / (1 << 20);
                  stringProgressReport[2] = mbSent.ToString();
                  percentComplete = (int)Math.Round(((double)obj.BytesSent) / totalBytes * 100);
                  stringProgressReport[3] = percentComplete.ToString();
      
                  if (obj.BytesSent != 0)
                  {
                      var currentTime = DateTime.Now;
                      TimeSpan diff = currentTime - dt;
                      double diffSeconds = (DateTime.Now - dt).TotalSeconds;
                      double averageSpeed = obj.BytesSent / diffSeconds;
                      double MBunits = ConvertBytesToMegabytes((long)averageSpeed);
                      stringProgressReport[4] = string.Format("{0:f2} MB/s", MBunits);
                  }
              }
      
              public static YouTubeService AuthenticateOauth(string apiKey)
              {
                  try
                  {
                      YouTubeService service = new YouTubeService(new YouTubeService.Initializer()
                      {
                          ApiKey = apiKey,
                          ApplicationName = "YouTube Uploader",
                      });
                      return service;
                  }
                  catch (Exception ex)
                  {
                      Console.WriteLine(ex.InnerException);
                      return null;
                  }
              }
      
              private void MakeRequest()
              {
                  var searchListRequest = service.Search.List("snippet");
                  searchListRequest.Q = "daniel lipman gta"; // Replace with your search term.
                  searchListRequest.RegionCode = "IL";
                  searchListRequest.MaxResults = 50;
                  var searchListResponse = searchListRequest.Execute();
      
                  List<string> videos = new List<string>();
                  List<string> channels = new List<string>();
                  List<string> playlists = new List<string>();
      
                  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;
                      }
                  }
              }
      
              static Video video = new Video();
      
              public void Revoke()
              {
                  if (uc!=null)
                  {
                      uc.RevokeTokenAsync(CancellationToken.None);
                  }
      
              }
      
              UserCredential uc = null;
              private void UploadVideo(string FileName, string VideoTitle, string VideoDescription)
              {
                  try
                  {
                      var youtubeService = new YouTubeService(new BaseClientService.Initializer()
                      {
                          HttpClientInitializer = credential,
                          ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
                      });
      
                      video.Snippet = new VideoSnippet();
                      video.Snippet.Title = VideoTitle;
                      video.Snippet.Description = VideoDescription;
                      video.Snippet.Tags = new string[] { "tag1", "tag2" };
                      video.Status = new VideoStatus();
                      video.Status.PrivacyStatus = "public";
                      using (var fileStream = new FileStream(FileName, FileMode.Open))
                      {
      
                          const int KB = 0x400;
                          var minimumChunkSize = 256 * KB;
      
                          var videosInsertRequest = youtubeService.Videos.Insert(video,
                              "snippet,status", fileStream, "video/*");
                          videosInsertRequest.ProgressChanged +=
                              videosInsertRequest_ProgressChanged;
                          videosInsertRequest.ResponseReceived +=
                              videosInsertRequest_ResponseReceived;
                          // The default chunk size is 10MB, here will use 1MB.
                          videosInsertRequest.ChunkSize = minimumChunkSize * 3;
                          dt = DateTime.Now;
                          videosInsertRequest.Upload();
                      }
                  }
                  catch (Exception errors)
                  {
                      string errorss = errors.ToString();
                  }
              }
      
              static double ConvertBytesToMegabytes(long bytes)
              {
                  return (bytes / 1024f) / 1024f;
              }
      
              private void Youtube_Uploader_Load(object sender, EventArgs e)
              {
      
              }
      
              private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
              {
                  UploadVideo(FileNameToUpload, "test", "Testing");
              }
      
              private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
              {
      
              }
      
              private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
              {
      
              }
      
              private void timer1_Tick(object sender, EventArgs e)
              {
      
              }
      
              private void button1_Click(object sender, EventArgs e)
              {
                  Revoke();
              }
      
              UserCredential credential = null;
              private void UserCredentials()
              {
                  using (FileStream stream = new FileStream(@"C:\jason file\client_secrets.json", FileMode.Open, FileAccess.Read))
                  {
                      credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                          GoogleClientSecrets.Load(stream).Secrets,
                          new[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeUpload },
                          "user",
                          CancellationToken.None,
                          new FileDataStore("YouTube.Auth.Store")).Result;
                  }
                  uc = credential;
              }
      
              private void UserYoutubeService()
              {
                  var youtubeService = new YouTubeService(new BaseClientService.Initializer()
                  {
                      HttpClientInitializer = credential,
                      ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
                  });
              }
          }
      }
      

      在本课程中我有这一部分:

      private void button1_Click(object sender, EventArgs e)
              {
                  Revoke();
              }
      

      public void Revoke()
          {
              if (uc!=null)
              {
                  uc.RevokeTokenAsync(CancellationToken.None);
              }
      
          }
      

      用户凭证

      UserCredential credential = null;
              private void UserCredentials()
              {
                  using (FileStream stream = new FileStream(@"C:\jason file\client_secrets.json", FileMode.Open, FileAccess.Read))
                  {
                      credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                          GoogleClientSecrets.Load(stream).Secrets,
                          new[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeUpload },
                          "user",
                          CancellationToken.None,
                          new FileDataStore("YouTube.Auth.Store")).Result;
                  }
                  uc = credential;
              }
      

      问题是这个GoogleWebAuthorizationBroker会显示我每次撤销时都需要接受的屏幕。

      另外一个问题是,如果有任何用户已登录到gmail并获取gmail地址,如何使用GoogleWebAuthorizationBroker进行检查。

      然后决定是否撤销,以及如何使用GoogleWebAuthorizationBroker连接到Gmail帐户。

      我正在使用google api。

0 个答案:

没有答案