require 'goauth2/hash_response' require 'goauth2/array_response' require 'goauth2/contacts' require 'goauth2/calendar' module Goauth2 class Client SCOPES = { :calendar => 'https://www.google.com/calendar/feeds/', :contacts => 'https://www.google.com/m8/feeds/', :gmail => 'https://mail.google.com/mail/feed/atom/' } def initialize(options = {}) @client_id = options[:client_id] @client_secret = options[:client_secret] @redirect_uri = options[:redirect_uri] @scope = options[:scope] || SCOPES.values.join(' ') @token = options[:token] @refresh_token = options[:refresh_token] @expires_at = options[:expires_at] @expires_in = options[:expires_in] end def authorize_url(options = {}) client.auth_code.authorize_url( :redirect_uri => options[:redirect_uri] || @redirect_uri, :scope => options[:scope] || @scope ) end def authorize(options = {}) @access_token ||= client.auth_code.get_token( options[:code], :redirect_uri => options[:redirect_uri] || @redirect_uri ) @token = @access_token.token @refresh_token = @access_token.refresh_token @expires_at = @access_token.expires_at @expires_in = @access_token.expires_in @access_token end def client @client ||= OAuth2::Client.new( @client_id, @client_secret, { :site => "https://accounts.google.com", :authorize_url => '/o/oauth2/auth', :token_url => '/o/oauth2/token' } ) end def access_token refresh! @access_token ||= OAuth2::AccessToken.new(client, @token, :refresh_token => @refresh_token, :expires_at => @expires_at, :expires_in => @expires_in) end private def refresh! if @access_token && @access_token.expired? @refresh_token ||= @access_token.refresh_token access_token = @access_token.refresh! @token = access_token.token @expires_at = access_token.expires_at @expires_in = access_token.expires_in @access_token = OAuth2::AccessToken.new(client, @token, :refresh_token => @refresh_token, :expires_at => @expires_at, :expires_in => @expires_in) end end def _get_jsonc(url, params={}) params.merge! :params => {'alt' => 'jsonc'} res = _get(url, params) end def _get_json(url, params={}) params.merge! :params => {'alt' => 'json'} res = _get(url, params) end def _get(url, params={}) res = access_token.get(url, params) Goauth2::HashResponse.new(JSON.parse(res.body)) rescue res end def _post(url, params={}, headers={}) oauth_response = access_token.post(url, params, headers) JSON.parse(oauth_response) rescue oauth_response end def _delete(url) oauth_response = access_token.delete(url) JSON.parse(oauth_response) rescue oauth_response end end end