Moved Buzz example into its own directory for consistency.
[arvados.git] / examples / buzz / buzz.rb
1 $:.unshift('lib')
2 require 'rubygems'
3 require 'sinatra'
4 require 'datamapper'
5 require 'google/api_client'
6
7 use Rack::Session::Pool, :expire_after => 86400 # 1 day
8
9 # Set up our token store
10 DataMapper.setup(:default, 'sqlite::memory:')
11 class TokenPair
12   include DataMapper::Resource
13
14   property :id, Serial
15   property :refresh_token, String
16   property :access_token, String
17   property :expires_in, Integer
18   property :issued_at, Integer
19
20   def update_token!(object)
21     self.refresh_token = object.refresh_token
22     self.access_token = object.access_token
23     self.expires_in = object.expires_in
24     self.issued_at = object.issued_at
25   end
26
27   def to_hash
28     return {
29       :refresh_token => refresh_token,
30       :access_token => access_token,
31       :expires_in => expires_in,
32       :issued_at => Time.at(issued_at)
33     }
34   end
35 end
36 TokenPair.auto_migrate!
37
38 before do
39   @client = Google::APIClient.new
40   @client.authorization.client_id = '245083617981.apps.googleusercontent.com'
41   @client.authorization.client_secret = 'pYelZCRjSa+iMezYENVScXFk'
42   @client.authorization.scope = 'https://www.googleapis.com/auth/buzz'
43   @client.authorization.redirect_uri = to('/oauth2callback')
44   @client.authorization.code = params[:code] if params[:code]
45   if session[:token_id]
46     # Load the access token here if it's available
47     token_pair = TokenPair.get(session[:token_id])
48     @client.authorization.update_token!(token_pair.to_hash)
49   end
50   if @client.authorization.refresh_token && @client.authorization.expired?
51     @client.authorization.fetch_access_token!
52   end
53   @buzz = @client.discovered_api('buzz')
54   unless @client.authorization.access_token || request.path_info =~ /^\/oauth2/
55     redirect to('/oauth2authorize')
56   end
57 end
58
59 get '/oauth2authorize' do
60   redirect @client.authorization.authorization_uri.to_s, 303
61 end
62
63 get '/oauth2callback' do
64   @client.authorization.fetch_access_token!
65   # Persist the token here
66   token_pair = if session[:token_id]
67     TokenPair.get(session[:token_id])
68   else
69     TokenPair.new
70   end
71   token_pair.update_token!(@client.authorization)
72   token_pair.save()
73   session[:token_id] = token_pair.id
74   redirect to('/')
75 end
76
77 get '/' do
78   result = @client.execute(
79     @buzz.activities.list,
80     {'userId' => '@me', 'scope' => '@consumption', 'alt'=> 'json'}
81   )
82   status, _, _ = result.response
83   [status, {'Content-Type' => 'application/json'}, JSON.generate(result.data)]
84 end