Class: GoogleDrive::Session

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

Overview

A session for Google Drive operations.

Use from_credentials, from_access_token, from_service_account_key or from_config class method to construct a GoogleDrive::Session object.

Constant Summary collapse

DEFAULT_SCOPE =
[
  'https://www.googleapis.com/auth/drive',
  'https://spreadsheets.google.com/feeds/'
].freeze

Constants included from Util

Util::EXT_TO_CONTENT_TYPE, Util::IMPORTABLE_CONTENT_TYPE_MAP

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

Constructor Details

#initialize(credentials_or_access_token, proxy = nil) ⇒ Session

Returns a new instance of Session.



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/google_drive/session.rb', line 159

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

  if credentials_or_access_token
    if credentials_or_access_token.is_a?(String)
      credentials = AccessTokenCredentials.new(credentials_or_access_token)
    # Equivalent of credentials_or_access_token.is_a?(OAuth2::AccessToken),
    # without adding dependency to "oauth2" library.
    elsif credentials_or_access_token
          .class
          .ancestors
          .any? { |m| m.name == 'OAuth2::AccessToken' }
      credentials =
        AccessTokenCredentials.new(credentials_or_access_token.token)
    else
      credentials = credentials_or_access_token
    end
    @fetcher = ApiClientFetcher.new(credentials)
  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.



190
191
192
# File 'lib/google_drive/session.rb', line 190

def on_auth_fail
  @on_auth_fail
end

Class Method Details

.from_access_token(access_token) ⇒ Object

Constructs a GoogleDrive::Session object from OAuth2 access token string.



58
59
60
# File 'lib/google_drive/session.rb', line 58

def self.from_access_token(access_token)
  Session.new(access_token)
end

.from_config(config, options = {}) ⇒ Object

Returns GoogleDrive::Session constructed from a config JSON file at config.

config is the path to the config file.

This will prompt the credential via command line for the first time and save it to config for later usages.

See github.com/gimite/google-drive-ruby/blob/master/doc/authorization.md for a usage example.

You can also provide a config object that must respond to:

client_id
client_secret
refesh_token
refresh_token=
scope
scope=
save


105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/google_drive/session.rb', line 105

def self.from_config(config, options = {})
  if config.is_a?(String)
    config_path = config
    config = Config.new(config_path)
    if config.type == 'service_account'
      return (
        config_path, options[:scope] || DEFAULT_SCOPE
      )
    end
  end

  config.scope ||= DEFAULT_SCOPE

  if options[:client_id] && options[:client_secret]
    config.client_id = options[:client_id]
    config.client_secret = options[:client_secret]
  end
  if !config.client_id && !config.client_secret
    config.client_id =
      '452925651630-egr1f18o96acjjvphpbbd1qlsevkho1d.' \
      'apps.googleusercontent.com'
    config.client_secret = '1U3-Krii5x1oLPrwD5zgn-ry'
  elsif !config.client_id || !config.client_secret
    raise(
      ArgumentError,
      'client_id and client_secret must be both specified or both omitted'
    )
  end

  credentials = Google::Auth::UserRefreshCredentials.new(
    client_id: config.client_id,
    client_secret: config.client_secret,
    scope: config.scope,
    redirect_uri: 'urn:ietf:wg:oauth:2.0:oob'
  )

  if config.refresh_token
    credentials.refresh_token = config.refresh_token
    credentials.fetch_access_token!
  else
    $stderr.print(
      format("\n1. Open this page:\n%s\n\n", credentials.authorization_uri)
    )
    $stderr.print('2. Enter the authorization code shown in the page: ')
    credentials.code = $stdin.gets.chomp
    credentials.fetch_access_token!
    config.refresh_token = credentials.refresh_token
  end

  config.save

  Session.new(credentials)
end

.from_credentials(credentials) ⇒ Object

Constructs a GoogleDrive::Session object from OAuth2 credentials such as Google::Auth::UserRefreshCredentials.

See github.com/gimite/google-drive-ruby/blob/master/doc/authorization.md for a usage example.



53
54
55
# File 'lib/google_drive/session.rb', line 53

def self.from_credentials(credentials)
  Session.new(credentials)
end

.from_service_account_key(json_key_path_or_io, scope = DEFAULT_SCOPE) ⇒ Object

Constructs a GoogleDrive::Session object from a service account key JSON.

You can pass either the path to a JSON file, or an IO-like object with the JSON.

See github.com/gimite/google-drive-ruby/blob/master/doc/authorization.md for a usage example.



70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/google_drive/session.rb', line 70

