Class: GoogleDriver::Api

Inherits:
Object
  • Object
show all
Defined in:
lib/google_driver/api.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(scope, issuer, p12_path) ⇒ Api

Returns a new instance of Api.



7
8
9
10
11
12
13
# File 'lib/google_driver/api.rb', line 7

def initialize(scope, issuer, p12_path)
  @oauth_scope = scope
  @issuer = issuer
  @p12_path = p12_path

  google_authorize
end

Instance Attribute Details

#clientObject

Returns the value of attribute client.



5
6
7
# File 'lib/google_driver/api.rb', line 5

def client
  @client
end

#driveObject

Returns the value of attribute drive.



5
6
7
# File 'lib/google_driver/api.rb', line 5

def drive
  @drive
end

Instance Method Details

#detect_mimetype(file) ⇒ Object



33
34
35
36
37
# File 'lib/google_driver/api.rb', line 33

def detect_mimetype(file)
  # use the unix `file` program to get the mimetype of the file
  %x<file --mime-type '#{file}'>.split(':')[1].strip()
  # check success with $?.success? (perlism)
end

#google_authorizeObject



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/google_driver/api.rb', line 15

def google_authorize
  @client = Google::APIClient.new(application_name:"GoogleDriver", application_version:VERSION)
  @drive = @client.discovered_api('drive', 'v2')

  # Create a new server<>server based API client
  key = Google::APIClient::KeyUtils.load_from_pkcs12(@p12_path, 'notasecret')

  # Request Auth
  @client.authorization = Signet::OAuth2::Client.new(
      token_credential_uri: 'https://accounts.google.com/o/oauth2/token',
      audience: 'https://accounts.google.com/o/oauth2/token',
      scope: @oauth_scope,
      issuer: @issuer,
      signing_key: key)

    @client.authorization.fetch_access_token!
end

#upload(file, title = "A document", description = "Words, words, words") ⇒ Object

::file path to a file you wish to upload [REQUIRED] ::title title of the document for browsing on google drive ::description description of the document for browsing on google drive



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/google_driver/api.rb', line 43

def upload(file, title="A document", description="Words, words, words")
  #
  # TODO: throw warning if people don't name documents

  resource = @drive.files.insert.request_schema.new(
    'title' => title,
    'description' => description
  )

  mimetype = detect_mimetype(file)

  media = Google::APIClient::UploadIO.new(file, mimetype)

  response = @client.execute(
    api_method: @drive.files.insert,
    body_object: resource,
    media: media,
    parameters: {
      'uploadType' => 'multipart',
      'convert' => true,
      'alt' => 'json'})
  Document.new(response, self)
end

#upload_files(*files) ⇒ Object



67
68
69
70
71
# File 'lib/google_driver/api.rb', line 67

def upload_files(*files)
  files.map do |file|
    upload(file)
  end
end