Class: GoogleSpreadsheet::Session

Inherits:
Object
  • Object
show all
Extended by:
Util
Includes:
Util
Defined in:
lib/google_spreadsheet.rb

Overview

Use GoogleSpreadsheet.login or GoogleSpreadsheet.saved_session to get GoogleSpreadsheet::Session object.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Util

as_utf8, encode_query, h

Constructor Details

#initialize(auth_tokens, oauth_token) ⇒ Session

Restores session using return value of auth_tokens method of previous session. You can use oauth_token instead of gmail username and password if you have used Google hybrid protocol (Open ID+ OAuth)



144
145
146
147
148
149
150
# File 'lib/google_spreadsheet.rb', line 144

def initialize(auth_tokens, oauth_token)
  if oauth_token
    @oauth_token = oauth_token
  else  
    @auth_tokens = auth_tokens
  end
end

Instance Attribute Details

#auth_tokensObject (readonly)

Authentication tokens.



167
168
169
# File 'lib/google_spreadsheet.rb', line 167

def auth_tokens
  @auth_tokens
end

#on_auth_failObject

Proc or Method called when authentication has failed. When this function returns true, it tries again.



176
177
178
# File 'lib/google_spreadsheet.rb', line 176

def on_auth_fail
  @on_auth_fail
end

Class Method Details

.authorized(oauth_token) ⇒ Object



138
139
140
# File 'lib/google_spreadsheet.rb', line 138

def self.authorized(oauth_token)
  session = Session.new(nil, oauth_token)
end

.login(mail, password) ⇒ Object

The same as GoogleSpreadsheet.login.



132
133
134
135
136
# File 'lib/google_spreadsheet.rb', line 132

def self.(mail, password)
  session = Session.new()
  session.(mail, password)
  return session
end

Instance Method Details

#auth_header(auth) ⇒ Object

:nodoc:



178
179
180
181
182
183
184
# File 'lib/google_spreadsheet.rb', line 178

def auth_header(auth) #:nodoc:
  if auth == :none
    return {}
  else
    return {"Authorization" => "GoogleLogin auth=#{@auth_tokens[auth]}"}
  end
end

#auth_token(auth = :wise) ⇒ Object

Authentication token.



170
171
172
# File 'lib/google_spreadsheet.rb', line 170

def auth_token(auth = :wise)
  return @auth_tokens[auth]
end

#create_spreadsheet(title = "Untitled", feed_url = "http://docs.google.com/feeds/documents/private/full") ⇒ Object

Creates new spreadsheet and returns the new GoogleSpreadsheet::Spreadsheet.

e.g.

session.create_spreadsheet("My new sheet")


251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/google_spreadsheet.rb', line 251

def create_spreadsheet(
    title = "Untitled",
    feed_url = "http://docs.google.com/feeds/documents/private/full")
  xml = <<-"EOS"
    <atom:entry xmlns:atom="http://www.w3.org/2005/Atom" xmlns:docs="http://schemas.google.com/docs/2007">
      <atom:category scheme="http://schemas.google.com/g/2005#kind"
          term="http://schemas.google.com/docs/2007#spreadsheet" label="spreadsheet"/>
      <atom:title>#{h(title)}</atom:title>
    </atom:entry>
  EOS

  doc = request(:post, feed_url, :data => xml, :auth => :writely)
  ss_url = as_utf8(doc.search(
    "link[@rel='http://schemas.google.com/spreadsheets/2006#worksheetsfeed']")[0]["href"])
  return Spreadsheet.new(self, ss_url, title)
end

#login(mail, password) ⇒ Object

Authenticates with given mail and password, and updates current session object if succeeds. Raises GoogleSpreadsheet::AuthenticationError if fails. Google Apps account is supported.



155
156
157
158
159
160
161
162
163
164
# File 'lib/google_spreadsheet.rb', line 155

def (mail, password)
  begin
    @auth_tokens = {}
    authenticate(mail, password, :wise)
    authenticate(mail, password, :writely)
  rescue GoogleSpreadsheet::Error => ex
    return true if @on_auth_fail && @on_auth_fail.call()
    raise(AuthenticationError, "authentication failed for #{mail}: #{ex.message}")
  end
end

#request(method, url, params = {}) ⇒ Object

:nodoc:



268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# File 'lib/google_spreadsheet.rb', line 268

