2016-04-07 42 views
0

Şirketimdeki youtube kanallarına yüklenen videolara altyazı eklerken sorun yaşıyorum. Google’ın Youtube Api v3’ünde .Net’le yapmak istiyorum. Videoları kanallara başarıyla yükleyebildim, ancak altyazı göndermeye çalışırken şu hatayı alıyorum: "System.Net.Http.HttpRequestException: Yanıt durumu kodu başarıyı göstermiyor: 403 (Yasak)."Youtube'da YoutubeApi v3 ile YouTube videolarına altyazı eklenir. Net

Anlatabildiğim kadarıyla, kimlik bilgilerim altyazı yüklememe izin vermez. Videoları sorunsuz bir şekilde yükleyebildim. Youtube API single-user scenario with OAuth (uploading videos)

Bu benim YouTubeService nesnesi oluşturmak için kullanıyorum kodudur: Burada

private YouTubeService GetYouTubeService() 
    { 
     string clientId = "clientId"; 
     string clientSecret = "clientSecret"; 
     string refreshToken = "refreshToken"; 
     try 
     { 
      ClientSecrets secrets = new ClientSecrets() 
      { 
       ClientId = clientId, 
       ClientSecret = clientSecret 
      }; 

      var token = new TokenResponse { RefreshToken = refreshToken }; 
      var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
       new GoogleAuthorizationCodeFlow.Initializer 
       { 
        ClientSecrets = secrets, 
        Scopes = new[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeUpload, YouTubeService.Scope.YoutubeForceSsl } 
       }), 
       "user", 
       token); 

      var service = new YouTubeService(new BaseClientService.Initializer() 
      { 
       HttpClientInitializer = credentials, 
       ApplicationName = "TestProject" 
      }); 

      service.HttpClient.Timeout = TimeSpan.FromSeconds(360); 
      return service; 
     } 
     catch (Exception ex) 
     { 
      Log.Error("YouTube.GetYouTubeService() => Could not get youtube service. Ex: " + ex); 
      return null; 
     } 

    } 

Ve I yüklemek için var kodu

Burada talimatları kullanarak yenileme jetonu yarattı altyazı dosyası:

private void UploadCaptionFile(String videoId) 
    { 
     try 
     { 
      Caption caption = new Caption(); 
      caption.Snippet = new CaptionSnippet(); 
      caption.Snippet.Name = videoId + "_Caption"; 
      caption.Snippet.Language = "en"; 
      caption.Snippet.VideoId = videoId; 
      caption.Snippet.IsDraft = false; 

      WebRequest req = WebRequest.Create(_urlCaptionPath); 
      using (Stream stream = req.GetResponse().GetResponseStream()) 
      { 
       CaptionsResource.InsertMediaUpload captionInsertRequest = _youtubeService.Captions.Insert(caption, "snippet", stream, "*/*"); 
       captionInsertRequest.Sync = true; 
       captionInsertRequest.ProgressChanged += captionInsertRequest_ProgressChanged; 
       captionInsertRequest.ResponseReceived += captionInsertRequest_ResponseReceived; 

       IUploadProgress result = captionInsertRequest.Upload(); 
      } 
     } 
     catch (Exception ex) 
     { 
      Log.Error("YouTube.UploadCaptionFile() => Unable to upload caption file. Ex: " + ex); 
     } 
    } 

    void captionInsertRequest_ResponseReceived(Caption obj) 
    { 
     Log.Info("YouTube.captionInsertRequest_ResponseReceived() => Caption ID " + obj.Id + " was successfully uploaded for this clip."); 
     Utility.UpdateClip(_videoClip); 
    } 

    void captionInsertRequest_ProgressChanged(IUploadProgress obj) 
    { 
     switch (obj.Status) 
     { 
      case UploadStatus.Uploading: 
       Console.WriteLine("{0} bytes sent.", obj.BytesSent); 
       break; 

      case UploadStatus.Failed: 
       Log.Error("YouTube.UploadCaptionFile() => An error prevented the upload from completing. " + obj.Exception); 
       break; 
     } 
    } 

