Module: Dewey

Defined in:
lib/dewey.rb,
lib/dewey/core.rb,
lib/dewey/mime.rb,
lib/dewey/utils.rb,
lib/dewey/version.rb,
lib/dewey/validation.rb,
lib/dewey/client_auth.rb

Defined Under Namespace

Modules: Utils Classes: ClientAuth, DeweyAuthorizationError, DeweyError, Mime, Validation

Constant Summary collapse

GOOGLE_DOCS_URL =
"https://docs.google.com"
GOOGLE_SPRD_URL =
"https://spreadsheets.google.com"
GOOGLE_LOGIN_URL =
"https://www.google.com/accounts/ClientLogin"
GOOGLE_FEED_URL =
GOOGLE_DOCS_URL + "/feeds/default/private/full"
GOOGLE_DOCUMENT_URL =
GOOGLE_DOCS_URL + "/feeds/download/documents/Export"
GOOGLE_DRAWING_URL =
GOOGLE_DOCS_URL + "/feeds/download/drawings/Export"
GOOGLE_PRESENTATION_URL =
GOOGLE_DOCS_URL + "/feeds/download/presentations/Export"
GOOGLE_SPREADSHEET_URL =
GOOGLE_SPRD_URL + "/feeds/download/spreadsheets/Export"
DOCUMENT_MIMETYPES =
{
  :doc  => ['application/msword', 'application/vnd.ms-office'],
  :docx => ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/x-docx', 'application/zip'],
  :htm  => 'text/html',
  :html => 'text/html',
  :odt  => 'application/vnd.oasis.opendocument.text',
  :pdf  => 'application/pdf',
  :rtf  => 'application/rtf',
  :sxw  => 'application/vnd.sun.xml.writer',
  :txt  => 'text/plain'
}
DRAWING_MIMETYPES =
{
  :jpeg => 'image/jpeg',
  :png  => 'image/png',
  :svg  => 'image/svg+xml'
}
PRESENTATION_MIMETYPES =
{
  :pps => 'application/vnd.ms-powerpoint',
  :ppt => 'application/vnd.ms-powerpoint'
}
SPREADSHEET_MIMETYPES =
{
  :csv  => 'text/csv',
  :ods  => 'application/x-vnd.oasis.opendocument.spreadsheet',
  :tab  => 'text/tab-separated-values',
  :tsv  => 'text/tab-separated-values',
  :xls  => 'application/vnd.ms-excel',
  :xlsx => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}
VERSION =
'0.2.10'
DOCUMENT_EXPORT_FORMATS =
[:txt, :odt, :pdf, :html, :rtf, :doc, :png, :zip]
DRAWING_EXPORT_FORMATS =
[:jpeg, :pdf, :png, :svg]
PRESENTATION_EXPORT_FORMATS =
[:swf, :pdf, :png, :ppt]
SPREADSHEET_EXPORT_FORMATS =
[:xls, :csv, :pdf, :ods, :tsv, :html]

Class Method Summary collapse

Class Method Details

.authenticate!Object

Tell the authentication strategy to authenticate. Not necessary though, as any file operation will authenticate automatically.



30
31
32
# File 'lib/dewey/core.rb', line 30

def authenticate!
  @@authenticator.authenticate!
end

.authenticated?Boolean

Report whether Dewey has both an authentication strategy selected, and has been authenticated. Delegates to the chosen authenticator.

Returns:

  • (Boolean)


23
24
25
# File 'lib/dewey/core.rb', line 23

def authenticated?
  !@@authenticator.nil? && @@authenticator.authenticated?
end

.authentication(strategy, options) ⇒ Object

Set the authentication strategy. You can currently only use ClientAuth, but you must provide email and password options. You must set up authentication before using any file operations.



13
14
15
16
17
18
# File 'lib/dewey/core.rb', line 13

def authentication(strategy, options)
  case strategy
  when :client
    @@authenticator = Dewey::ClientAuth.new(options[:email], options[:password])
  end
end

.convert(file, options = {}) ⇒ Tempfile

Convenience method for ‘put`, `get`, `delete`.

Parameters:

  • file (File)

    The file that will be converted

  • options (Hash) (defaults to: {})

    Options for conversion

Options Hash (options):

  • :title (Symbol)

    The title that the file will be stored under. Only useful if the conversion fails.

  • :format (Symbol)

    Format to convert to.

Returns:

  • (Tempfile)

    The converted file

See Also:

  • #put
  • #get
  • #delete


204
205
206
207
208
209
210
211
# File 'lib/dewey/core.rb', line 204

def convert(file, options = {})
  id = put(file, options)
  converted = get(id, options)

  delete(id)

  converted
end

.delete(query, options = {}) ⇒ Boolean

Deletes a document. The default behavior is to delete the document permanently, rather than trashing it.

Parameters:

  • query (String)

    A resource id or title. If a title is provided a search will be performed automatically.

  • options (Hash) (defaults to: {})

    Options for deleting the document

Options Hash (options):

  • :trash (Symbol)

    If ‘true` the resource will be sent to the trash, rather than being permanently deleted.

