lib/kraken-io.rb in kraken-io-0.0.4 vs lib/kraken-io.rb in kraken-io-0.1.0

- old
+ new

@@ -1,51 +1,96 @@ require 'json' require 'httparty' -require 'rest-client' -require 'net/http/post/multipart' +require 'active_support/hash_with_indifferent_access' +require 'active_support/core_ext/hash' +require 'thread' +require 'kraken-io/http_multi_part' +require 'kraken-io/response' + module Kraken class API include HTTParty + extend HTTPMultiPart + base_uri 'https://api.kraken.io/v1' + attr_accessor :api_key, :api_secret - def initialize(api_key = '', api_secret = '') - @api_key = api_key - @api_secret = api_secret + def initialize(options = {}) + @api_key = options.fetch(:api_key) + @api_secret = options.fetch(:api_secret) end - def url(params = {}) - params.merge!({ - 'auth' => { - 'api_key' => @api_key, - 'api_secret' => @api_secret - } - }) + def async + @async = true + self + end - self.class.post('https://api.kraken.io/v1/url', {:body => JSON.generate(params)}) + def sync + @async = false + self end - def upload(params = {}) - params.merge!({ - 'auth' => { - 'api_key' => @api_key, - 'api_secret' => @api_secret - } - }) + def url(url, params = {}) + params = normalized_params(params).merge!(auth_hash) + params[:url] = url + call_kraken do + res = self.class.post('/url', body: params.to_json) + res = Kraken::Response.new(res) + yield res if block_given? or return res + end + end - url = URI.parse("https://api.kraken.io/v1/upload") + def callback_url(url) + @callback_url = url + self + end - File.open(params['file']) do |file| - params.delete('file') + def upload(file_name, params = {}) + params = normalized_params(params).merge!(auth_hash) + call_kraken do + res = self.class.multipart_post('/upload', file: file_name, body: params.to_json) + res = Kraken::Response.new(res) + yield res if block_given? or return res + end + end - req = Net::HTTP::Post::Multipart.new url.path, "body" => JSON.generate(params), "file" => UploadIO.new(file, 'logotyp.png') + private + def call_kraken(&block) + if @async + call_async(&block) + else + yield + end + end - https = Net::HTTP.new(url.host, url.port) - https.use_ssl = true + def call_async(&block) + Thread.abort_on_exception = false + Thread.new do |t| + block.call + end + nil + end - res = https.start() {|conn| conn.request(req)} - response = JSON.parse(res.body) + def normalized_params(params) + params = params.with_indifferent_access + + if params.keys.include?(:callback_url) || @callback_url + params[:callback_url] = @callback_url + else + params[:wait] = true end + + params end + + def auth_hash + { + auth: { + api_key: api_key, + api_secret: api_secret + } + } + end end -end \ No newline at end of file +end