require 'rest-client' require 'base64' require 'nokogiri' require 'json' class PawClient::Client class ClientError < StandardError attr_reader :response def initialize(response) super(message) @response = response message=to_json.success rescue 'Error while call plugandwork API, Unparsable response' super(message) end def info to_json.info end def to_json JSON.parse(self.response.to_s) end def request self.response.request end end attr_accessor :base_url attr_accessor :uuid attr_accessor :token attr_accessor :user_token attr_accessor :logger def initialize(attrs={}) @base_url = attrs.fetch(:base_url, PawClient.config.base_url) @uuid = attrs.fetch(:uuid, PawClient.config.uuid) @token = attrs.fetch(:token, PawClient.config.token) @user_token = attrs.fetch(:token, PawClient.config.user_token) @logger = attrs.fetch(:logger, PawClient.config.logger) end def endpoint_for(path) base_resource[path] end def get(path, params={}) begin r=endpoint_for(path).get(params) JSON.parse(r.to_s) rescue RestClient::ExceptionWithResponse => err raise ClientError.new(err.response) end end def post(path, payload, params={}) begin r=endpoint_for(path).post(payload,params) JSON.parse(r.to_s) rescue RestClient::ExceptionWithResponse => err raise ClientError.new(err.response) end end def delete(path, params={}) begin r=endpoint_for(path).delete(params) JSON.parse(r.to_s) rescue RestClient::ExceptionWithResponse => err raise ClientError.new(err.response) end end def create_doc(filepath = nil,params = {}) j = {} j['doc']=params j['doc']['title']||=File.basename(filepath) if filepath res = post('docs', j) if res && res['id'] && filepath res = upload_file(filepath, 'id' => res['id']) end return res end def delete_doc(id) delete('docs/'+id ) end def upload_file(localpath, params={}) begin request = RestClient::Request.new( :method => :post, :url => @base_url + "/api/d1/docs/#{params['id']}/file", :payload => { :multipart => true, :file => File.new(localpath, 'rb') }, :headers => {'Accept' => 'application/json', 'Authorization': "Bearer #{@user_token}"} ) r = request.execute #RestClient::Resource.new(@base_url + '/api/d1/', headers: {'Authorization': "Bearer #{@user_token}"}, lo JSON.parse(r.to_s) rescue RestClient::ExceptionWithResponse => err raise ClientError.new(err.response) end end def base_resource(reload=false) if !@base_resource || reload @base_resource=RestClient::Resource.new(@base_url + '/api/d1/', headers: {'Authorization': "Bearer #{@user_token}"}, log: self.logger) end @base_resource end end