Son birkaç gündür bu konu üzerinde çalıştım ve bunu yapamıyorum. e herhangi bir gelişme. YouTubeApi v3'ün altyazı eklemeyle ilgili fazla bilgisi yok. Tüm bulabildiğim, sahip olmadığım tuşları gerektiren bazı POST çağrıları gerektiren v2 için eski bazı bilgiler oldu. Bunu yapmak için API’nin yerleşik yöntemlerini kullanarak altyazıları ekleyebilmeyi isterim.

Bu sorunla ilgilenen herhangi biri varsa, sunabileceğin herhangi bir yardımı çok takdir ediyorum.

DÜZENLEME:

İşte YouTube'a video göndermek için benim kodudur.

public string UploadClipToYouTube() 
    { 
     try 
     { 
      var video = new Google.Apis.YouTube.v3.Data.Video(); 
      video.Snippet = new VideoSnippet(); 
      video.Snippet.Title = _videoClip.Name; 
      video.Snippet.Description = _videoClip.Description; 
      video.Snippet.Tags = GenerateTags(); 
      video.Snippet.DefaultAudioLanguage = "en"; 
      video.Snippet.DefaultLanguage = "en"; 
      video.Snippet.CategoryId = "22"; 
      video.Status = new VideoStatus(); 
      video.Status.PrivacyStatus = "unlisted"; 

      WebRequest req = WebRequest.Create(_videoPath); 
      using (Stream stream = req.GetResponse().GetResponseStream()) 
      { 
       VideosResource.InsertMediaUpload insertRequest = _youtubeService.Videos.Insert(video, "snippet, status", stream, "video/*"); 
       insertRequest.ProgressChanged += videosInsertRequest_ProgressChanged; 
       insertRequest.ResponseReceived += videosInsertRequest_ResponseReceived; 

       insertRequest.Upload(); 
      } 
      return UploadedVideoId; 
     } 
     catch (Exception ex) 
     { 
      Log.Error("YouTube.UploadClipToYoutube() => Error attempting to authenticate for YouTube. Ex: " + ex); 
      return ""; 
     } 
    } 

    void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress) 
    { 
     switch (progress.Status) 
     { 
      case UploadStatus.Uploading: 
       Log.Info("YouTube.videosInsertRequest_ProgressChanged() => Uploading to Youtube. " + progress.BytesSent + " bytes sent."); 
       break; 

      case UploadStatus.Failed: 
       Log.Error("YouTube.videosInsertRequest_ProgressChanged() => An error prevented the upload from completing. Exception: " + progress.Exception); 
       break; 
     } 
    } 

    void videosInsertRequest_ResponseReceived(Google.Apis.YouTube.v3.Data.Video video) 
    { 
     Log.Info("YouTube.videosInsertRequest_ResponseReceived() => Video was successfully uploaded to YouTube. The YouTube id is " + video.Id); 
     UploadedVideoId = video.Id; 
     UploadCaptionFile(video.Id); 
    } 
+0

Birkaç soru. Kimlik doğrulama ile ilgili olarak, yükleme ile aynı işlemi kullanıyor musunuz? * 403 yasak * hatasıyla (bu aşikar, ama bence de sormaya değer), Caption verileriniz [sınırlamalar] ile uyumludur (https://developers.google.com/youtube/v3/docs/captions/insert #istek). Ayrıca, bunu gördüm [benzer yazı] (http://stackoverflow.com/questions/31823160/uploading-captions-using-youtube-api-v3-dotnet-c-null-error-challenging), sadece fark Aldığı hata, kodlarını kontrol etmeye çalıştın mı? :) –

+0

Video yükleme işlemi, resim yazısı yükleme işlemiyle hemen hemen aynı. Orijinal yayımı kullanıyorum video yükleme işlemi ile güncelleyeceğim. Kimlik bilgilerini oluştururken kapsamlardan biri olarak "YouTubeService.Scope.YoutubeForceSsl" var, bu yüzden her şey kısıtlamalara uymalıdır. Benzer yazıya baktım; Aslında, repliers biri bu proje üzerinde çalışan ve o devraldı önce çalışan eski bir iş arkadaşıdır. Maalesef, gönderdiği kod çalışmıyor. – Chelsea

+1

@Chelsea Bu, 'v3' değil. Sürüm 3, Oauth için 'GoogleWebAuthorizationBroker' ve' FileDataStore' kullanır ... Ayrıca uygulamayı kilitlemeyi engelleyen 'bekle' ve 'uyumsuz' işlemleri kullanır. Yeni versiyonu muhtemelen eski versiyonlarla karıştırıyor musunuz? Ayrıca, isteğiniz için bir kullanıcı adı vermediğinizden şüpheliyim, bu hatalar için mümkün veya güvenlik nedenlerinden ötürü dışarıda bıraktınız ... – Codexer

cevap

1

Tamam, ben Java tercüme sizin için gerçekten hızlı bir şeyi (dürüst yaklaşık 15 dakika) kadar çırpılmış. Öncelikle mevcut kodunuzda fark ettiğim birkaç şey var, fakat bu CodeReview değil.

YouTubeApi v3'ün altyazı ekleme hakkında fazla bilgisi yoktur. Ben bulabildim Tüm ama umarım yakın gelecekte bazen, bu süre (v3) de değil, Bu konuda doğru v2

için bazı eski bilgiler oldu. api çok benzer gibi bu

Kod & bir örnek .srt dosya Bilmiyorsanız eğer İşte

private async Task addVideoCaption(string videoID) //pass your video id here.. 
     { 
      UserCredential credential; 
      //you should go out and get a json file that keeps your information... You can get that from the developers console... 
      using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read)) 
      { 
       credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
        GoogleClientSecrets.Load(stream).Secrets, 
        new[] { YouTubeService.Scope.YoutubeForceSsl, YouTubeService.Scope.Youtube, YouTubeService.Scope.Youtubepartner }, 
        "ACCOUNT NAME HERE", 
        CancellationToken.None, 
        new FileDataStore(this.GetType().ToString()) 
       ); 
      } 
      //creates the service... 
      var youtubeService = new Google.Apis.YouTube.v3.YouTubeService(new BaseClientService.Initializer() 
      { 
       HttpClientInitializer = credential, 
       ApplicationName = this.GetType().ToString(), 
      }); 

      //create a CaptionSnippet object... 
      CaptionSnippet capSnippet = new CaptionSnippet(); 
      capSnippet.Language = "en"; 
      capSnippet.Name = videoID + "_Caption"; 
      capSnippet.VideoId = videoID; 
      capSnippet.IsDraft = false; 

      //create new caption object 
      Caption caption = new Caption();  

      //set the completed snippet to the object now... 
      caption.Snippet = capSnippet; 

      //here we read our .srt which contains our subtitles/captions... 
      using (var fileStream = new FileStream("filepathhere", FileMode.Open)) 
      { 
       //create the request now and insert our params... 
       var captionRequest = youtubeService.Captions.Insert(caption, "snippet",fileStream,"application/atom+xml"); 

       //finally upload the request... and wait. 
       await captionRequest.UploadAsync(); 
      } 

     } 

Test çalıştı ... gerçi bizim için avantaj v2 değiştirmesini bizi durmuyor neye benziyor ya da nasıl biçimlendiriliyor.

1 
00:00:00,599 --> 00:00:03,160 
>> Caption Test [email protected] StackOverflow 

2 
00:00:03,160 --> 00:00:05,770 
>> If you're reading this it worked! 

YouTube Video Proof. Sadece çalıştığını ve neye benzediğini göstermek için yaklaşık 5 saniye kısa bir klip. VE...Hiçbir video değil maden, SADECE :)

İyi Şanslar ve Mutlu Programlama testi için kaptı!

+0

Çok teşekkür ederim! Programım şimdi çalışıyor! – Chelsea

+0

Hoşgeldiniz, yardımcı olabildiğime sevindim! kimlik = GoogleWebAuthorizationBroker.AuthorizeAsync beklemektedir ( GoogleClientSecrets.Load (akış) .Secrets, yeni [] {YouTubeService.Scope.YoutubeForceSsl, YouTubeService.Scope.Youtube, YouTubeService.Scope.Youtubepartner} "HESAP ADI burada: Bu bölüm, – Codexer

+0

" CancellationToken.None, new FileDataStore (this.GetType(). ToString()) ); –