class Rb1drv::OneDrive
Base class to support oauth2 authentication and sending simple API requests.
Call #root
or #get
to get an OneDriveDir
or OneDriveFile
to wotk with.
Attributes
Public Class Methods
Instanciates with app id and secret.
# File lib/rb1drv.rb, line 12 def initialize(client_id, client_secret, callback_url, logger=nil) @client_id = client_id @client_secret = client_secret @callback_url = callback_url @logger = logger @oauth2_client = OAuth2::Client.new client_id, client_secret, authorize_url: 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize', token_url: 'https://login.microsoftonline.com/common/oauth2/v2.0/token' @conn = Excon.new('https://graph.microsoft.com/', persistent: true, idempotent: true) @conn.logger = @logger if @logger end
Public Instance Methods
Gets access token from authorize code
@return [OAuth2::AccessToken] the access token
# File lib/rb1drv/auth.rb, line 16 def auth_access(auth_code) @access_token = @oauth2_client.auth_code.get_token(auth_code, redirect_uri: @callback_url) end
# File lib/rb1drv/auth.rb, line 29 def auth_check @access_token = @access_token.refresh! if @access_token.expired? end
Loads previously retrieved access token from Hash
@return [OAuth2::AccessToken] the access token
# File lib/rb1drv/auth.rb, line 23 def auth_load(access_token) @access_token = OAuth2::AccessToken.from_hash(@oauth2_client, access_token) @access_token = @access_token.refresh! if @access_token.expired? @access_token end
Gets authorize URL to start authentication process
@return [String] the authorize URL
# File lib/rb1drv/auth.rb, line 6 def auth_url @oauth2_client.auth_code.authorize_url( redirect_uri: @callback_url, scope: 'openid offline_access https://graph.microsoft.com/Files.ReadWrite.All' ) end
Get an object by an arbitary path.
TODO: API endpoint does not play well with remote files
@return [OneDriveDir,OneDriveFile] the drive item you asked
# File lib/rb1drv/onedrive.rb, line 15 def get(path) path = "/#{path}" unless path[0] == '/' OneDriveItem.smart_new(self, request("drive/root:#{path}")) end
Issues requests to API endpoint.
@param uri [String] relative path of the API @param data [Hash] JSON data to be post @param verb [Symbol] HTTP request verb if data is given
@return [Hash] response from API.
# File lib/rb1drv.rb, line 31 def request(uri, data=nil, verb=:post) @logger.info(uri) if @logger auth_check query = { path: File.join('v1.0/me/', URI.escape(uri)), headers: { 'Authorization': "Bearer #{@access_token.token}" } } if data query[:body] = JSON.generate(data) query[:headers]['Content-Type'] = 'application/json' @logger.info(query[:body]) if @logger verb = :post unless [:post, :put, :patch, :delete].include?(verb) response = @conn.send(verb, query) else response = @conn.get(query) end JSON.parse(response.body) end
Get root directory object.
@return [OneDriveDir] your root
# File lib/rb1drv/onedrive.rb, line 6 def root @_root_dir ||= OneDriveDir.new(self, request('drive/root')) end