|
#!/usr/bin/env ruby |
|
require 'net/http' |
|
require 'net/http/post/multipart' |
|
require 'mime/types' |
|
require 'oauth' |
|
require 'json' |
|
require 'yaml' |
|
require 'launchy' |
|
|
|
AUTH_FILE = 'figshare.yaml' |
|
CONSUMER_KEY = '...' |
|
CONSUMER_SECRET = '...' |
|
|
|
unless ARGV.size == 1 |
|
STDERR.puts 'Syntax: ./figshare.rb [file name]' |
|
exit 1 |
|
end |
|
path = ARGV.first |
|
file = File.basename path |
|
|
|
# setup the oauth stuff |
|
consumer = OAuth::Consumer.new CONSUMER_KEY, |
|
CONSUMER_SECRET, |
|
:site => 'http://api.figshare.com', |
|
:request_token_path => '/v1/pbl/oauth/request_token', |
|
:authorize_path => '/v1/pbl/oauth/authorize', |
|
:access_token_path => '/v1/pbl/oauth/access_token', |
|
:http_method => :post |
|
unless File.exist? AUTH_FILE |
|
request_token = consumer.get_request_token |
|
Launchy.open request_token.authorize_url |
|
STDOUT.print 'Enter pincode: '; STDOUT.flush; |
|
pincode = STDIN.readline.chomp |
|
access_token = request_token.get_access_token :oauth_verifier => pincode |
|
File.write AUTH_FILE, YAML.dump(access_token.params) |
|
end |
|
|
|
# setup the oauth stuff |
|
client = OAuth::AccessToken.from_hash consumer, YAML.load(File.read(AUTH_FILE)) |
|
|
|
# create an article |
|
body = JSON.generate 'title'=>file, 'description'=>file, 'defined_type'=>'dataset' |
|
result = client.post '/v1/my_data/articles', body, {"Content-Type"=>"application/json"} |
|
draft = JSON.parse result.body |
|
article_id = draft['article_id'] |
|
uri = URI.parse "http://api.figshare.com/v1/my_data/articles/#{article_id}/files" |
|
|
|
# upload file |
|
payload = {'filedata' => UploadIO.new(path, MIME::Types.of(path))} |
|
req = Net::HTTP::Put::Multipart.new(uri.path, payload, {'Content-Type' => 'multipart/form-data'}) |
|
oauth_params = {:consumer => consumer, :token => client, :request_uri => uri} |
|
oauth_helper = OAuth::Client::Helper.new req, oauth_params |
|
req.add_field "Authorization", oauth_helper.header # Signs the request |
|
|
|
# http = Net::HTTP.new uri.host, uri.port |
|
# http.set_debug_output $stdout #use this to debug net/http |
|
# res = http.start do |http| |
|
res = Net::HTTP.start uri.host, uri.port do |http| |
|
http.request req |
|
end |
|
puts res.body |