require "simplegdata/version" module SimpleGData # A simple class that makes a oauth request using the oauth gem # Initialize it by passing in a required oauth token and oauth # secret recieved form an external service such as omniauth or # the oauth gem. class Request def initialize(oauth_token, oauth_secret, params = { :application_id => 'anonymous', :application_secret => 'anonymous', :site => 'https://www.google.com' }) # Sets up the class variables. Defaults to Google's anonymous # usage if no account is given. @oauth_token = oauth_token @oauth_secret = oauth_secret @application_id = params[:application_id] @application_secret = params[:application_secret] @site = params[:site] end # A class method to make an optimized request to GData's APIS. # Automatically converts the request to JSON and accepts a # a ruby hash to convert to JSON to send for post data. Returns # results back as a ruby array. def request(rest, url, data = nil, options = nil) # Default get requests to json if rest == :get && @site == 'https://www.google.com' unless url.include? 'alt=json' if url.include? '?' url = url + '&alt=jsonc' else url = url + '?alt=jsonc' end end end # Default post requests to json if options.nil? options = { 'Content-Type' => 'application/json' } else unless options.has_key? 'Content-Type' options['Content-Type'] = 'application/json' end end # Convert any data passed in for post requests to JSON if data.class == {}.class data = ActiveSupport::JSON.encode(data) end # Run the query and return the results as a ruby object response = request_raw(rest, url, data, options) ActiveSupport::JSON.decode response end # A class method to process a raw request. All handling is # done by the user. Deals with the unique issue of GData # API's sometimes returning 302 redirects with gsessionids # appended to them. def request_raw(rest, url, data = nil, options = nil) response = access_token.request(rest, url, data, options) #end case response when Net::HTTPSuccess then response.body when Net::HTTPRedirection then access_token.request(rest, response['location'], data, options).body else response.error! end end private # An internal storage of the access token used to make requests def access_token @access_token ||= create_access_token end # Creates an oauth token based off the provided credentials def create_access_token consumer = OAuth::Consumer.new @application_id, @application_secret, :site => @site token_hash = { :oauth_token => @oauth_token, :oauth_token_secret => @oauth_secret } access_token = OAuth::AccessToken.from_hash(consumer, token_hash) end end end