def request(method, url, params = {}) #:nodoc:
  if @oauth_token  
    if method == :get
      response = @oauth_token.get(url)
      return Hpricot.XML(response.body)
    elsif method == :post
      response = @oauth_token.post(url,params[:data])
      return Hpricot.XML(response.body)
    end
  else
    uri = URI.parse(url)
    data = params[:data]
    auth = params[:auth] || :wise
    if params[:header]
      add_header = params[:header]
    else
      add_header = data ? {"Content-Type" => "application/atom+xml"} : {}
    end
    response_type = params[:response_type] || :xml

    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = uri.scheme == "https"
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    http.start() do
      while true
        path = uri.path + (uri.query ? "?#{uri.query}" : "")
        header = auth_header(auth).merge(add_header)
        if method == :delete || method == :get
          response = http.__send__(method, path, header)
        else
          response = http.__send__(method, path, data, header)
        end
        if response.code == "401" && @on_auth_fail && @on_auth_fail.call()
          next
        end
        if !(response.code =~ /^2/)
          raise(
          response.code == "401" ? AuthenticationError : GoogleSpreadsheet::Error,
          "Response code #{response.code} for #{method} #{url}: " +
          CGI.unescapeHTML(response.body))
        end
        case response_type
        when :xml
          return Hpricot.XML(response.body)
        when :raw
          return response.body
        else
          raise("unknown params[:response_type]: %s" % response_type)
        end
      end
    end
  end
end

#spreadsheet_by_key(key) ⇒ Object

Returns GoogleSpreadsheet::Spreadsheet with given key.

e.g.

# http://spreadsheets.google.com/ccc?key=pz7XtlQC-PYx-jrVMJErTcg&hl=ja
session.spreadsheet_by_key("pz7XtlQC-PYx-jrVMJErTcg")


211
212
213
214
# File 'lib/google_spreadsheet.rb', line 211

def spreadsheet_by_key(key)
  url = "http://spreadsheets.google.com/feeds/worksheets/#{key}/private/full"
  return Spreadsheet.new(self, url)
end

#spreadsheet_by_url(url) ⇒ Object

Returns GoogleSpreadsheet::Spreadsheet with given url. You must specify either of:

  • URL of the page you open to access the spreadsheet in your browser

  • URL of worksheet-based feed of the spreadseet

e.g.

session.spreadsheet_by_url(
  "http://spreadsheets.google.com/ccc?key=pz7XtlQC-PYx-jrVMJErTcg&hl=en")
session.spreadsheet_by_url(
  "http://spreadsheets.google.com/feeds/worksheets/pz7XtlQC-PYx-jrVMJErTcg/private/full")


225
226
227
228
229
230
231
232
233
234
235
# File 'lib/google_spreadsheet.rb', line 225

def spreadsheet_by_url(url)
  # Tries to parse it as URL of human-readable spreadsheet.
  uri = URI.parse(url)
  if uri.host == "spreadsheets.google.com" && uri.path =~ /\/ccc$/
    if (uri.query || "").split(/&/).find(){ |s| s=~ /^key=(.*)$/ }
      return spreadsheet_by_key($1)
    end
  end
  # Assumes the URL is worksheets feed URL.
  return Spreadsheet.new(self, url)
end

#spreadsheets(params = {}) ⇒ Object

Returns list of spreadsheets for the user as array of GoogleSpreadsheet::Spreadsheet. You can specify query parameters described at code.google.com/apis/spreadsheets/docs/2.0/reference.html#Parameters

e.g.

session.spreadsheets
session.spreadsheets("title" => "hoge")


193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/google_spreadsheet.rb', line 193

def spreadsheets(params = {})
  query = encode_query(params)
  doc = request(:get, "http://spreadsheets.google.com/feeds/spreadsheets/private/full?#{query}")
  result = []
  for entry in doc.search("entry")
    title = as_utf8(entry.search("title").text)
    url = as_utf8(entry.search(
      "link[@rel='http://schemas.google.com/spreadsheets/2006#worksheetsfeed']")[0]["href"])
    result.push(Spreadsheet.new(self, url, title))
  end
  return result
end

#worksheet_by_url(url) ⇒ Object

Returns GoogleSpreadsheet::Worksheet with given url. You must specify URL of cell-based feed of the worksheet.

e.g.

session.worksheet_by_url(
  "http://spreadsheets.google.com/feeds/cells/pz7XtlQC-PYxNmbBVgyiNWg/od6/private/full")


243
244
245
# File 'lib/google_spreadsheet.rb', line 243

def worksheet_by_url(url)
  return Worksheet.new(self, nil, url)
end