summaryrefslogtreecommitdiffstats
path: root/chrome/browser/chromeos/gdata/gdata.cc
blob: 9b7d666cd4517c36bebd7c723c0071bd106ebd88 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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
97
98
99
100
101
102
103
104
105
106
107
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
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
191
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
223
224
225
226
227
228
229
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
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
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/gdata/gdata.h"

#include <string>

#include "base/bind.h"
#include "base/message_loop_proxy.h"
#include "chrome/browser/chromeos/gdata/gdata_operations.h"
#include "chrome/browser/net/browser_url_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/token_service.h"
#include "chrome/browser/signin/token_service_factory.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/net/gaia/gaia_constants.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/notification_types.h"

using content::BrowserThread;

namespace gdata {

namespace {

const char* GetExportFormatParam(DocumentExportFormat format) {
  switch (format) {
    case PNG:
      return "png";
    case HTML:
      return "html";
    case TXT:
      return "txt";
    case DOC:
      return "doc";
    case ODT:
      return "odt";
    case RTF:
      return "rtf";
    case ZIP:
      return "zip";
    case JPEG:
      return "jpeg";
    case SVG:
      return "svg";
    case PPT:
      return "ppt";
    case XLS:
      return "xls";
    case CSV:
      return "csv";
    case ODS:
      return "ods";
    case TSV:
      return "tsv";
    default:
      return "pdf";
  }
}

}  // namespace

//================================ GDataAuthService ============================

void GDataAuthService::Initialize(Profile* profile) {
  profile_ = profile;
  // Get OAuth2 refresh token (if we have any) and register for its updates.
  TokenService* service = TokenServiceFactory::GetForProfile(profile_);
  refresh_token_ = service->GetOAuth2LoginRefreshToken();
  registrar_.Add(this,
                 chrome::NOTIFICATION_TOKEN_AVAILABLE,
                 content::Source<TokenService>(service));
  registrar_.Add(this,
                 chrome::NOTIFICATION_TOKEN_REQUEST_FAILED,
                 content::Source<TokenService>(service));

  if (!refresh_token_.empty())
    FOR_EACH_OBSERVER(Observer, observers_, OnOAuth2RefreshTokenChanged());
}

GDataAuthService::GDataAuthService()
    : profile_(NULL),
      weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)),
      weak_ptr_bound_to_ui_thread_(weak_ptr_factory_.GetWeakPtr()) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}

GDataAuthService::~GDataAuthService() {
}

void GDataAuthService::StartAuthentication(
    GDataOperationRegistry* registry,
    const AuthStatusCallback& callback) {
  scoped_refptr<base::MessageLoopProxy> relay_proxy(
      base::MessageLoopProxy::current());

  if (IsFullyAuthenticated()) {
    relay_proxy->PostTask(FROM_HERE,
         base::Bind(callback, gdata::HTTP_SUCCESS, oauth2_auth_token()));
  } else if (IsPartiallyAuthenticated()) {
    BrowserThread::PostTask(
        BrowserThread::UI,
        FROM_HERE,
        base::Bind(&GDataAuthService::StartAuthenticationOnUIThread,
                   weak_ptr_bound_to_ui_thread_,
                   registry,
                   relay_proxy,
                   base::Bind(&GDataAuthService::OnAuthCompleted,
                              weak_ptr_bound_to_ui_thread_,
                              relay_proxy,
                              callback)));
  } else {
    relay_proxy->PostTask(FROM_HERE,
        base::Bind(callback, gdata::HTTP_UNAUTHORIZED, std::string()));
  }
}

void GDataAuthService::StartAuthenticationOnUIThread(
    GDataOperationRegistry* registry,
    scoped_refptr<base::MessageLoopProxy> relay_proxy,
    const AuthStatusCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  // We have refresh token, let's gets authenticated.
  (new AuthOperation(registry, profile_,
                     callback, GetOAuth2RefreshToken()))->Start();
}

void GDataAuthService::OnAuthCompleted(
    scoped_refptr<base::MessageLoopProxy> relay_proxy,
    const AuthStatusCallback& callback,
    GDataErrorCode error,
    const std::string& auth_token) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (error == HTTP_SUCCESS)
    auth_token_ = auth_token;

  // TODO(zelidrag): Add retry, back-off logic when things go wrong here.
  if (!callback.is_null())
    relay_proxy->PostTask(FROM_HERE, base::Bind(callback, error, auth_token));
}

void GDataAuthService::AddObserver(Observer* observer) {
  observers_.AddObserver(observer);
}

void GDataAuthService::RemoveObserver(Observer* observer) {
  observers_.RemoveObserver(observer);
}

void GDataAuthService::Observe(int type,
                               const content::NotificationSource& source,
                               const content::NotificationDetails& details) {
  DCHECK(type == chrome::NOTIFICATION_TOKEN_AVAILABLE ||
         type == chrome::NOTIFICATION_TOKEN_REQUEST_FAILED);

  TokenService::TokenAvailableDetails* token_details =
      content::Details<TokenService::TokenAvailableDetails>(details).ptr();
  if (token_details->service() != GaiaConstants::kGaiaOAuth2LoginRefreshToken)
    return;

  auth_token_.clear();
  if (type == chrome::NOTIFICATION_TOKEN_AVAILABLE) {
    TokenService* service = TokenServiceFactory::GetForProfile(profile_);
    refresh_token_ = service->GetOAuth2LoginRefreshToken();
  } else {
    refresh_token_.clear();
  }
  FOR_EACH_OBSERVER(Observer, observers_, OnOAuth2RefreshTokenChanged());
}

//=============================== DocumentsService =============================

DocumentsService::DocumentsService()
    : profile_(NULL),
      gdata_auth_service_(new GDataAuthService()),
      operation_registry_(new GDataOperationRegistry),
      weak_ptr_factory_(this),
      // The weak pointers is used to post tasks to UI thread.
      weak_ptr_bound_to_ui_thread_(weak_ptr_factory_.GetWeakPtr()) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}

DocumentsService::~DocumentsService() {
  gdata_auth_service_->RemoveObserver(this);
}

void DocumentsService::Initialize(Profile* profile) {
  profile_ = profile;
  // AddObserver() should be called before Initialize() as it could change
  // the refresh token.
  gdata_auth_service_->AddObserver(this);
  gdata_auth_service_->Initialize(profile);
}

void DocumentsService::CancelAll() {
  operation_registry_->CancelAll();
}

void DocumentsService::Authenticate(const AuthStatusCallback& callback) {
  gdata_auth_service_->StartAuthentication(operation_registry_.get(),
                                           callback);
}

void DocumentsService::GetDocuments(const GURL& url,
                                    const GetDataCallback& callback) {
  GetDocumentsOperation* operation =
      new GetDocumentsOperation(operation_registry_.get(), profile_, callback);
  if (!url.is_empty())
    operation->SetUrl(url);
  StartOperationOnUIThread(operation);
}

void DocumentsService::GetAccountMetadata(const GetDataCallback& callback) {
  GetAccountMetadataOperation* operation =
      new GetAccountMetadataOperation(operation_registry_.get(),
                                      profile_,
                                      callback);
  StartOperationOnUIThread(operation);
}

void DocumentsService::DownloadDocument(
    const FilePath& virtual_path,
    const GURL& document_url,
    DocumentExportFormat format,
    const DownloadActionCallback& callback) {
  DownloadFile(
      virtual_path,
      chrome_browser_net::AppendQueryParameter(document_url,
                                               "exportFormat",
                                               GetExportFormatParam(format)),
      callback);
}

void DocumentsService::DownloadFile(const FilePath& virtual_path,
                                    const GURL& document_url,
                                    const DownloadActionCallback& callback) {
  StartOperationOnUIThread(
      new DownloadFileOperation(operation_registry_.get(), profile_, callback,
                                document_url));
}

void DocumentsService::DeleteDocument(const GURL& document_url,
                                      const EntryActionCallback& callback) {
  StartOperationOnUIThread(
      new DeleteDocumentOperation(operation_registry_.get(), profile_, callback,
                                  document_url));
}

