Class: GoogleDrive::File

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

Overview

A file in Google Drive, including Google Docs document/spreadsheet/presentation.

Use GoogleDrive::Session#files or GoogleDrive::Session#file_by_title to get this object.

In addition to the methods below, properties defined here are also available as attributes: developers.google.com/drive/v2/reference/files#resource

e.g.,

file.mime_type  # ==> "text/plain"

Direct Known Subclasses

Collection, Spreadsheet

Constant Summary

Constants included from Util

Util::EXT_TO_CONTENT_TYPE

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Util

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

Constructor Details

#initialize(session, api_file) ⇒ File

:nodoc:



29
30
31
32
33
34
# File 'lib/google_drive/file.rb', line 29

def initialize(session, api_file) #:nodoc:
  @session = session
  @api_file = api_file
  @acl = nil
  delegate_api_methods(self, @api_file, ["title"])
end

Instance Attribute Details

#api_fileObject (readonly)

Wrapped Google::APIClient::Schema::Drive::V2::File object.



37
38
39
# File 'lib/google_drive/file.rb', line 37

def api_file
  @api_file
end

Instance Method Details

#acl(params = {}) ⇒ Object

Returns GoogleDrive::Acl object for the file.

With the object, you can see and modify people who can access the file. Modifications take effect immediately.

e.g.

# Dumps people who have access:
for entry in file.acl
  p [entry.scope_type, entry.scope, entry.role]
  # => e.g. ["user", "[email protected]", "owner"]
end

# Shares the file with new people:
# NOTE: This sends email to the new people.
file.acl.push(
    {:type => "user", :value => "[email protected]", :role => "reader"})
file.acl.push(
    {:type => "user", :value => "[email protected]", :role => "writer"})

# Changes the role of a person:
file.acl[1].role = "writer"

# Deletes an ACL entry:
file.acl.delete(file.acl[1])


288
289
290
291
292
293
# File 'lib/google_drive/file.rb', line 288

def acl(params = {})
  if !@acl || params[:reload]
    @acl = Acl.new(@session, self)
  end
  return @acl
end

#acl_feed_urlObject

Deprecated ACL feed URL of the file.



61
62
63
# File 'lib/google_drive/file.rb', line 61

def acl_feed_url
  return self.document_feed_url + "/acl"
end

#available_content_typesObject

Content types you can specify in methods download_to_file, download_to_string, download_to_io .

This returns zero or one file type. You may be able to download the file in other formats using export_as_file, export_as_string, or export_to_io. Use export_links method to get available formats in these methods.



89
90
91
92
93
94
95
# File 'lib/google_drive/file.rb', line 89

def available_content_types
  if self.api_file.download_url
    return [self.api_file.mime_type]
  else
    return []
  end
end

#copy(title) ⇒ Object Also known as: duplicate

Creates copy of this file with the given title.



251
252
253
254
255
256
257
258
259
260
# File 'lib/google_drive/file.rb', line 251

def copy(title)
  copied_file = @session.drive.files.copy.request_schema.new({
      "title" => title,
  })
  api_result = @session.execute!(
      :api_method => @session.drive.files.copy,
      :body_object => copied_file,
      :parameters => {"fileId" => self.id})
  return @session.wrap_api_file(api_result.data)
end

#delete(permanent = false) ⇒ Object

If permanent is false, moves the file to the trash. If permanent is true, deletes the file permanently.



226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/google_drive/file.rb', line 226

def delete(permanent = false)
  if permanent
    @session.execute!(
        :api_method => @session.drive.files.delete,
        :parameters => {"fileId" => self.id})
  else
    @session.execute!(
        :api_method => @session.drive.files.trash,
        :parameters => {"fileId" => self.id})
  end
  return nil
end

#document_feed_urlObject

URL of feed used in the deprecated document list feed API.



56
57
58
# File 'lib/google_drive/file.rb', line 56

def document_feed_url
  return "https://docs.google.com/feeds/default/private/full/" + CGI.escape(self.resource_id)
end

#download_to_file(path, params = {}) ⇒ Object

Downloads the file to a local file. e.g.

file.download_to_file("/path/to/hoge.txt")

To export the file in other formats, use export_as_file.



101
102
103
104
105
# File 'lib/google_drive/file.rb', line 101

def download_to_file(path, params = {})
  open(path, "wb") do |f|
    download_to_io(f, params)
  end
end

#download_to_io(io, params = {}) ⇒ Object

Downloads the file and writes it to io.

To export the file in other formats, use export_to_io.



119
120
121
122
123
124
125
126
# File 'lib/google_drive/file.rb', line 119

def download_to_io(io, params = {})
  if !self.api_file.download_url
    raise(GoogleDrive::Error, "Downloading is not supported for this file.")
  end
  # TODO Use streaming if possible.
  api_result = @session.execute!(:uri => self.api_file.download_url)
  io.write(api_result.body)
end

#download_to_string(params = {}) ⇒ Object

Downloads the file and returns as a String.

To export the file in other formats, use export_as_string.



110
111
112
113
114
# File 'lib/google_drive/file.rb', line 110

def download_to_string(params = {})
  sio = StringIO.new()
  download_to_io(sio, params)
  return sio.string
end

#export_as_file(path, format = nil) ⇒ Object

Export the file to path in content type format. If format is nil, it is guessed from the file name.

e.g.,

spreadsheet.export_as_file("/path/to/hoge.csv")
spreadsheet.export_as_file("/path/to/hoge", "text/csv")

If you want to download the file in the original format, use download_to_file instead.



136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/google_drive/file.rb', line 136

def export_as_file(path, format = nil)
  if !format
    format = EXT_TO_CONTENT_TYPE[::File.extname(path).downcase]
    if !format
      raise(ArgumentError,
          ("Cannot guess format from the file name: %s\n" +
           "Specify format argument explicitly.") %
          path)
    end
  end
  open(path, "wb") do |f|
    export_to_io(f, format)
  end
end

#export_as_string(format) ⇒ Object

Export the file as String in content type format.

e.g.,

spreadsheet.export_as_string("text/csv")

If you want to download the file in the original format, use download_to_string instead.



157
158
159
160
161
# File 'lib/google_drive/file.rb', line 157

def export_as_string(format)
  sio = StringIO.new()
  export_to_io(sio, format)
  return sio.string
end

#export_to_io(io, format) ⇒ Object

Export the file to io in content type format.

If you want to download the file in the original format, use download_to_io instead.



166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/google_drive/file.rb', line 166

def export_to_io(io, format)
  mime_type = EXT_TO_CONTENT_TYPE["." + format] || format
  if !self.export_links
    raise(
        GoogleDrive::Error,
        "This file doesn't support exporting. You may still download the file in the " +
        "original format using download_to_file, download_to_string or download_to_io.")
  end
  export_url = self.export_links[mime_type]
  if !export_url
    raise(
        GoogleDrive::Error,
        "This file doesn't support export with mime type %p. Supported mime types: %p" %
            [mime_type, self.export_links.to_hash().keys])
  end
  # TODO Use streaming if possible.
  api_result = @session.execute!(:uri => export_url)
  io.write(api_result.body)
end

#human_urlObject

URL to view/edit the file in a Web browser.

e.g. “docs.google.com/file/d/xxxx/edit



79
80
81
# File 'lib/google_drive/file.rb', line 79

def human_url
  return self.alternate_link
end

#inspectObject



295
296
297
# File 'lib/google_drive/file.rb', line 295

def inspect
  return "\#<%p id=%p title=%p>" % [self.class, self.id, self.title]
end

#reload_metadataObject

Reloads file metadata such as title and acl.



40
41
42
43
44
45
46
47
48
# File 'lib/google_drive/file.rb', line 40

def ()
  api_result = @session.execute!(
    :api_method => @session.drive.files.get,
    :parameters => { "fileId" => self.id })
  @api_file = api_result.data
  if @acl
    @acl = Acl.new(@session, self)
  end
end

#rename(title) ⇒ Object Also known as: title=

Renames title of the file.



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

def rename(title)
  api_result = @session.execute!(
      :api_method => @session.drive.files.patch,
      :body_object => {"title" => title},
      :parameters => {"fileId" => self.id})
  @api_file = api_result.data
end

#resource_idObject

Returns resource_type + “:” + id.



51
52
53
# File 'lib/google_drive/file.rb', line 51

def resource_id
  return "%s:%s" % [self.resource_type, self.id]
end

#resource_typeObject

The type of resourse. e.g. “document”, “spreadsheet”, “folder”



66
67
68
# File 'lib/google_drive/file.rb', line 66

def resource_type
  return self.mime_type.slice(/^application\/vnd.google-apps.(.+)$/, 1) || "file"
end

#title(params = {}) ⇒ Object

Title of the file.



71
72
73
74
# File 'lib/google_drive/file.rb', line 71

def title(params = {})
  () if params[:reload]
  return self.api_file.title
end

#update_from_file(path, params = {}) ⇒ Object

Updates the file with the content of the local file.

e.g.

file.update_from_file("/path/to/hoge.txt")


199
200
201
202
203
204
# File 'lib/google_drive/file.rb', line 199

def update_from_file(path, params = {})
  file_name = ::File.basename(path)
  params = {:file_name => file_name}.merge(params)
  media = new_upload_io(path, params)
  return update_from_media(media, params)
end

#update_from_io(io, params = {}) ⇒ Object

Reads content from io and updates the file with the content.



207
208
209
210
# File 'lib/google_drive/file.rb', line 207

def update_from_io(io, params = {})
  media = new_upload_io(io, params)
  return update_from_media(media, params)
end

#update_from_media(media, params = {}) ⇒ Object

Reads content from media and updates the file with the content.



213
214
215
216
217
218
219
220
221
222
# File 'lib/google_drive/file.rb', line 213

def update_from_media(media, params = {})
  api_result = @session.execute!(
      :api_method => @session.drive.files.update,
      :media => media,
      :parameters => {
        "fileId" => self.id,
        "uploadType" => "media",
      })
  return @session.wrap_api_file(api_result.data)
end

#update_from_string(content, params = {}) ⇒ Object

Updates the file with content.

e.g.

file.update_from_string("Good bye, world.")


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

def update_from_string(content, params = {})
  media = new_upload_io(StringIO.new(content), params)
  return update_from_media(media, params)
end