Skip to content

Instantly share code, notes, and snippets.

@kaspergrubbe
Created May 30, 2013 23:37
Show Gist options
  • Save kaspergrubbe/5682088 to your computer and use it in GitHub Desktop.
Save kaspergrubbe/5682088 to your computer and use it in GitHub Desktop.
# Net / encoding
require 'net/http'
require 'net/https'
require 'base64'
# Imgur:
$client_id = 'xxx'
$client_secret = 'xxx'
# Imgur user tokens:
$refresh_token = 'xxx'
$access_token = nil
#get_urls = "https://api.imgur.com/oauth2/authorize?client_id=#{client_id}&response_type=token"
# http://example.iana.org/#access_token=xxx&expires_in=3600&token_type=bearer&refresh_token=xxx&account_username=kasperg
def imgur_get_access_token(client_id, client_secret, refresh_token)
# Get a new access_token:
#
# POST: https://api.imgur.com/oauth2/token
# refresh_token = "#{xxx}"
# client_id = "#{client_id}"
# client_secret = "#{client_secret}"
# grant_type = 'refresh_token'
uri = URI('https://api.imgur.com/oauth2/token')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new(uri.request_uri)
values = {
'refresh_token' => refresh_token,
'client_id' => client_id,
'client_secret' => client_secret,
'grant_type' => 'refresh_token',
}
request.set_form_data(values)
JSON.parse(http.request(request).body)
end
def imgur_upload(access_token, file_name)
# POST: https://api.imgur.com/3/image
# header: Authorization: Bearer YOUR_ACCESS_TOKEN
# image: base64 encoded image
uri = URI('https://api.imgur.com/3/image')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new(uri.request_uri)
request.add_field("Authorization", "Bearer #{access_token}")
file = File.open(file_name)
file = Base64.encode64(file.read)
request.set_form_data({"image" => file})
JSON.parse(http.request(request).body)
end
def login(client_id, client_secret, refresh_token)
data = imgur_get_access_token(client_id, client_secret, refresh_token)
$access_token = data['access_token']
puts "Logged into imgur..." if $access_token.present?
end
def upload(file_name)
login($client_id, $client_secret, $refresh_token) if $access_token == nil
output = imgur_upload($access_token, file_name)
unless output['success']
login($client_id, $client_secret, $refresh_token)
output = imgur_upload($access_token, file_name)
return nil if output['success'] == false
end
return output['data']['link']
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment