Class: GoogleDrive::Session

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

Overview

Use GoogleDrive.login_with_oauth or GoogleDrive.saved_session to get GoogleDrive::Session object.

Constant Summary

Constants included from Util

Util::EXT_TO_CONTENT_TYPE

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Util

concat_url, construct_and_query, construct_query, convert_params, delegate_api_methods, encode_query, get_singleton_class, h, new_upload_io

Constructor Details

#initialize(client_or_access_token, proxy = nil) ⇒ Session

Returns a new instance of Session.



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/google_drive/session.rb', line 43

def initialize(client_or_access_token, proxy = nil)

  if proxy
    raise(
        ArgumentError,
        "Specifying a proxy object is no longer supported. Set ENV[\"http_proxy\"] instead.")
  end

  if client_or_access_token
    api_client_params = {
      :application_name => "google_drive Ruby library",
      :application_version => "0.4.0",
    }
    case client_or_access_token
      when Google::APIClient
        client = client_or_access_token
      when String
        client = Google::APIClient.new(api_client_params)
        client.authorization.access_token = client_or_access_token
      when OAuth2::AccessToken
        client = Google::APIClient.new(api_client_params)
        client.authorization.access_token = client_or_access_token.token
      when OAuth::AccessToken
        raise(
            ArgumentError,
            "Passing OAuth::AccessToken to login_with_oauth is no longer supported. " +
            "You can use OAuth1 by passing Google::APIClient.")
      else
        raise(
            ArgumentError,
            ("client_or_access_token is neither Google::APIClient, " +
             "String nor OAuth2::AccessToken: %p") %
            client_or_access_token)
    end
    @fetcher = ApiClientFetcher.new(client)
  else
    @fetcher = nil
  end

end

Instance Attribute Details

#on_auth_failObject

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



86
87
88
# File 'lib/google_drive/session.rb', line 86

def on_auth_fail
  @on_auth_fail
end

Class Method Details

.login_with_oauth(client_or_access_token, proxy = nil) ⇒ Object

The same as GoogleDrive.login_with_oauth.



34
35
36
# File 'lib/google_drive/session.rb', line 34

def self.(client_or_access_token, proxy = nil)
  return Session.new(client_or_access_token, proxy)
end

.new_dummyObject

Creates a dummy GoogleDrive::Session object for testing.



39
40
41
# File 'lib/google_drive/session.rb', line 39

def self.new_dummy()
  return Session.new(nil)
end

Instance Method Details

#clientObject

Returns the Google::APIClient object.



93
94
95
# File 'lib/google_drive/session.rb', line 93

def client
  return @fetcher.client
end

#collection_by_title(title) ⇒ Object

Returns a top-level collection whose title exactly matches title as GoogleDrive::Collection. Returns nil if not found. If multiple collections with the title are found, returns one of them.



250
251
252
# File 'lib/google_drive/session.rb', line 250

def collection_by_title(title)
  return self.root_collection.subcollection_by_title(title)
end

#collection_by_url(url) ⇒ Object

Returns GoogleDrive::Collection with given url. You must specify either of:

  • URL of the page you get when you go to docs.google.com/ with your browser and open a collection

  • URL of collection (folder) feed

e.g.

session.collection_by_url(
  "https://drive.google.com/#folders/" +
  "0B9GfDpQ2pBVUODNmOGE0NjIzMWU3ZC00NmUyLTk5NzEtYaFkZjY1MjAyxjMc")
session.collection_by_url(
  "http://docs.google.com/feeds/default/private/full/folder%3A" +
  "0B9GfDpQ2pBVUODNmOGE0NjIzMWU3ZC00NmUyLTk5NzEtYaFkZjY1MjAyxjMc")


267
268
269
270
271
272
273
# File 'lib/google_drive/session.rb', line 267

def collection_by_url(url)
  file = file_by_url(url)
  if !file.is_a?(Collection)
    raise(GoogleDrive::Error, "The file with the URL is not a collection: %s" % url)
  end
  return file
end

#collectionsObject

Returns the top-level collections (direct children of the root collection).

By default, it returns the first 100 collections. See document of files method for how to get all collections.



242
243
244
# File 'lib/google_drive/session.rb', line 242

