使用客户端登录将视频上传到YouTube时。第一次重定向到UI以获取权限。
我想上传而不重定向到网页。我需要在服务器上执行此代码。
这是我的代码。
private async Task<string> Run(string title, string description, string filepath)
{
var videoID = string.Empty;
try
{
logger.Info(string.Format("[uploading file on youTube Title: {0}, Description: {1}, filePath: {2}]", title, description, filepath));
UserCredential credential;
using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
logger.Info("[Load credentials from google start]");
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
// This OAuth 2.0 access scope allows an application to upload files to the
// authenticated user's YouTube channel, but doesn't allow other types of access.
new[] { YouTubeService.Scope.YoutubeUpload },
"user",
CancellationToken.None
);
logger.Info("[Load credentials from google end]");
}
logger.Info("YouTubeApiKey {0}", System.Configuration.ConfigurationManager.AppSettings["YoutubeApiKey"]);
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApiKey = System.Configuration.ConfigurationManager.AppSettings["YoutubeApiKey"],
ApplicationName = System.Configuration.ConfigurationManager.AppSettings["ApplicationName"]
});
logger.Info("ApplicationName {0}", System.Configuration.ConfigurationManager.AppSettings["ApplicationName"]);
var video = new Video();
video.Snippet = new VideoSnippet();
video.Snippet.Title = title;
video.Snippet.Description = description;
//video.Snippet.Tags = new string[] { "tag1", "tag2" };
// video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
video.Status = new VideoStatus();
video.Status.PrivacyStatus = "public"; // or "private" or "public"
var filePath = filepath; // 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();
}
return videoID;
}
catch (Exception e)
{
logger.ErrorException("[Error occurred in Run ]", e);
}
return videoID;
}
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);
}
答案 0 :(得分:0)
您的代码正在做的就是正确地完成所有事情。 YouTube API不允许纯服务器身份验证(服务帐户)。您可以上传文件的唯一选择是使用Oauth2并在第一次验证您的代码。
我只是夸大你做一个小改变添加filedatastore。这将为您存储身份验证。通过Web浏览器对其进行身份验证后,您无需再次执行此操作。
/// <summary>
/// Authenticate to Google Using Oauth2
/// Documentation https://developers.google.com/accounts/docs/OAuth2
/// </summary>
/// <param name="clientId">From Google Developer console https://console.developers.google.com</param>
/// <param name="clientSecret">From Google Developer console https://console.developers.google.com</param>
/// <param name="userName">A string used to identify a user.</param>
/// <returns></returns>
public static YouTubeService AuthenticateOauth(string clientId, string clientSecret, string userName)
{
string[] scopes = new string[] { YouTubeService.Scope.Youtube, // view and manage your YouTube account
YouTubeService.Scope.YoutubeForceSsl,
YouTubeService.Scope.Youtubepartner,
YouTubeService.Scope.YoutubepartnerChannelAudit,
YouTubeService.Scope.YoutubeReadonly,
YouTubeService.Scope.YoutubeUpload};
try
{
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
, scopes
, userName
, CancellationToken.None
, new FileDataStore("Daimto.YouTube.Auth.Store")).Result;
YouTubeService service = new YouTubeService(new YouTubeService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "YouTube Data API Sample",
});
return service;
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException);
return null;
}
}
像这样调用上面的方法:
// Authenticate Oauth2
String CLIENT_ID = "xxxxxx-d0vpdthl4ms0soutcrpe036ckqn7rfpn.apps.googleusercontent.com";
String CLIENT_SECRET = "NDmluNfTgUk6wgmy7cFo64RV";
var service = Authentication.AuthenticateOauth(CLIENT_ID, CLIENT_SECRET, "SingleUser");
您的代码需要首次进行身份验证。一旦其经过身份验证的filedatastore将文件存储在您计算机上的%appData%中。每次运行之后,它将使用存储在%appData%中的刷新令牌再次获得访问权限。