J'utilise YouTube API V3 dans une application Web MVC. L'objectif est que mes utilisateurs Web téléchargent une vidéo sur ma chaîne YouTube en utilisant les informations d'identification MY OAuth. Une fois que l'utilisateur a téléchargé sa vidéo sur mon serveur Web, le téléchargement entre mon serveur Web et YouTube doit être automatisé sans aucune intervention de l'utilisateur.YouTube API v3, C# MVC - Envoyer la vidéo sur MY channel avec OAuth
Mon code (premier brouillon) est ci-dessous. Mes questions sont les suivantes:
MISE À JOUR - Résolu ci-dessous. Chaque fois que j'essaie de supprimer une vidéo, je reçois une erreur «non autorisée». Quand je vérifie la portée du jeton, il n'a que 'YoutubeUpload' et pas 'Youtube'. Y-a-t-il une façon de résoudre ceci?
J'ai créé un diplôme client OAuth de type 'Autre' et exporté le JSON (I spécifié 'Autre' au lieu de 'Application Web' - ce correct?): https://console.developers.google.com/apis/credentials
Lorsque je tente et télécharger une vidéo, je suis redirigé vers 'Autoriser l'application' en disant "Ma société veut accéder à votre chaîne YouTube." Le problème est, je ne veux pas accéder à la chaîne de quelqu'un. Je veux juste qu'ils soient en mesure de télécharger sur ma chaîne. Est-ce possible, et si oui comment?
public async Task<string> UploadVideoToYouTube(Stream filestream)
{
UserCredential credential;
string cs = HttpContext.Current.Server.MapPath("~/client_secrets.json");
using (var stream = new FileStream(cs, FileMode.Open, FileAccess.Read))
{
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.Youtube,
YouTubeService.Scope.YoutubeUpload },
"user",
CancellationToken.None
);
}
//check scope with this URL
//https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={ACCESS-TOKEN}
// This bit checks if the token is out of date,
// and refreshes the access token using the refresh token.
if (credential.Token.IsExpired(SystemClock.Default))
{
if (!await credential.RefreshTokenAsync(CancellationToken.None))
{
Console.WriteLine("No valid refresh token.");
}
}
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" };
//https://gist.github.com/dgp/1b24bf2961521bd75d6c
//26 - How-to & Style
video.Snippet.CategoryId = "26"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
video.Status = new VideoStatus();
video.Status.PrivacyStatus = "private"; // "unlisted" or "private" or "public"
var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", filestream, "video/*");
videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;
await videosInsertRequest.UploadAsync();
return videosInsertRequest.ResponseBody.Id;
}
void videosInsertRequest_ResponseReceived(Video video)
{
//http://www.youtube.com/watch?v={VIDEO-ID}
Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
}
public async Task DeleteVideoFromYouTube(string id)
{
UserCredential credential;
string cs = HttpContext.Current.Server.MapPath("~/client_secrets.json");
using (var stream = new FileStream(cs, FileMode.Open, FileAccess.Read))
{
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.Youtube,
YouTubeService.Scope.YoutubeUpload },
"user",
CancellationToken.None
);
}
// This bit checks if the token is out of date,
// and refreshes the access token using the refresh token.
if (credential.Token.IsExpired(SystemClock.Default))
{
if (!await credential.RefreshTokenAsync(CancellationToken.None))
{
Console.WriteLine("No valid refresh token.");
}
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
});
var videosDeleteRequest = youtubeService.Videos.Delete(id);
await videosDeleteRequest.ExecuteAsync();
}
void videosInsertRequest_ProgressChanged(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;
}
}
MISE À JOUR Résolution à la première question était d'aller ici: https://myaccount.google.com/permissions et supprimer l'application YouTube autorisée. Il doit avoir été autorisé auparavant sans la portée YouTubeService.Scope.Youtube. Cependant, lorsque j'ai supprimé le compte et réexécuté mon application Web, il m'a incité à m'authentifier à nouveau à l'aide de OAuth. Je ne le veux pas faire ça. Je veux l'authentifier automatiquement comme moi (pour tous les utilisateurs). Quelle est ma deuxième question qui reste sans réponse ....
Avez-vous obtenu la réponse? – sachin