Created
June 9, 2013 12:51
-
-
Save liubin/5743405 to your computer and use it in GitHub Desktop.
This file contains 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
require 'google/api_client' | |
class GcalendarController < ApplicationController | |
before_filter :setup | |
def events | |
# 取得 calendar API的service | |
@calendar = @client.discovered_api('calendar', 'v3') | |
# 调用取得calendar 一览接口 | |
@calendarlist = @client.execute(:api_method => @calendar.calendar_list.list, | |
:authorization => @client.authorization) | |
# 调用取得某一calendar里面某一天的events | |
# 注意,日期格式要iso8601,且要注意时区信息 | |
day = Time.now | |
@time_min = Time.local(day.year, day.month, day.day, 0,0,0).iso8601 | |
@time_max = Time.local(day.year, day.month, day.day, 23,59,59).iso8601 | |
@events = @client.execute(:api_method => @calendar.events.list, | |
:parameters => {'calendarId' => 'primary', | |
"timeMin" => @time_min, | |
"timeMax" => @time_max | |
}, | |
:authorization => @client.authorization) | |
end | |
def login | |
# login画面,提供了一个指向Google的认证链接,即下面这个网址 | |
# @client.authorization.authorization_uri | |
@redirect_uri = @client.authorization.authorization_uri | |
end | |
# 每个action执行前设置token等信息 | |
def setup | |
@client = Google::APIClient.new | |
@client.authorization.client_id = '........' | |
@client.authorization.client_secret = '........' | |
@client.authorization.scope = 'https://www.googleapis.com/auth/calendar' | |
@client.authorization.redirect_uri = 'http://localhost:3000/gcalendar/callback' | |
# got access_token | |
# TODO: need more conditions | |
access_token = session[:access_token] | |
unless access_token.nil? | |
# 如果已经授权过了,设置token信息。 | |
@client.authorization.access_token = session[:access_token] | |
@client.authorization.refresh_token = session[:refresh_token] | |
@client.authorization.expires_in = session[:expires_in] | |
@client.authorization.issued_at = session[:issued_at] | |
end | |
end | |
# Google API 服务器授权后的回调接口 | |
def callback | |
# 设置code,从Google 服务器返回的 | |
@client.authorization.code = params[:code] if params[:code] | |
# 取得access token等信息 | |
@client.authorization.fetch_access_token! | |
# 将token相关信息保存到session | |
session[:access_token] = @client.authorization.access_token | |
session[:refresh_token] = @client.authorization.refresh_token | |
session[:expires_in] = @client.authorization.expires_in | |
session[:issued_at] = @client.authorization.issued_at | |
redirect_to :action => 'events' | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment