Created
July 21, 2018 19:02
-
-
Save dncrht/438eee30b4150fce69871f17aebeb959 to your computer and use it in GitHub Desktop.
Upload file to Microsoft's OneDrive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Usage: | |
# - Store refresh token on Redis under one_drive:refresh_token | |
# - Do OneDrive::Client.new.upload_file('/path/to/file') | |
module OneDrive | |
class Client | |
REFRESH_TOKEN = 'one_drive:refresh_token'.freeze | |
class NoTokens < StandardError; end | |
def initialize | |
refresh_token = Rails.cache.read REFRESH_TOKEN | |
refresh_token, access_token = get_tokens(refresh_token) | |
Rails.cache.write REFRESH_TOKEN, refresh_token | |
@access_token = access_token | |
end | |
def upload_file(filename) | |
connection = Faraday.new( | |
'https://graph.microsoft.com', | |
headers: { | |
'Authorization' => 'Bearer ' << @access_token, | |
'Content-Type' => 'text/plain', | |
} | |
) | |
file = filename.split('/').last | |
request = connection.put("/v1.0/me/drive/root:/MyFolder/#{Rails.env}/#{file}:/content", File.read(filename)) | |
return Response.new(success: false, data: request.status) if request.status != 201 | |
Response.new(success: true, data: JSON.parse(request.body)['webUrl']) | |
end | |
private | |
def get_tokens(refresh_token) | |
connection = Faraday.new('https://login.microsoftonline.com') | |
request = connection.post '/common/oauth2/v2.0/token', { | |
refresh_token: refresh_token, | |
client_id: ENV['ONEDRIVE_CLIENT_ID'], | |
client_secret: ENV['ONEDRIVE_CLIENT_SECRET'], | |
scope: 'offline_access files.readwrite', | |
redirect_uri: 'http://localhost:3003', | |
grant_type: 'refresh_token', | |
} | |
raise NoTokens if request.status != 200 | |
body = JSON.parse(request.body) | |
[body['refresh_token'], body['access_token']] | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment