Class: GoogleDrive::Session
- Inherits:
-
Object
- Object
- GoogleDrive::Session
- 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, Util::IMPORTABLE_CONTENT_TYPE_MAP
Instance Attribute Summary collapse
-
#on_auth_fail ⇒ Object
Proc or Method called when authentication has failed.
Class Method Summary collapse
-
.login_with_oauth(credentials_or_access_token, proxy = nil) ⇒ Object
The same as GoogleDrive.login_with_oauth.
-
.new_dummy ⇒ Object
Creates a dummy GoogleDrive::Session object for testing.
Instance Method Summary collapse
-
#collection_by_title(title) ⇒ Object
Returns a top-level collection whose title exactly matches
titleas GoogleDrive::Collection. -
#collection_by_url(url) ⇒ Object
Returns GoogleDrive::Collection with given
url. -
#collections(params = {}, &block) ⇒ Object
Returns the top-level collections (direct children of the root collection).
-
#create_spreadsheet(title = 'Untitled') ⇒ Object
Creates new spreadsheet and returns the new GoogleDrive::Spreadsheet.
-
#drive ⇒ Object
Returns an instance of Google::Apis::DriveV3::DriveService.
-
#execute_paged!(opts, &block) ⇒ Object
:nodoc:.
-
#file_by_id(id) ⇒ Object
Returns GoogleDrive::File or its subclass with a given
id. -
#file_by_title(title) ⇒ Object
Returns GoogleDrive::File or its subclass whose title exactly matches
title. -
#file_by_url(url) ⇒ Object
Returns GoogleDrive::File or its subclass with a given
url. -
#files(params = {}, &block) ⇒ Object
Returns list of files for the user as array of GoogleDrive::File or its subclass.
-
#initialize(credentials_or_access_token, proxy = nil) ⇒ Session
constructor
A new instance of Session.
- #inspect ⇒ Object
-
#request(method, url, params = {}) ⇒ Object
:nodoc:.
-
#root_collection ⇒ Object
Returns the root collection.
-
#spreadsheet_by_key(key) ⇒ Object
Returns GoogleDrive::Spreadsheet with given
key. -
#spreadsheet_by_title(title) ⇒ Object
Returns GoogleDrive::Spreadsheet with given
title. -
#spreadsheet_by_url(url) ⇒ Object
Returns GoogleDrive::Spreadsheet with given
url. -
#spreadsheets(params = {}, &block) ⇒ Object
Returns list of spreadsheets for the user as array of GoogleDrive::Spreadsheet.
-
#upload_from_file(path, title = nil, params = {}) ⇒ Object
Uploads a local file.
-
#upload_from_io(io, title = 'Untitled', params = {}) ⇒ Object
Uploads a file.
-
#upload_from_string(content, title = 'Untitled', params = {}) ⇒ Object
Uploads a file with the given
titleandcontent. -
#worksheet_by_url(url) ⇒ Object
Returns GoogleDrive::Worksheet with given
url. -
#wrap_api_file(api_file) ⇒ Object
:nodoc:.
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
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/google_drive/session.rb', line 39 def initialize(credentials_or_access_token, proxy = nil) if proxy fail( 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 = Google::Auth::UserRefreshCredentials.new( access_token: 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 = Google::Auth::UserRefreshCredentials.new( access_token: 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_fail ⇒ Object
Proc or Method called when authentication has failed. When this function returns true, it tries again.
66 67 68 |
# File 'lib/google_drive/session.rb', line 66 def on_auth_fail @on_auth_fail end |
Class Method Details
.login_with_oauth(credentials_or_access_token, proxy = nil) ⇒ Object
The same as GoogleDrive.login_with_oauth.
30 31 32 |
# File 'lib/google_drive/session.rb', line 30 def self.login_with_oauth(credentials_or_access_token, proxy = nil) Session.new(credentials_or_access_token, proxy) end |
.new_dummy ⇒ Object
Creates a dummy GoogleDrive::Session object for testing.
35 36 37 |
# File 'lib/google_drive/session.rb', line 35 def self.new_dummy Session.new(nil) end |
Instance Method Details
#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.
231 232 233 |
# File 'lib/google_drive/session.rb', line 231 def collection_by_title(title) 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")
248 249 250 251 252 253 254 |
# File 'lib/google_drive/session.rb', line 248 def collection_by_url(url) file = file_by_url(url) unless file.is_a?(Collection) fail(GoogleDrive::Error, 'The file with the URL is not a collection: %s' % url) end file end |
#collections(params = {}, &block) ⇒ Object
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.
223 224 225 |
# File 'lib/google_drive/session.rb', line 223 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")
260 261 262 263 264 265 266 267 |
# File 'lib/google_drive/session.rb', line 260 def create_spreadsheet(title = 'Untitled') = { name: title, mime_type: 'application/vnd.google-apps.spreadsheet' } file = self.drive.create_file(, fields: '*') wrap_api_file(file) end |
#drive ⇒ Object
Returns an instance of Google::Apis::DriveV3::DriveService.
69 70 71 |
# File 'lib/google_drive/session.rb', line 69 def drive @fetcher.drive end |
#execute_paged!(opts, &block) ⇒ Object
:nodoc:
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 |
# File 'lib/google_drive/session.rb', line 333 def execute_paged!(opts, &block) #:nodoc: 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 return [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 GoogleDrive::File or its subclass with a given id.
117 118 119 120 |
# File 'lib/google_drive/session.rb', line 117 def file_by_id(id) api_file = self.drive.get_file(id, fields: '*') wrap_api_file(api_file) 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"])
108 109 110 111 112 113 114 |
# File 'lib/google_drive/session.rb', line 108 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 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
125 126 127 |
# File 'lib/google_drive/session.rb', line 125 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'")
session.files(q: ["name = ?", "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(page_token: page_token)
p files
end while page_token
92 93 94 95 96 97 98 99 100 |
# File 'lib/google_drive/session.rb', line 92 def files(params = {}, &block) params = convert_params(params) execute_paged!( method: self.drive.method(:list_files), parameters: {fields: '*'}.merge(params), items_method_name: :files, converter: proc { |af| wrap_api_file(af) }, &block) end |
#inspect ⇒ Object
384 385 386 |
# File 'lib/google_drive/session.rb', line 384 def inspect '#<%p:0x%x>' % [self.class, object_id] end |
#request(method, url, params = {}) ⇒ Object
:nodoc:
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 |
# File 'lib/google_drive/session.rb', line 357 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) 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/ fail((response.code == '401' ? AuthenticationError : ResponseCodeError) .new(response.code, response.body, method, url)) end return convert_response(response, response_type) end end |
#root_collection ⇒ Object
Returns the root collection.
215 216 217 |
# File 'lib/google_drive/session.rb', line 215 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")
154 155 156 157 158 159 160 |
# File 'lib/google_drive/session.rb', line 154 def spreadsheet_by_key(key) file = file_by_id(key) unless file.is_a?(Spreadsheet) fail(GoogleDrive::Error, 'The file with the ID is not a spreadsheet: %s' % key) end 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.
183 184 185 |
# File 'lib/google_drive/session.rb', line 183 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")
session.spreadsheet_by_url(
"https://spreadsheets.google.com/feeds/" +
"worksheets/1L3-kvwJblyW_TvjYD-7pE-AXxw5_bkb6S_MljuIPVL0/private/full")
172 173 174 175 176 177 178 |
# File 'lib/google_drive/session.rb', line 172 def spreadsheet_by_url(url) file = file_by_url(url) unless file.is_a?(Spreadsheet) fail(GoogleDrive::Error, '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'")
session.spreadsheets(q: ["name = ?", "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.
140 141 142 143 144 145 146 147 |
# File 'lib/google_drive/session.rb', line 140 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")
304 305 306 307 308 309 310 311 312 313 314 |
# File 'lib/google_drive/session.rb', line 304 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.
318 319 320 |
# File 'lib/google_drive/session.rb', line 318 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")
284 285 286 |
# File 'lib/google_drive/session.rb', line 284 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")
199 200 201 202 203 204 205 206 207 208 209 210 211 212 |
# File 'lib/google_drive/session.rb', line 199 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 fail(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
:nodoc:
322 323 324 325 326 327 328 329 330 331 |
# File 'lib/google_drive/session.rb', line 322 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 |