require "base64" require "excon" require "securerandom" require "uri" require "zlib" require "transcriptic/api/errors" require "transcriptic/api/version" srand module Transcriptic class API def initialize(options={}) @api_key = options.delete(:api_key) || ENV['TRANSCRIPTIC_API_KEY'] user_pass = ":#{@api_key}" options = { :headers => {}, :host => 'secure.transcriptic.com', :nonblock => false, :scheme => 'https' }.merge(options) options[:headers] = { 'Accept' => 'application/json', 'Accept-Encoding' => 'gzip', 'Accept-Language' => 'en-US, en;q=0.8', 'Authorization' => "Token token=\"#{@api_key}\"", 'User-Agent' => "transcriptic/#{Transcriptic::API::VERSION}", 'X-Transcriptic-API-Version' => '1', 'X-Ruby-Version' => RUBY_VERSION, 'X-Ruby-Platform' => RUBY_PLATFORM }.merge(options[:headers]) @connection = Excon.new("#{options[:scheme]}://#{options[:host]}", options) end def request(params, &block) begin response = @connection.request(params, &block) rescue Excon::Errors::SocketError => error raise error rescue Excon::Errors::Error => error klass = case error.response.status when 401 then Transcriptic::API::Errors::Unauthorized when 402 then Transcriptic::API::Errors::VerificationRequired when 403 then Transcriptic::API::Errors::Forbidden when 404 then Transcriptic::API::Errors::NotFound when 408 then Transcriptic::API::Errors::Timeout when 422 then Transcriptic::API::Errors::RequestFailed when 423 then Transcriptic::API::Errors::Locked when /50./ then Transcriptic::API::Errors::RequestFailed else Transcriptic::API::Errors::ErrorWithResponse end reerror = klass.new(error.message, error.response) reerror.set_backtrace(error.backtrace) raise(reerror) end if response.body && !response.body.empty? if response.headers['Content-Encoding'] == 'gzip' response.body = Zlib::GzipReader.new(StringIO.new(response.body)).read end begin response.body = Transcriptic::API::OkJson.decode(response.body) rescue # leave non-JSON body as is end end # reset (non-persistent) connection @connection.reset response end def escape(string) CGI.escape(string).gsub('.', '%2E') end end end