googleapis/google-api-ruby-client

YouTube Data API v3 insert captions not working

ekortright opened this issue · 2 comments

No matter what I do, the YouTubeService object always comes back with an error when I call the insert_caption method:

Google::Apis::ClientError (invalidMetadata: The request contains invalid metadata values, which prevent the track from being created. Confirm that the request specifies valid values for the snippet.language, snippet.name, and snippet.videoId properties. The snippet.isDraft property can also be included, but it is not required.)

I've modeled the snippet from examples in other languages, and there's not much room for mistakes for this particular method. Other methods work fine, including insert_video, delete_video and set_thumbnail.

Here is the code I am using to insert a caption:

require 'googleauth'
require 'googleauth/stores/file_token_store'
require 'google-apis-youtube_v3'

REDIRECT_URI = 'http://localhost'
APPLICATION_NAME = '...'
API_KEY = '...'

SCOPE = Google::Apis::YoutubeV3::AUTH_YOUTUBE_FORCE_SSL

def authorize
  client_id = Google::Auth::ClientId.from_file('secrets/client_secret.json')
  token_store = Google::Auth::Stores::FileTokenStore.new(file: "secrets/youtube-creds.yml")
  authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)
  user_id = 'default'
  credentials = authorizer.get_credentials(user_id)
  if credentials.nil?
    url = authorizer.get_authorization_url(base_url: REDIRECT_URI)
    puts "Open the following URL in the browser and enter the resulting code after authorization"
    puts url
    code = gets
    credentials = authorizer.get_and_store_credentials_from_code(user_id: user_id, code: code, base_url: REDIRECT_URI)
  end
  credentials
end

def get_service
  service = Google::Apis::YoutubeV3::YouTubeService.new
  service.key = API_KEY
  service.client_options.application_name = APPLICATION_NAME
  service.authorization = authorize
  service
end

o = {
      "snippet": {
        "videoId": 'XYZ123',
        "language": 'en',
        "name": 'English'
      }
}

s = get_service
resp = s.insert_caption('snippet', o, upload_source: 'captions.vtt', content_type: 'text/vtt')

Any pointers as to what I'm doing wrong would be appreciated.

Forgot to mention that I'm using version 0.22.0 of the google-apis-youtube_v3 gem.

Argh! I just figured it out. . . .

Apparently the snippet in Ruby must follow Ruby variable naming conventions, so "videoId" has to be passed in as "video_id". That seems to have worked. The captions are not showing up on the video (yet), but at least I don't get an error when calling the API.