Sha256: b1a0c253b7b176e96c5650e9d2b3468d8ddc19aa08055abfd3e3767363b87d73

Contents?: true

Size: 1.73 KB

Versions: 1

Compression:

Stored size: 1.73 KB

Contents

require "http"

module Brightcove
  class Cmsapi
    OAUTH_ENDPOINT = "https://oauth.brightcove.com/v4/access_token"
    API_ROOT = "https://cms.api.brightcove.com/v1/accounts"

    def initialize(account_id:, client_id:, client_secret:)
      @base_url = "#{API_ROOT}/#{account_id}"
      @client_id = client_id
      @client_secret = client_secret
      set_token
    end

    def self.default_api
      @default_api ||= new(
        account_id: ENV['BRIGHTCOVE_ACCOUNT_ID'],
        client_id: ENV['BRIGHTCOVE_CLIENT_ID'],
        client_secret: ENV['BRIGHTCOVE_CLIENT_SECRET'])
    end

    def get(path)
      set_token if @token_expires < Time.now
      response = HTTP.auth("Bearer #{@token}").get("#{@base_url}/#{path}")

      if response.code == 401 # Unauthorized, token expired
        set_token
        HTTP.auth("Bearer #{@token}").get("#{@base_url}/#{path}")
      else
        response
      end
    end

    def get_all(path="", resource)
      if path.empty?
        count = get("counts/#{resource}s").parse.fetch("count")
        resource_path = "#{resource}s"
      else
        count = get(path).parse.fetch("#{resource}_count")
        resource_path = "#{path}/#{resource}s"
      end
      offset = 0
      resources = []
      while offset < count do
        resources.concat(get("#{resource_path}?limit=100&offset=#{offset}").parse)
        offset = offset + 100
      end
      resources
    end

    private

    def set_token
      response = HTTP.basic_auth(user: @client_id, pass: @client_secret)
                     .post(OAUTH_ENDPOINT,
                           form: { grant_type: "client_credentials" }).parse
      @token = response.fetch("access_token")
      @token_expires = Time.now + response.fetch("expires_in")
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
brightcove-cmsapi-0.1.0 lib/brightcove/cmsapi.rb