Class: CloudDrive::Account

Inherits:
Object
  • Object
show all
Defined in:
lib/clouddrive/account.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(email, client_id, client_secret) ⇒ Account

Returns a new instance of Account.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/clouddrive/account.rb', line 12

def initialize(email, client_id, client_secret)
  @email = email
  @cache_file = File.expand_path("~/.clouddrive/#{email}.cache")
  @client_id = client_id
  @client_secret = client_secret

  @db = SQLite3::Database.new(File.expand_path("~/.clouddrive/#{@email}.db"))
  if @db.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='nodes';").empty?
    @db.execute "     CREATE TABLE nodes(\n        id VARCHAR PRIMARY KEY NOT NULL,\n        name VARCHAR NOT NULL,\n        kind VARCHAR NOT NULL,\n        md5 VARCHAR,\n        created DATETIME NOT NULL,\n        modified DATETIME NOT NULL,\n        raw_data TEXT NOT NULL\n     );\n    SQL\n  end\nend\n"

Instance Attribute Details

#access_tokenObject (readonly)

Returns the value of attribute access_token.



10
11
12
# File 'lib/clouddrive/account.rb', line 10

def access_token
  @access_token
end

#content_urlObject (readonly)

Returns the value of attribute content_url.



10
11
12
# File 'lib/clouddrive/account.rb', line 10

def content_url
  @content_url
end

#dbObject (readonly)

Returns the value of attribute db.



10
11
12
# File 'lib/clouddrive/account.rb', line 10

def db
  @db
end

#emailObject (readonly)

Returns the value of attribute email.



10
11
12
# File 'lib/clouddrive/account.rb', line 10

def email
  @email
end

#metadata_urlObject (readonly)

Returns the value of attribute metadata_url.



10
11
12
# File 'lib/clouddrive/account.rb', line 10

def 
  
end

#token_storeObject (readonly)

Returns the value of attribute token_store.



10
11
12
# File 'lib/clouddrive/account.rb', line 10

def token_store
  @token_store
end

Instance Method Details

#authorize(auth_url = nil) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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
87
88
89
90
91
92
93
94
95
96
# File 'lib/clouddrive/account.rb', line 34

def authorize(auth_url = nil)
  retval = {
    :success => true,
    :data => {}
  }

  @token_store = {
      "checkpoint" => nil,
      "nodes" => {}
  }

  if File.exists?(@cache_file)
    @token_store = JSON.parse(File.read(@cache_file))
  end

  if !@token_store.has_key?("access_token")
    if auth_url.nil?
      retval = {
        :success => false,
        :data => {
          "message" => "Initial authorization required",
          "auth_url" => "https://www.amazon.com/ap/oa?client_id=#{@client_id}&scope=clouddrive%3Aread%20clouddrive%3Awrite&response_type=code&redirect_uri=http://localhost"
        }
      }

      return retval
    else
      data = request_authorization(auth_url)
    end

    if data[:success] === true
      @token_store = data[:data]
    else
      return data
    end

    save_token_store
  elsif (Time.new.to_i - @token_store["last_authorized"]) > 60
    data = renew_authorization
    if data[:success] === false
      return data
    end
  end

  @access_token = @token_store["access_token"]

  if !@token_store.has_key?("metadataUrl") || !@token_store.has_key?("contentUrl")
    result = get_endpoint
    if result[:success] === true
       = result[:data]["metadataUrl"]
      @content_url = result[:data]["contentUrl"]
      @token_store["contentUrl"] = @content_url
      @token_store["metadataUrl"] = 

      save_token_store
    end
  end

   = @token_store["metadataUrl"]
  @content_url = @token_store["contentUrl"]

  retval
end

#clear_cacheObject



98
99
100
101
102
# File 'lib/clouddrive/account.rb', line 98

def clear_cache
  @token_store["nodes"] = {}
  @token_store["checkpoint"] = nil
  save_token_store
end

#delete_node_by_id(id) ⇒ Object



276
277
278
279
280
281
282
# File 'lib/clouddrive/account.rb', line 276

def delete_node_by_id(id)
  begin
    @db.execute("DELETE FROM nodes WHERE id = ?", id)
  rescue SQLite3::Exception => e
    puts "Exception deleting node with ID #{id}: #{e}"
  end
end

#get_endpointObject



104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/clouddrive/account.rb', line 104

def get_endpoint
  retval = {
      :success => false,
      :data => {}
  }
  RestClient.get("https://cdws.us-east-1.amazonaws.com/drive/v1/account/endpoint", {:Authorization => "Bearer #{@access_token}"}) do |response, request, result|
    retval[:data] = JSON.parse(response.body)
    if response.code === 200
      retval[:success] = true
    end
  end

  retval
end

#get_quotaObject



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/clouddrive/account.rb', line 119

def get_quota
  retval = {
      :success => false,
      :data => {}
  }

  RestClient.get("#{@metadata_url}account/quota", {:Authorization => "Bearer #{@access_token}"}) do |response, request, result|
    retval[:data] = JSON.parse(response.body)
    if response.code === 200
      retval[:success] = true
    end
  end

  retval
end

#get_usageObject



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

def get_usage
  retval = {
      :success => false,
      :data => {}
  }

  RestClient.get("#{@metadata_url}account/usage", {:Authorization => "Bearer #{@access_token}"}) do |response, request, result|
    retval[:data] = JSON.parse(response.body)
    if response.code === 200
      retval[:success] = true
    end
  end

  retval
end

#nodesObject



151
152
153
# File 'lib/clouddrive/account.rb', line 151

def nodes
  @token_store["nodes"]
end

#renew_authorizationObject



192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/clouddrive/account.rb', line 192

def renew_authorization
  retval = {
      :success => false,
      :data => {}
  }

  body = {
      'grant_type' => "refresh_token",
      'refresh_token' => @token_store["refresh_token"],
      'client_id' => @client_id,
      'client_secret' => @client_secret,
      'redirect_uri' => "http://localhost"
  }
  RestClient.post("https://api.amazon.com/auth/o2/token", body, :content_type => 'application/x-www-form-urlencoded') do |response, request, result|
    retval[:data] = JSON.parse(response.body)
    if response.code === 200
      retval[:success] = true

      @token_store["last_authorized"] = Time.new.to_i
      @token_store["refresh_token"] = retval[:data]["refresh_token"]
      @token_store["access_token"] = retval[:data]["access_token"]

      @access_token = @token_store["access_token"]
      @refresh_token = @token_store["refresh_token"]

      save_token_store
    end
  end

  retval
end

#request_authorization(auth_url) ⇒ Object



155
156
157
158
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
187
188
189
190
# File 'lib/clouddrive/account.rb', line 155

def request_authorization(auth_url)
  retval = {
      :success => false,
      :data => {}
  }

  params = CGI.parse(URI.parse(auth_url).query)
  if !params.has_key?('code')
    retval[:data]["message"] = "No authorization code exists in the callback URL: #{params}"

    return retval
  end

  code = params["code"]

  # Get token
  #
  # @TODO: why do I need to do this with code? (i.e., code[0])
  body = {
      'grant_type' => "authorization_code",
      'code' => code[0],
      'client_id' => @client_id,
      'client_secret' => @client_secret,
      'redirect_uri' => "http://localhost"
  }

  RestClient.post("https://api.amazon.com/auth/o2/token", body, :content_type => 'application/x-www-form-urlencoded') do |response, request, result|
    retval[:data] = JSON.parse(response.body)
    if response.code === 200
      retval[:success] = true
      retval[:data]["last_authorized"] = Time.new.to_i
    end
  end

  retval
end

#save_node(node) ⇒ Object



284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
# File 'lib/clouddrive/account.rb', line 284

def save_node(node)
  md5 = nil
  if node["contentProperties"] != nil && node["contentProperties"]["md5"] != nil
    md5 = node["contentProperties"]["md5"]
  end

  if node["name"] == nil && node["isRoot"] != nil && node["isRoot"] == true
    node["name"] = "root"
  end

  begin
    result = db.execute("INSERT OR REPLACE INTO nodes (id, name, kind, md5, created, modified, raw_data)
      VALUES (?, ?, ?, ?, ?, ?, ?);", [node["id"], node["name"], node["kind"], md5, node["createdDate"], node["modifiedDate"], node.to_json])
  rescue SQLite3::Exception => e
    if node["name"] == nil
      puts "Exception saving node: #{e}"
      puts node.to_json
    end
  end
end

#save_token_storeObject



224
225
226
227
228
# File 'lib/clouddrive/account.rb', line 224

def save_token_store
  File.open(@cache_file, 'w') do |file|
    file.write(@token_store.to_json)
  end
end

#syncObject



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# File 'lib/clouddrive/account.rb', line 230

def sync
  if !@token_store.has_key?("checkpoint")
    @token_store["checkpoint"] = nil
  end

  body = {
      :includePurged => "true"
  }

  loop do
    if @token_store["checkpoint"] != nil
      body[:checkpoint] = @token_store["checkpoint"]
    end

    loop = true
    RestClient.post( + "changes", body.to_json, :Authorization => "Bearer #{@access_token}") do |response, request, result|
      if response.code === 200
        data = response.body.split("\n")
        data.each do |xary|
          xary = JSON.parse(xary)
          if xary.has_key?("reset") && xary["reset"] == true
            @db.execute("DELETE FROM nodes WHERE 1=1")
          end

          if xary.has_key?("end") && xary["end"] == true
            loop = false
          elsif xary.has_key?("nodes")
            @token_store["checkpoint"] = xary["checkpoint"]
            xary["nodes"].each do |node|
              if node["status"] == "PURGED"
                delete_node_by_id(node["id"])
              else
                save_node(node)
              end
            end
          end
        end
      end
    end

    break if loop === false
  end

  save_token_store
end