def collections
  return self.root_collection.subcollections
end

#create_spreadsheet(title = "Untitled") ⇒ Object

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

e.g.

session.create_spreadsheet("My new sheet")


279
280
281
282
283
284
285
286
287
288
# File 'lib/google_drive/session.rb', line 279

def create_spreadsheet(title = "Untitled")
  file = self.drive.files.insert.request_schema.new({
      "title" => title,
      "mimeType" => "application/vnd.google-apps.spreadsheet",
  })
  api_result = execute!(
      :api_method => self.drive.files.insert,
      :body_object => file)
  return wrap_api_file(api_result.data)
end

#driveObject

Returns client.discovered_api(“drive”, “v2”).



98
99
100
# File 'lib/google_drive/session.rb', line 98

def drive
  return @fetcher.drive
end

#execute!(*args) ⇒ Object

:nodoc:



88
89
90
# File 'lib/google_drive/session.rb', line 88

def execute!(*args) #:nodoc:
  return @fetcher.client.execute!(*args)
end

#execute_paged!(opts, &block) ⇒ Object

:nodoc:



368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
# File 'lib/google_drive/session.rb', line 368

def execute_paged!(opts, &block) #:nodoc:

  if block

    page_token = nil
    begin
      parameters = (opts[:parameters] || {}).merge({"pageToken" => page_token})
      (items, page_token) = execute_paged!(opts.merge({:parameters => parameters}))
      items.each(&block)
    end while page_token

  elsif opts[:parameters] && opts[:parameters].has_key?("pageToken")

    api_result = self.execute!(
        :api_method => opts[:api_method],
        :parameters => opts[:parameters])
    items = api_result.data.items.map() do |item|
      opts[:converter] ? opts[:converter].call(item) : item
    end
    return [items, api_result.data.next_page_token]

  else

    parameters = (opts[:parameters] || {}).merge({"pageToken" => nil})
    (items, next_page_token) = execute_paged!(opts.merge({:parameters => parameters}))
    return items

  end
  
end

#file_by_id(id) ⇒ Object

Returns GoogleDrive::File or its subclass with a given id.



145
146
147
148
149
150
# File 'lib/google_drive/session.rb', line 145

def file_by_id(id)
  api_result = execute!(
    :api_method => self.drive.files.get,
    :parameters => { "fileId" => id })
  return wrap_api_file(api_result.data)
end

#file_by_title(title) ⇒ Object

Returns GoogleDrive::File or its subclass whose title exactly matches title. Returns nil if not found. If multiple files with the title are found, returns one of them.

If given an Array, traverses collections by title. e.g.

session.file_by_title(["myfolder", "mysubfolder/even/w/slash", "myfile"])


136
137
138
139
140
141
142
# File 'lib/google_drive/session.rb', line 136

def file_by_title(title)
  if title.is_a?(Array)
    return self.root_collection.file_by_title(title)
  else
    return files("q" => ["title = ?", title], "maxResults" => 1)[0]
  end
end

#file_by_url(url) ⇒ Object

Returns GoogleDrive::File or its subclass with a given url. url must be eitehr of:

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

  • URL of worksheet-based feed of a spreadseet



155
156
157
# File 'lib/google_drive/session.rb', line 155

def file_by_url(url)
  return file_by_id(url_to_id(url))
end

#files(params = {}, &block) ⇒ Object

Returns list of files for the user as array of GoogleDrive::File or its subclass. You can specify parameters documented at developers.google.com/drive/v2/reference/files/list

e.g.

session.files
session.files("q" => "title = 'hoge'")
session.files("q" => ["title = ?", "hoge"])  # Same as above with a placeholder

By default, it returns the first 100 files. You can get all files by calling with a block:

session.files do |file|
  p file
end

Or passing “pageToken” parameter:

page_token = nil
begin
  (files, page_token) = session.files("pageToken" => page_token)
  p files
end while page_token


121
122
123
124
125
126
127
128
# File 'lib/google_drive/session.rb', line 121

def files(params = {}, &block)
  params = convert_params(params)
  return execute_paged!(
      :api_method => self.drive.files.list,
      :parameters => params,
      :converter => proc(){ |af| wrap_api_file(af) },
      &block)
end

#inspectObject



430
431
432
# File 'lib/google_drive/session.rb', line 430

def inspect
  return "#<%p:0x%x>" % [self.class, self.object_id]
end

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

:nodoc:



399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
# File 'lib/google_drive/session.rb', line 399

def request(method, url, params = {}) #:nodoc:
  
  # Always uses HTTPS.
  url = url.gsub(%r{^http://}, "https://")
  data = params[:data]
  auth = params[:auth] || :wise
  response_type = params[:response_type] || :xml

  if params[:header]
    extra_header = params[:header]
  elsif data
    extra_header = {"Content-Type" => "application/atom+xml;charset=utf-8"}
  else
    extra_header = {}
  end
  extra_header = {"GData-Version" => "3.0"}.merge(extra_header)

  while true
    response = @fetcher.request_raw(method, url, data, extra_header, auth)
    if response.code == "401" && @on_auth_fail && @on_auth_fail.call()
      next
    end
    if !(response.code =~ /^2/)
      raise((response.code == "401" ? AuthenticationError : ResponseCodeError).
          new(response.code, response.body, method, url))
    end
    return convert_response(response, response_type)
  end
  
end

#root_collectionObject

Returns the root collection.



234
235
236
# File 'lib/google_drive/session.rb', line 234

def root_collection
  return @root_collection ||= file_by_id("root")
end

#spreadsheet_by_key(key) ⇒ Object

Returns GoogleDrive::Spreadsheet with given key.

e.g.

# https://docs.google.com/spreadsheets/d/1L3-kvwJblyW_TvjYD-7pE-AXxw5_bkb6S_MljuIPVL0/edit
session.spreadsheet_by_key("1L3-kvwJblyW_TvjYD-7pE-AXxw5_bkb6S_MljuIPVL0")


183
184
185
186
187
188
189
# File 'lib/google_drive/session.rb', line 183

def spreadsheet_by_key(key)
  file = file_by_id(key)
  if !file.is_a?(Spreadsheet)
    raise(GoogleDrive::Error, "The file with the ID is not a spreadsheet: %s" % key)
  end
  return file
end

#spreadsheet_by_title(title) ⇒ Object

Returns GoogleDrive::Spreadsheet with given title. Returns nil if not found. If multiple spreadsheets with the title are found, returns one of them.



212
213
214
# File 'lib/google_drive/session.rb', line 212

def spreadsheet_by_title(title)
  return spreadsheets("q" => ["title = ?", title], "maxResults" => 1)[0]
end

#spreadsheet_by_url(url) ⇒ Object

Returns GoogleDrive::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(
  "https://docs.google.com/spreadsheets/d/1L3-kvwJblyW_TvjYD-7pE-AXxw5_bkb6S_MljuIPVL0/edit")
session.spreadsheet_by_url(
  "https://spreadsheets.google.com/feeds/" +
  "worksheets/1L3-kvwJblyW_TvjYD-7pE-AXxw5_bkb6S_MljuIPVL0/private/full")


201
202
203
204
205
206
207
# File 'lib/google_drive/session.rb', line 201

def spreadsheet_by_url(url)
  file = file_by_url(url)
  if !file.is_a?(Spreadsheet)
    raise(GoogleDrive::Error, "The file with the URL is not a spreadsheet: %s" % url)
  end
  return file
end

#spreadsheets(params = {}, &block) ⇒ Object

Returns list of spreadsheets for the user as array of GoogleDrive::Spreadsheet. You can specify query parameters e.g. “title”, “title-exact”.

e.g.

session.spreadsheets
session.spreadsheets("q" => "title = 'hoge'")
session.spreadsheets("q" => ["title = ?", "hoge"])  # Same as above with a placeholder

By default, it returns the first 100 spreadsheets. See document of files method for how to get all spreadsheets.



169
170
171
172
173
174
175
176
# File 'lib/google_drive/session.rb', line 169

def spreadsheets(params = {}, &block)
  params = convert_params(params)
  query = construct_and_query([
      "mimeType = 'application/vnd.google-apps.spreadsheet'",
      params["q"],
  ])
  return files(params.merge({"q" => query}), &block)
end

#upload_from_file(path, title = nil, params = {}) ⇒ Object

Uploads a local file. Returns a GoogleSpreadsheet::File object.

e.g.

# Uploads a text file and converts to a Google Docs document:
session.upload_from_file("/path/to/hoge.txt")

# Uploads without conversion:
session.upload_from_file("/path/to/hoge.txt", "Hoge", :convert => false)

# Uploads with explicit content type:
session.upload_from_file("/path/to/hoge", "Hoge", :content_type => "text/plain")

# Uploads a text file and converts to a Google Spreadsheet:
session.upload_from_file("/path/to/hoge.csv", "Hoge")
session.upload_from_file("/path/to/hoge", "Hoge", :content_type => "text/csv")


326
327
328
329
330
331
# File 'lib/google_drive/session.rb', line 326

def upload_from_file(path, title = nil, params = {})
  file_name = ::File.basename(path)
  params = {:file_name => file_name}.merge(params)
  media = new_upload_io(path, params)
  return upload_from_media(media, title || file_name, params)
end

#upload_from_io(io, title = "Untitled", params = {}) ⇒ Object

Uploads a file. Reads content from io. Returns a GoogleSpreadsheet::File object.



335
336
337
338
# File 'lib/google_drive/session.rb', line 335

def upload_from_io(io, title = "Untitled", params = {})
  media = new_upload_io(io, params)
  return upload_from_media(media, title, params)
end

#upload_from_media(media, title = "Untitled", params = {}) ⇒ Object

Uploads a file. Reads content from media. Returns a GoogleSpreadsheet::File object.



342
343
344
345
346
347
348
349
350
351
352
353
354
355
# File 'lib/google_drive/session.rb', line 342

def upload_from_media(media, title = "Untitled", params = {})
  file = self.drive.files.insert.request_schema.new({
    "title" => title,
  })
  api_result = execute!(
      :api_method => self.drive.files.insert,
      :body_object => file,
      :media => media,
      :parameters => {
          "uploadType" => "multipart",
          "convert" => params[:convert] == false ? "false" : "true",
      })
  return wrap_api_file(api_result.data)
end

#upload_from_string(content, title = "Untitled", params = {}) ⇒ Object

Uploads a file with the given title and content. Returns a GoogleSpreadsheet::File object.

e.g.

# Uploads and converts to a Google Docs document:
session.upload_from_string(
    "Hello world.", "Hello", :content_type => "text/plain")

# Uploads without conversion:
session.upload_from_string(
    "Hello world.", "Hello", :content_type => "text/plain", :convert => false)

# Uploads and converts to a Google Spreadsheet:
session.upload_from_string("hoge\tfoo\n", "Hoge", :content_type => "text/tab-separated-values")
session.upload_from_string("hoge,foo\n", "Hoge", :content_type => "text/tsv")


305
306
307
308
# File 'lib/google_drive/session.rb', line 305

def upload_from_string(content, title = "Untitled", params = {})
  media = new_upload_io(StringIO.new(content), params)
  return upload_from_media(media, title, params)
end

#worksheet_by_url(url) ⇒ Object

Returns GoogleDrive::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")


223
224
225
226
227
228
229
230
231
# File 'lib/google_drive/session.rb', line 223

def worksheet_by_url(url)
  if !(url =~
      %r{^https?://spreadsheets.google.com/feeds/cells/(.*)/(.*)/private/full((\?.*)?)$})
    raise(GoogleDrive::Error, "URL is not a cell-based feed URL: #{url}")
  end
  worksheet_feed_url = "https://spreadsheets.google.com/feeds/worksheets/#{$1}/private/full/#{$2}#{$3}"
  worksheet_feed_entry = request(:get, worksheet_feed_url)
  return Worksheet.new(self, nil, worksheet_feed_entry)
end

#wrap_api_file(api_file) ⇒ Object

:nodoc:



357
358
359
360
361
362
363
364
365
366
# File 'lib/google_drive/session.rb', line 357

def wrap_api_file(api_file) #:nodoc:
  case api_file.mime_type
    when "application/vnd.google-apps.folder"
      return Collection.new(self, api_file)
    when "application/vnd.google-apps.spreadsheet"
      return Spreadsheet.new(self, api_file)
    else
      return File.new(self, api_file)
  end
end