Returns:

  • (Boolean)

    ‘true` if delete was successful, `false` otherwise



166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/dewey/core.rb', line 166

def delete(query, options = {})

  # We use 'If-Match' => '*' to make sure we delete regardless of others
  headers = base_headers.merge({'If-Match' => '*'})
  trash   = options.delete(:trash) || false
  id      = (is_id?(query)) ? query : search(query, :exact => true).first

  return false if id.nil?

  url   = "#{GOOGLE_FEED_URL}/#{URI.escape(id)}"
  url << "?delete=true" unless trash

  response = http_request(:delete, url, headers)

  response.kind_of?(Net::HTTPOK)
end

.delete!(query, options = {}) ⇒ Object

The same as delete, except that it will raise ‘Dewey::DeweyError` if the request fails.

See Also:

  • #delete


187
188
189
# File 'lib/dewey/core.rb', line 187

def delete!(query, options = {})
  delete(query, options) || raise(DeweyError, "Unable to delete document")
end

.get(query, options = {}) ⇒ Tempfile?

Download a file. You may optionally specify a format for export.

Parameters:

  • query (String)

    A resource id or title, ‘document:12345` or `My Document` for example

  • options (Hash) (defaults to: {})

    Options for downloading the document

Options Hash (options):

  • :format (Symbol)

    The output format

Returns:

  • (Tempfile, nil)

    The downloaded file, otherwise ‘nil` if the file couldn’t be found.

See Also:

  • Dewey::Validation::DOCUMENT_EXPORT_FORMATS
  • Dewey::Validation::SPREADSHEET_EXPORT_FORMATS
  • Dewey::Validation::PRESENTATION_EXPORT_FORMATS


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
# File 'lib/dewey/core.rb', line 108

def get(query, options = {})
  resource_id = is_id?(query) ? query : search(query, :exact => true).first

  return nil if resource_id.nil?

  service, id = resource_id.split(':')
  format      = options[:format].to_s
  url         = ''

  case service
  when 'document'
    url << GOOGLE_DOCUMENT_URL
    url << "?id=#{id}"
  when 'drawing'
    url << GOOGLE_DRAWING_URL
    url << "?id=#{id}"
  when 'presentation'
    url << GOOGLE_PRESENTATION_URL
    url << "?id=#{id}"
  when 'spreadsheet'
    url << GOOGLE_SPREADSHEET_URL
    url << "?key=#{id}"
  else
    raise DeweyError, "Invalid service: #{service}"
  end

  unless format.empty?
    if Dewey::Validation.valid_export_format?(format, service)
      url << "&exportFormat=#{format}"
      url << "&format=#{format}"       if service == 'document'
      url << "&gid=#{options[:sheet]}" if service == 'spreadsheet' && options[:sheet]
    else
      raise DeweyError, "Invalid format: #{format}"
    end
  end

  response = http_request(:get, url, base_headers(service))

  if response.kind_of?(Net::HTTPOK)
    file = Tempfile.new([id, format].join('.')).binmode
    file.write(response.body)
    file.rewind
    file
  else
    nil
  end
end

.put(file, options = {}) ⇒ String?

Upload a file to the account. A successful upload will return the resource id, which is useful for downloading the file without doing a title search.

Parameters:

  • file (File)

    An IOStream object that responds to path, size

  • options (Hash) (defaults to: {})

    Options for uploading the file

Options Hash (options):

  • :title (Symbol)

    An alternative title, to be used instead of the filename

Returns:

  • (String, nil)

    The id if upload was successful, nil otherwise

Raises:



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/dewey/core.rb', line 62

def put(file, options = {})
  extension = Dewey::Mime.extension(file)
  basename  = File.basename(file.path, ".#{extension}")
  mimetype  = Dewey::Mime.mime_type(file)
  service   = Dewey::Mime.guess_service(mimetype)
  title     = options[:title] || basename

  raise DeweyError, "Invalid file type: #{extension}" unless Dewey::Validation.valid_upload_format?(extension, service)

  headers = base_headers
  headers['Content-Length'] = File.size?(file).to_s
  headers['Slug']           = Dewey::Utils.slug(title)
  headers['Content-Type']   = mimetype unless mimetype =~ /Can't expand summary_info/

  # Rewind the file in the case of multiple uploads, or conversions
  file.rewind

  response = http_request(:post, GOOGLE_FEED_URL, headers, file.read.to_s)

  if response.kind_of?(Net::HTTPCreated)
    extract_ids(response.body).first
  else
    nil
  end
end

.put!(file, options = {}) ⇒ Object

The same as ‘put`, except it will raise an exception if the request fails.

See Also:



91
92
93
# File 'lib/dewey/core.rb', line 91

def put!(file, options = {})
  put(file, options) || raise(DeweyError, "Unable to put document")
end

.search(query, options = {}) ⇒ Array

Queries the document list for a particular title. Titles can be either full or partial matches. Matches are returned as an array of ids.

Parameters:

  • query (String)

    The title to be matched

  • options (Hash) (defaults to: {})

    Search options

Options Hash (options):

  • :exact (Symbol)

    Setting this to ‘true` will force an exact match, with a maximum of one id returned

Returns:

  • (Array)

    An array of matched ids. No matches return an empty array



43
44
45
46
47
48
49
50
51
# File 'lib/dewey/core.rb', line 43

def search(query, options = {})
  title    = query.gsub(/\s+/, '+')
  headers  = base_headers
  url      = "#{GOOGLE_FEED_URL}?title=#{title}"
  url     << "&title-exact=true" if options[:exact]
  response = http_request(:get, url, headers)

  response.kind_of?(Net::HTTPOK) ? extract_ids(response.body) : []
end