def self.(
    json_key_path_or_io, scope = DEFAULT_SCOPE
)
  if json_key_path_or_io.is_a?(String)
    open(json_key_path_or_io) do |f|
      (f, scope)
    end
  else
    credentials = Google::Auth::ServiceAccountCredentials.make_creds(
      json_key_io: json_key_path_or_io, scope: scope
    )
    Session.new(credentials)
  end
end

.login_with_oauth(credentials_or_access_token, proxy = nil) ⇒ Object

Equivalent of either from_credentials or from_access_token.



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

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

.new_dummyObject

Creates a dummy GoogleDrive::Session object for testing.



43
44
45
# File 'lib/google_drive/session.rb', line 43

def self.new_dummy
  Session.new(nil)
end

Instance Method Details

#collection_by_title(title) ⇒ Object Also known as: folders_by_name

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



393
394
395
# File 'lib/google_drive/session.rb', line 393

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

#collection_by_url(url) ⇒ Object Also known as: folder_by_url

Returns GoogleDrive::Collection with given url.

You must specify the URL of the page you get when you go to drive.google.com/ with your browser and open a folder.

e.g.

session.collection_by_url(
  "https://drive.google.com/drive/folders/" \
  "1u99gpfHIk08RVK5q_vXxUqkxR1r6FUJH")


408
409
410
411
412
413
414
415
416
417
# File 'lib/google_drive/session.rb', line 408

def collection_by_url(url)
  file = file_by_url(url)
  unless file.is_a?(Collection)
    raise(
      GoogleDrive::Error,
      format('The file with the URL is not a folder: %s', url)
    )
  end
  file
end

#collections(params = {}, &block) ⇒ Object Also known as: folders

Returns the top-level folders (direct children of the root folder).

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



383
384
385
# File 'lib/google_drive/session.rb', line 383

def collections(params = {}, &block)
  root_collection.subcollections(params, &block)
end

#create_spreadsheet(title = 'Untitled') ⇒ Object

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

e.g.

session.create_spreadsheet("My new sheet")


425
426
427
428
429
430
431
432
433
434
# File 'lib/google_drive/session.rb', line 425

def create_spreadsheet(title = 'Untitled')
   = {
    name:    title,
    mime_type: 'application/vnd.google-apps.spreadsheet'
  }
  file = drive.create_file(
    , fields: '*', supports_team_drives: true
  )
  wrap_api_file(file)
end

#driveObject

Returns an instance of Google::Apis::DriveV3::DriveService.



193
194
195
# File 'lib/google_drive/session.rb', line 193

def drive
  @fetcher.drive
end

#execute_paged!(opts, &block) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
# File 'lib/google_drive/session.rb', line 507

def execute_paged!(opts, &block)
  if block
    page_token = nil
    loop do
      parameters =
        (opts[:parameters] || {}).merge(page_token: page_token)
      (items, page_token) =
        execute_paged!(opts.merge(parameters: parameters))
      items.each(&block)
      break unless page_token
    end

  elsif opts[:parameters] && opts[:parameters].key?(:page_token)
    response = opts[:method].call(opts[:parameters])
    items    = response.__send__(opts[:items_method_name]).map do |item|
      opts[:converter] ? opts[:converter].call(item) : item
    end
    [items, response.next_page_token]

  else
    parameters = (opts[:parameters] || {}).merge(page_token: nil)
    (items,) = execute_paged!(opts.merge(parameters: parameters))
    items
  end
end

#file_by_id(id) ⇒ Object

Returns a file (including a spreadsheet and a folder) with a given id.

Returns an instance of GoogleDrive::File or its subclass (GoogleDrive::Spreadsheet, GoogleDrive::Collection).



253
254
255
256
# File 'lib/google_drive/session.rb', line 253

def file_by_id(id)
  api_file = drive.get_file(id, fields: '*', supports_team_drives: true)
  wrap_api_file(api_file)
end

#file_by_title(title) ⇒ Object Also known as: file_by_name

Returns a file (including a spreadsheet and a folder) whose title exactly matches title.

Returns an instance of GoogleDrive::File or its subclass (GoogleDrive::Spreadsheet, GoogleDrive::Collection). Returns nil if not found. If multiple files with the title are found, returns one of them.

If given an Array, traverses folders by title. e.g.:

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


239
240
241
242
243
244
245
# File 'lib/google_drive/session.rb', line 239

def file_by_title(title)
  if title.is_a?(Array)
    root_collection.file_by_title(title)
  else
    files(q: ['name = ?', title], page_size: 1)[0]
  end
end

#file_by_url(url) ⇒ Object

Returns a file (including a spreadsheet and a folder) with a given url. url must be the URL of the page you open to access a document/spreadsheet in your browser.