void DocumentsService::CreateDirectory(
    const GURL& parent_content_url,
    const FilePath::StringType& directory_name,
    const GetDataCallback& callback) {
  StartOperationOnUIThread(
      new CreateDirectoryOperation(operation_registry_.get(), profile_,
                                   callback, parent_content_url,
                                   directory_name));
}

void DocumentsService::CopyDocument(const GURL& document_url,
                                    const FilePath::StringType& new_name,
                                    const GetDataCallback& callback) {
  StartOperationOnUIThread(
      new CopyDocumentOperation(operation_registry_.get(), profile_, callback,
                                document_url, new_name));
}

void DocumentsService::RenameResource(const GURL& resource_url,
                                      const FilePath::StringType& new_name,
                                      const EntryActionCallback& callback) {
  StartOperationOnUIThread(
      new RenameResourceOperation(operation_registry_.get(), profile_, callback,
                                  resource_url, new_name));
}

void DocumentsService::AddResourceToDirectory(
    const GURL& parent_content_url,
    const GURL& resource_url,
    const EntryActionCallback& callback) {
  StartOperationOnUIThread(
      new AddResourceToDirectoryOperation(operation_registry_.get(),
                                          profile_,
                                          callback,
                                          parent_content_url,
                                          resource_url));
}

void DocumentsService::RemoveResourceFromDirectory(
    const GURL& parent_content_url,
    const GURL& resource_url,
    const std::string& resource_id,
    const EntryActionCallback& callback) {
  StartOperationOnUIThread(
      new RemoveResourceFromDirectoryOperation(operation_registry_.get(),
                                               profile_,
                                               callback,
                                               parent_content_url,
                                               resource_url,
                                               resource_id));
}

void DocumentsService::InitiateUpload(const InitiateUploadParams& params,
                                      const InitiateUploadCallback& callback) {
  if (params.resumable_create_media_link.is_empty()) {
    if (!callback.is_null()) {
      callback.Run(HTTP_BAD_REQUEST, GURL());
    }
    return;
  }

  StartOperationOnUIThread(
      new InitiateUploadOperation(operation_registry_.get(), profile_, callback,
                                  params));
}

void DocumentsService::ResumeUpload(const ResumeUploadParams& params,
                                    const ResumeUploadCallback& callback) {
  StartOperationOnUIThread(
      new ResumeUploadOperation(operation_registry_.get(), profile_, callback,
                                params));
}

void DocumentsService::OnOAuth2RefreshTokenChanged() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}

void DocumentsService::StartOperationOnUIThread(
    GDataOperationInterface* operation) {
  operation->SetReAuthenticateCallback(
      base::Bind(&DocumentsService::RetryOperation,
                 weak_ptr_factory_.GetWeakPtr()));
  BrowserThread::PostTask(
      BrowserThread::UI,
      FROM_HERE,
      base::Bind(&DocumentsService::StartOperation,
                 weak_ptr_bound_to_ui_thread_,
                 operation));  // |operation| is self-contained
}

void DocumentsService::StartOperation(GDataOperationInterface* operation) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (!gdata_auth_service_->IsFullyAuthenticated()) {
    // Fetch OAuth2 authentication token from the refresh token first.
    gdata_auth_service_->StartAuthentication(
        operation_registry_.get(),
        base::Bind(&DocumentsService::OnOperationAuthRefresh,
                   weak_ptr_factory_.GetWeakPtr(),
                   operation));
    return;
  }

  operation->Start(gdata_auth_service_->oauth2_auth_token());
}

void DocumentsService::OnOperationAuthRefresh(
    GDataOperationInterface* operation,
    GDataErrorCode code,
    const std::string& auth_token) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (code == HTTP_SUCCESS) {
    DCHECK(gdata_auth_service_->IsPartiallyAuthenticated());
    StartOperation(operation);
  } else {
    operation->OnAuthFailed(code);
  }
}

void DocumentsService::RetryOperation(GDataOperationInterface* operation) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  gdata_auth_service_->ClearOAuth2Token();
  // User authentication might have expired - rerun the request to force
  // auth token refresh.
  StartOperation(operation);
}

}  // namespace gdata