読者です 読者をやめる 読者になる 読者になる

EvernoteAPI試験用開発環境の構築

RubyでEvernoteAPI試験用開発環境の構築をします。

■構築環境
Ubuntu 13.04

■用意するパッケージ(利用したバージョン)
Ruby (1.9.3)
gem (2.0.3)
sinatra (1.4.3)
evernote_oauth (0.2.1)

■用意するデータ
Evernote API Key :取得はこちらです
Evernoteサンドボックスアカウント:作成はこちらです
サンプルスクリプト:本ブログの下記に示します。またGitHubにもあります。

sinatraとは
Rubyの軽量Webフレームワーク
・シンプルなWebアプリ用のDSLDomain Specific Languageドメイン特化言語

■導入コマンド履歴

sudo gem install sinatra
sudo gem install evernote_oauth

rubyとgemは導入済みでした。

■サンプルスクリプトの実行
端末でアプリを起動(ruby en_oauth.rb)し、ブラウザからアクセス(http://localhost:4567/)します。
evernote_configも同じフォルダ内に置きます。

■実行結果
端末側:

ruby en_oauth.rb
INFO WEBrick 1.3.1
INFO ruby 1.9.3 (2012-04-20) [i686-linux]
== Sinatra/1.4.3 has taken the stage on 4567 for development with backup from WEBrick
INFO WEBrick::HTTPServer#start: pid=xxxx port=4567
ブラウザ側:

f:id:cherno_su:20130726153704p:plain

■サンプルスクリプト
en_oauth.rb

require 'sinatra'
enable :sessions
 
# Load our dependencies and configuration settings
$LOAD_PATH.push(File.expand_path(File.dirname(__FILE__)))
require "evernote_config.rb"

before do
    if OAUTH_CONSUMER_KEY.empty? || OAUTH_CONSUMER_SECRET.empty?
halt '<span style="color:red">Before using this sample code you must edit evernote_config.rb and replace OAUTH_CONSUMER_KEY and OAUTH_CONSUMER_SECRET with the values that you received from Evernote. If you do not have an API key, you can request one from <a href="http://dev.evernote.com/documentation/cloud/">dev.evernote.com/documentation/cloud/</a>.</span>'
    end
end

def auth_token
    session[:access_token].token if session[:access_token]
end

def client
    @client ||= EvernoteOAuth::Client.new(token: auth_token, consumer_key:OAUTH_CONSUMER_KEY, consumer_secret:OAUTH_CONSUMER_SECRET, sandbox: SANDBOX)
end

def user_store
    @user_store ||= client.user_store
end
def note_store
    @note_store ||= client.note_store
end

def en_user
    user_store.getUser(auth_token)
end

def notebooks
    @notebooks ||= note_store.listNotebooks(auth_token)
end

def total_note_count
    filter = Evernote::EDAM::NoteStore::NoteFilter.new
    counts = note_store.findNoteCounts(auth_token, filter, false)
    notebooks.inject(0) do |total_count, notebook|
        total_count + (counts.notebookCounts[notebook.guid] || 0)
    end
end

get '/' do
    erb :index
end

get '/reset' do
    session.clear
    redirect '/'
end

get '/list' do
    begin
         # Get notebooks
         session[:notebooks] = notebooks.map(&:name)
         # Get username
         session[:username] = en_user.username
         # Get total note count
         session[:total_notes] = total_note_count
         erb :index
                  rescue => e
                  @last_error = "Error listing notebooks: #{e.message}"
         erb :error
         end
end

get '/requesttoken' do
    callback_url = request.url.chomp("requesttoken").concat("callback")
    begin
         session[:request_token] = client.request_token(:oauth_callback => callback_url)
         redirect '/authorize'
         rescue => e
         @last_error = "Error obtaining temporary credentials: #{e.message}"
         erb :error
    end
end

get '/authorize' do
    if session[:request_token]
         redirect session[:request_token].authorize_url
    else
         # You shouldn't be invoking this if you don't have a request token
         @last_error = "Request token not set."
         erb :error
    end
end

get '/callback' do
    unless params['oauth_verifier'] || session['request_token']
        @last_error = "Content owner did not authorize the temporary credentials"
        halt erb :error
    end
    session[:oauth_verifier] = params['oauth_verifier']
    begin
        session[:access_token] = session[:request_token].get_access_token(:oauth_verifier => session[:oauth_verifier])
        redirect '/list'
        rescue => e
        @last_error = 'Error extracting access token'
        erb :error
    end
end

__END__
 
@@ index
<html>
<head>
<title>Evernote Ruby Example App</title>
</head>
<body>
<a href="/requesttoken">Click here</a> to authenticate this application using OAuth.
<% if session[:notebooks] %>
<hr />
<h3>The current user is <%= session[:username] %> and there are <%= session[:total_notes] %> notes in their account</h3>
<br />
<h3>Here are the notebooks in this account:</h3>
<ul>
<% session[:notebooks].each do |notebook| %>
<li><%= notebook %></li>
<% end %>
</ul>
<% end %>
</body>
</html>

@@ error
<html>
<head>
<title>Evernote Ruby Example App &mdash; Error</title>
</head>
<body>
<p>An error occurred: <%= @last_error %></p>
<p>Please <a href="/reset">start over</a>.</p>
</body>
</html>

evernote_config

# Load libraries required by the Evernote OAuth
require 'oauth'
require 'oauth/consumer'
 
# Load Thrift & Evernote Ruby libraries
require "evernote_oauth"
 
# Client credentials
OAUTH_CONSUMER_KEY = "your key"
OAUTH_CONSUMER_SECRET = "your secret"
 
# Connect to Sandbox server?
SANDBOX = true

以上で開発環境の構築とサンプルの実行は終了です。