Returns an instance of GoogleDrive::File or its subclass (GoogleDrive::Spreadsheet, GoogleDrive::Collection).



264
265
266
# File 'lib/google_drive/session.rb', line 264

def file_by_url(url)
  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/v3/web/search-parameters

e.g.

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

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(page_token: page_token)
  p files
end while page_token


218
219
220
221
222
223
224
225
226
227
# File 'lib/google_drive/session.rb', line 218

def files(params = {}, &block)
  params = convert_params(params)
  execute_paged!(
    method: drive.method(:list_files),
    parameters: { fields: '*', supports_team_drives: true }.merge(params),
    items_method_name: :files,
    converter: proc { |af| wrap_api_file(af) },
    &block
  )
end

#inspectObject



565
566
567
# File 'lib/google_drive/session.rb', line 565

def inspect
  format('#<%p:0x%x>', self.class, object_id)
end

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

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
# File 'lib/google_drive/session.rb', line 534

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

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

  loop do
    response = @fetcher.request_raw(method, url, data, extra_header, auth)
    next if response.code == '401' && @on_auth_fail && @on_auth_fail.call
    unless 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 Also known as: root_folder

Returns the root folder.



373
374
375
# File 'lib/google_drive/session.rb', line 373

def root_collection
  @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")


298
299
300
301
302
303
304
305
306
307
# File 'lib/google_drive/session.rb', line 298

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

#spreadsheet_by_title(title) ⇒ Object Also known as: spreadsheet_by_name

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



332
333
334
# File 'lib/google_drive/session.rb', line 332

def spreadsheet_by_title(title)
  spreadsheets(q: ['name = ?', title], page_size: 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")


318
319
320
321
322
323
324
325
326
327
# File 'lib/google_drive/session.rb', line 318

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

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

Returns list of spreadsheets for the user as array of GoogleDrive::Spreadsheet. You can specify parameters documented at developers.google.com/drive/v3/web/search-parameters

e.g.

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

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



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

def spreadsheets(params = {}, &block)
  params = convert_params(params)
  query  = construct_and_query(
    [
      "mimeType = 'application/vnd.google-apps.spreadsheet'",
      params[:q]
    ]
  )
  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")


475
476
477
478
479
480
481
482
483
484
485
486
# File 'lib/google_drive/session.rb', line 475

def upload_from_file(path, title = nil, params = {})
  # TODO: Add a feature to upload to a folder.
  file_name = ::File.basename(path)
  default_content_type =
    EXT_TO_CONTENT_TYPE[::File.extname(file_name).downcase] ||
    'application/octet-stream'
  upload_from_source(
    path,
    title || file_name,
    { content_type: default_content_type }.merge(params)
  )
end

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

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



490
491
492
# File 'lib/google_drive/session.rb', line 490

def upload_from_io(io, title = 'Untitled', params = {})
  upload_from_source(io, title, params)
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")


453
454
455
# File 'lib/google_drive/session.rb', line 453

def upload_from_string(content, title = 'Untitled', params = {})
  upload_from_source(StringIO.new(content), title, params)
end

#worksheet_by_url(url) ⇒ Object

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

e.g.:

# Worksheet feed URL
session.worksheet_by_url(
  "https://spreadsheets.google.com/feeds/worksheets/" \
  "1smypkyAz4STrKO4Zkos5Z4UPUJKvvgIza32LnlQ7OGw/private/full/od7")
# Cell-based feed URL
session.worksheet_by_url(
  "https://spreadsheets.google.com/feeds/cells/" \
  "1smypkyAz4STrKO4Zkos5Z4UPUJKvvgIza32LnlQ7OGw/od7/private/full")


351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
# File 'lib/google_drive/session.rb', line 351

def worksheet_by_url(url)
  case url
  when %r{^https?://spreadsheets.google.com/feeds/worksheets/.*/.*/full/.*$}
    worksheet_feed_url = url
  when %r{^https?://spreadsheets.google.com/feeds/cells/(.*)/(.*)/private/full((\?.*)?)$}
    worksheet_feed_url =
      'https://spreadsheets.google.com/feeds/worksheets/' \
      "#{Regexp.last_match(1)}/private/full/" \
      "#{Regexp.last_match(2)}#{Regexp.last_match(3)}"
  else
    raise(
      GoogleDrive::Error,
      'URL is neither a worksheet feed URL nor a cell-based feed URL: ' \
      "#{url}"
    )
  end

  worksheet_feed_entry = request(:get, worksheet_feed_url)
  Worksheet.new(self, nil, worksheet_feed_entry)
end

#wrap_api_file(api_file) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



495
496
497
498
499
500
501
502
503
504
# File 'lib/google_drive/session.rb', line 495

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