2012年8月10日金曜日

Google APIs Calnedar & OAuth2.0 (v3/v2)

はじめに

Google APIs を使うコマンドラインを書いてみました。自分のイベントとか見たい方は適当に改良してください。:-)

** かぶりネタですが興味のある方は読んでください。**


Usage

USAGE
      gapicalendarlist.sh  v2|v3

RESET SETTINGS
      remove 'v2.gapi.token' or 'v3.gapi.token'

DEPENDENCIES
      lynx, curl


解説のようなメモのような

簡単に認証と処理内容を書いてみました

認証の種類

Version 2 : using ClientLogin
  • OAuth
  • AuthSub
  • ClientLogin
Version 3 : using OAuth -> Devices

知識の足りなさ等の諸事情で Devices の方法を選択してます。

Installed Applicatoins の方式で、https://accounts.google.com/o/oauth2/auth にリクエストするとHTMLコンテンツがかえって来ます。これはシェルであれこれするのが面倒だったのでやめました。
Devices方式で、https://accounts.google.com/o/oauth2/device/code にリクエストをすると、JSONがかえってpiar毎に改行されているのでシェルで扱いやすいのでこちらを選択しました

  • OAuth
    • Login
    • Web Server Applications
    • Client-size Applications
    • Installled Applications (Winwdows, iOS, Android, Blackberry)
    • Devices
    • Service Accounts

処理内容

*** Google のサイトを見た方がいいと思ったので割愛します。 ***

 [ shell ]                  [ google ]
    |                            |
    |                            |
    +----- get user token -----> +  URL 1 
    |                            |
    | <------ user token --------+
    |     and other params       |
    |          JSON              |
    |                            |
    +----+                       |
    |    | save token            |
    |<---+                       |
    |         [ lynx ]           |
    |            |               |
    +-- verify ->|               |
    |    URL     +-- Sign in --> |
    |            |               |
    |            |<- user code --+
    |            |     form      |
    |            |               |
    |            +- user code -->|
    |            |               |
    |            |<- allow acces-+
    |            |  confirm page |
    |            |               |
    |            +-allow submit->|
    |            |               |
    |            |<- result page-+
    |            |               |
    |                            |
    |                            |
    |                            |
    |                            |
    +------ get access token --->+ URL 2 
    |                            |
    | <------ access token ------+
    |       and other params     |
    |           JSON             |
    |                            |
    +----+                       |
    |    | save token            |
    |<---+                       |
    |                            |
    |                            |
    +----- get calendar list --->+  URL 3
    |                            |
    | <----- calendar list ------+
    |         JSON               |
    |                            |
    |                            |


URL 1 https://accounts.google.com/o/oauth2/device/code
URL 2 https://accounts.google.com/o/oauth2/token
URL 3 https://www.googleapis.com/calendar/v3/users/me/calendarList

Reference Link

Google OAuth 2.0

Google APIs Calendar



Source & Screen cast

#!/bin/bash
# ------------ parameters ------------
api_version=$1
# if need set, please remove these files.
token_file="v2.gapi.token"
user_code_file="v3.gapi.token"
# *************************************
# account : need setting
# *************************************
# ClientLogin
username=yourmail@address.net
password=xxxx
# oauth 2.0
client_id=your.account.clientId
client_secret=
# ------------ functions ------------
#
# Version 2
#
function V2ClientLoginAndCalendarList {
# [company-id]-[app-name]-[app-version]
applicationName="mycompany-googleapi.sh-v1"
# cl (Calendar) / mail (Gmail) / blogger (Blogger)
serviceName="cl"
# GOOGLE / HOSTED / HOSTED_OR_GOOGLE
accountType="HOSTED_OR_GOOGLE"
#
# login , get token
#
if [ -e ${token_file} ]; then
TOKEN=`cat ${token_file}`
else
URL="https://www.google.com/accounts/ClientLogin"
parameters="Email=${username}&Passwd=${password}&source=${applicationName}&service=${serviceName}&accountType=${accountType}"
TOKEN=`curl -s -d "${parameters}" -k ${URL} -H "GData-Version: 2" | awk '{if (/Auth/) {print $0;}}' | sed 's/=/ /' | awk '{print $2}'`
echo ${TOKEN} > ${token_file}
# for interval
sleep 5
fi
# get calendar list
URL="https://www.google.com/calendar/feeds/default/owncalendars/full"
curl -s -H "GData-Version: 2" -H "Authorization: GoogleLogin auth=${TOKEN}" -k ${URL}
}
#
# Version 3
#
function V3OAuthAndCalendarList {
# for lynx
#LANG=en
#export LANG
scope="https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.readonly"
#scope="https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.readonly"
#
# obtain user code
#
if [ ! -e ${user_code_file} ]; then
URL="https://accounts.google.com/o/oauth2/device/code"
parameters="scope=${scope}&client_id=${client_id}"
curl -s -k ${URL} -d "${parameters}" | sed 's/"/ /g' | awk '{ if (NF > 3) {printf("%s=%s\n", $1, $3);}}' > ${user_code_file}
fi
source ${user_code_file}
#
# allow api using and obtain access token
#
if [ "${access_token}" = "" ]; then
echo "********* COPY ************"
echo "user_code: ${user_code}"
echo "********* COPY ************"
sleep 8
lynx "${verification_url}"
URL="https://accounts.google.com/o/oauth2/token"
parameters="client_id=${client_id}&client_secret=${client_secret}&code=${device_code}&grant_type=http://oauth.net/grant_type/device/1.0"
curl -s -H "GData-Version: 3" -k ${URL} -d "${parameters}" | sed 's/"/ /g' | awk '{ if (NF > 3) {printf("%s=%s\n", $1, $3);}}' >> ${user_code_file}
source ${user_code_file}
fi
#
# get calendar
#
URL=https://www.googleapis.com/calendar/v3/users/me/calendarList
curl -s -k ${URL} -H "Authorization: Bearer ${access_token}"
}
function UsageMessage {
echo "USAGE"
echo " gapicalendarlist.sh v2|v3"
echo ""
echo "RESET SETTINGS"
echo " remove '${token_file}' or '${user_code_file}'"
echo ""
echo "DEPENDENCIES"
echo " lynx, curl"
echo ""
}
# ------------ logic ------------
if [ "${client_id}" = "your.account.clientId" -o "${username}" = "yourmail@address.net" ]; then
echo "**********************************"
echo "PLEASE SETUP ACCOUNT PARAMETERS"
echo "**********************************"
echo ""
echo "v2 => uesername , password"
echo "v3 => client_id , client_secret"
echo ""
echo "**********************************"
UsageMessage
elif [ "${api_version}" = "v3" ]; then
V3OAuthAndCalendarList
elif [ "${api_version}" = "v2" ]; then
V2ClientLoginAndCalendarList
else
UsageMessage
fi

ttyplay