summaryrefslogtreecommitdiffstats
path: root/chrome/browser/sync_file_system/drive_file_sync_client.cc
blob: b6c8095be7db9cb0cd56bb55ae54f4230573c174 (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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
// 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/sync_file_system/drive_file_sync_client.h"

#include <algorithm>
#include <functional>
#include <sstream>
#include <string>

#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/google_apis/drive_api_parser.h"
#include "chrome/browser/google_apis/drive_uploader.h"
#include "chrome/browser/google_apis/gdata_wapi_service.h"
#include "chrome/browser/google_apis/gdata_wapi_url_generator.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sync_file_system/drive_file_sync_util.h"
#include "chrome/common/extensions/extension.h"
#include "extensions/common/constants.h"
#include "net/base/escape.h"
#include "net/base/mime_util.h"

namespace sync_file_system {

namespace {

enum ParentType {
  PARENT_TYPE_ROOT_OR_EMPTY,
  PARENT_TYPE_DIRECTORY,
};

const char kSyncRootDirectoryName[] = "Chrome Syncable FileSystem";
const char kMimeTypeOctetStream[] = "application/octet-stream";

// This path is not actually used but is required by DriveUploaderInterface.
const base::FilePath::CharType kDummyDrivePath[] =
    FILE_PATH_LITERAL("/dummy/drive/path");

void EmptyGDataErrorCodeCallback(google_apis::GDataErrorCode error) {}

bool HasParentLinkTo(const ScopedVector<google_apis::Link>& links,
                     GURL parent_link,
                     ParentType parent_type) {
  bool has_parent = false;

  for (ScopedVector<google_apis::Link>::const_iterator itr = links.begin();
       itr != links.end(); ++itr) {
    if ((*itr)->type() == google_apis::Link::LINK_PARENT) {
      has_parent = true;
      if ((*itr)->href().GetOrigin() == parent_link.GetOrigin() &&
          (*itr)->href().path() == parent_link.path())
        return true;
    }
  }

  return parent_type == PARENT_TYPE_ROOT_OR_EMPTY && !has_parent;
}

struct TitleAndParentQuery
    : std::unary_function<const google_apis::ResourceEntry*, bool> {
  TitleAndParentQuery(const std::string& title,
                      const GURL& parent_link,
                      ParentType parent_type)
      : title(title),
        parent_link(parent_link),
        parent_type(parent_type) {
  }

  bool operator()(const google_apis::ResourceEntry* entry) const {
    return entry->title() == title &&
        HasParentLinkTo(entry->links(), parent_link, parent_type);
  }

  const std::string& title;
  const GURL& parent_link;
  ParentType parent_type;
};

void FilterEntriesByTitleAndParent(
    ScopedVector<google_apis::ResourceEntry>* entries,
    const std::string& title,
    const GURL& parent_link,
    ParentType parent_type) {
  typedef ScopedVector<google_apis::ResourceEntry>::iterator iterator;
  iterator itr = std::partition(entries->begin(), entries->end(),
                                TitleAndParentQuery(title, parent_link,
                                                    parent_type));
  entries->erase(itr, entries->end());
}

google_apis::ResourceEntry* GetDocumentByTitleAndParent(
    const ScopedVector<google_apis::ResourceEntry>& entries,
    const std::string& title,
    const GURL& parent_link,
    ParentType parent_type) {
  typedef ScopedVector<google_apis::ResourceEntry>::const_iterator iterator;
  iterator found = std::find_if(entries.begin(), entries.end(),
                                TitleAndParentQuery(title, parent_link,
                                                    parent_type));
  if (found != entries.end())
    return *found;
  return NULL;
}

void EntryAdapter(scoped_ptr<google_apis::ResourceEntry> entry,
                  const DriveFileSyncClient::ResourceEntryCallback& callback,
                  google_apis::GDataErrorCode error) {
  callback.Run(error, entry.Pass());
}

void UploadResultAdapter(
    const DriveFileSyncClient::ResourceEntryCallback& callback,
    google_apis::DriveUploadError error,
    const base::FilePath& drive_path,
    const base::FilePath& file_path,
    scoped_ptr<google_apis::ResourceEntry> entry) {
  callback.Run(DriveUploadErrorToGDataErrorCode(error), entry.Pass());
}

}  // namespace

DriveFileSyncClient::DriveFileSyncClient(Profile* profile)
    : url_generator_(GURL(
          google_apis::GDataWapiUrlGenerator::kBaseUrlForProduction)),
      upload_next_key_(0) {
  drive_service_.reset(new google_apis::GDataWapiService(
      profile->GetRequestContext(),
      GURL(google_apis::GDataWapiUrlGenerator::kBaseUrlForProduction),
      "" /* custom_user_agent */));
  drive_service_->Initialize(profile);
  drive_service_->AddObserver(this);
  net::NetworkChangeNotifier::AddConnectionTypeObserver(this);

  drive_uploader_.reset(new google_apis::DriveUploader(drive_service_.get()));
}

scoped_ptr<DriveFileSyncClient> DriveFileSyncClient::CreateForTesting(
    Profile* profile,
    const GURL& base_url,
    scoped_ptr<google_apis::DriveServiceInterface> drive_service,
    scoped_ptr<google_apis::DriveUploaderInterface> drive_uploader) {
  return make_scoped_ptr(new DriveFileSyncClient(
      profile, base_url, drive_service.Pass(), drive_uploader.Pass()));
}

DriveFileSyncClient::DriveFileSyncClient(
    Profile* profile,
    const GURL& base_url,
    scoped_ptr<google_apis::DriveServiceInterface> drive_service,
    scoped_ptr<google_apis::DriveUploaderInterface> drive_uploader)
    : url_generator_(base_url),
      upload_next_key_(0) {
  drive_service_ = drive_service.Pass();
  drive_service_->Initialize(profile);
  drive_service_->AddObserver(this);
  net::NetworkChangeNotifier::AddConnectionTypeObserver(this);

  drive_uploader_ = drive_uploader.Pass();
}

DriveFileSyncClient::~DriveFileSyncClient() {
  DCHECK(CalledOnValidThread());
  net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
  drive_service_->RemoveObserver(this);
  drive_service_->CancelAll();
}

void DriveFileSyncClient::AddObserver(DriveFileSyncClientObserver* observer) {
  DCHECK(CalledOnValidThread());
  observers_.AddObserver(observer);
}

void DriveFileSyncClient::RemoveObserver(
    DriveFileSyncClientObserver* observer) {
  DCHECK(CalledOnValidThread());
  observers_.RemoveObserver(observer);
}

void DriveFileSyncClient::GetDriveDirectoryForSyncRoot(
    const ResourceIdCallback& callback) {
  DCHECK(CalledOnValidThread());
  DVLOG(2) << "Getting Drive directory for SyncRoot";

  std::string directory_name(kSyncRootDirectoryName);
  SearchFilesInDirectory(
      std::string(),
      FormatTitleQuery(directory_name),
      base::Bind(&DriveFileSyncClient::DidGetDirectory, AsWeakPtr(),
                 std::string(), directory_name, callback));
}

void DriveFileSyncClient::GetDriveDirectoryForOrigin(
    const std::string& sync_root_resource_id,
    const GURL& origin,
    const ResourceIdCallback& callback) {
  DCHECK(CalledOnValidThread());
  DVLOG(2) << "Getting Drive directory for Origin: " << origin;

  std::string directory_name(OriginToDirectoryTitle(origin));
  SearchFilesInDirectory(
      sync_root_resource_id,
      FormatTitleQuery(directory_name),
      base::Bind(&DriveFileSyncClient::DidGetDirectory, AsWeakPtr(),
                 sync_root_resource_id, directory_name, callback));
}

void DriveFileSyncClient::DidGetDirectory(
    const std::string& parent_resource_id,
    const std::string& directory_name,
    const ResourceIdCallback& callback,
    google_apis::GDataErrorCode error,
    scoped_ptr<google_apis::ResourceList> feed) {
  DCHECK(CalledOnValidThread());
  DCHECK(IsStringASCII(directory_name));

  if (error != google_apis::HTTP_SUCCESS) {
    DVLOG(2) << "Error on getting Drive directory: " << error;
    callback.Run(error, std::string());
    return;
  }

  GURL parent_link;
  ParentType parent_type = PARENT_TYPE_DIRECTORY;
  if (parent_resource_id.empty()) {
    parent_link = ResourceIdToResourceLink(
        drive_service_->GetRootResourceId());
    parent_type = PARENT_TYPE_ROOT_OR_EMPTY;
  } else {
    parent_link = ResourceIdToResourceLink(parent_resource_id);
  }
  std::string title(directory_name);
  google_apis::ResourceEntry* entry = GetDocumentByTitleAndParent(
      feed->entries(), title, parent_link, parent_type);
  if (!entry) {
    DVLOG(2) << "Directory not found. Creating: " << directory_name;

    // If the |parent_resource_id| is empty, create a directory under the root
    // directory. So here we use the result of GetRootResourceId() for such a
    // case.
    std::string resource_id = parent_type == PARENT_TYPE_ROOT_OR_EMPTY ?
        drive_service_->GetRootResourceId() : parent_resource_id;
    drive_service_->AddNewDirectory(
        resource_id, directory_name,
        base::Bind(&DriveFileSyncClient::DidCreateDirectory, AsWeakPtr(),
                   parent_resource_id, title, callback));
    return;
  }
  DVLOG(2) << "Found Drive directory.";

  // TODO(tzik): Handle error.
  DCHECK_EQ(google_apis::ENTRY_KIND_FOLDER, entry->kind());
  DCHECK_EQ(directory_name, entry->title());

  if (entry->title() == kSyncRootDirectoryName)
    EnsureSyncRootIsNotInMyDrive(entry->resource_id());

  callback.Run(error, entry->resource_id());
}

void DriveFileSyncClient::DidCreateDirectory(
    const std::string& parent_resource_id,
    const std::string& title,
    const ResourceIdCallback& callback,
    google_apis::GDataErrorCode error,
    scoped_ptr<google_apis::ResourceEntry> entry) {
  DCHECK(CalledOnValidThread());

  if (error != google_apis::HTTP_SUCCESS &&
      error != google_apis::HTTP_CREATED) {
    DVLOG(2) << "Error on creating Drive directory: " << error;
    callback.Run(error, std::string());
    return;
  }
  DVLOG(2) << "Created Drive directory.";

  DCHECK(entry);
  // Check if any other client creates a directory with same title.
  EnsureTitleUniqueness(
      parent_resource_id, title,
      base::Bind(&DriveFileSyncClient::DidEnsureUniquenessForCreateDirectory,
                 AsWeakPtr(), callback));
}

void DriveFileSyncClient::DidEnsureUniquenessForCreateDirectory(
    const ResourceIdCallback& callback,
    google_apis::GDataErrorCode error,
    scoped_ptr<google_apis::ResourceEntry> entry) {
  DCHECK(CalledOnValidThread());
  // If error == HTTP_FOUND: the directory is successfully created without
  //   conflict.
  // If error == HTTP_SUCCESS: the directory is created with conflict, but
  //   the conflict was resolved.
  //

  if (error == google_apis::HTTP_FOUND)
    error = google_apis::HTTP_CREATED;

  if (error != google_apis::HTTP_SUCCESS &&
      error != google_apis::HTTP_CREATED) {
    callback.Run(error, std::string());
    return;
  }

  DCHECK(entry) << "No entry: " << error;

  if (entry->title() == kSyncRootDirectoryName)
    EnsureSyncRootIsNotInMyDrive(entry->resource_id());

  callback.Run(error, entry->resource_id());
}

void DriveFileSyncClient::GetLargestChangeStamp(
    const ChangeStampCallback& callback) {
  DCHECK(CalledOnValidThread());
  DVLOG(2) << "Getting largest change id";

  drive_service_->GetAboutResource(
      base::Bind(&DriveFileSyncClient::DidGetAboutResource,
                 AsWeakPtr(), callback));
}

void DriveFileSyncClient::GetResourceEntry(
    const std::string& resource_id,
    const ResourceEntryCallback& callback) {
  DCHECK(CalledOnValidThread());
  DVLOG(2) << "Getting ResourceEntry for: " << resource_id;

  drive_service_->GetResourceEntry(
      resource_id,
      base::Bind(&DriveFileSyncClient::DidGetResourceEntry,
                 AsWeakPtr(), callback));
}

void DriveFileSyncClient::DidGetAboutResource(
    const ChangeStampCallback& callback,
    google_apis::GDataErrorCode error,
    scoped_ptr<google_apis::AboutResource> about_resource) {
  DCHECK(CalledOnValidThread());

  int64 largest_change_id = 0;
  if (error == google_apis::HTTP_SUCCESS) {
    DCHECK(about_resource);
    largest_change_id = about_resource->largest_change_id();
    DVLOG(2) << "Got largest change id: " << largest_change_id;
  } else {
    DVLOG(2) << "Error on getting largest change id: " << error;
  }

  callback.Run(error, largest_change_id);
}

void DriveFileSyncClient::SearchFilesInDirectory(
    const std::string& directory_resource_id,
    const std::string& search_query,
    const ResourceListCallback& callback) {
  DCHECK(CalledOnValidThread());
  DVLOG(2) << "Searching resources in the directory [" << directory_resource_id
           << "] with query [" << search_query << "]";

  drive_service_->GetResourceList(
      GURL(),  // feed_url
      0,  // start_changestamp
      search_query,
      directory_resource_id,
      base::Bind(&DriveFileSyncClient::DidGetResourceList,
                 AsWeakPtr(), callback));
}

void DriveFileSyncClient::ListFiles(const std::string& directory_resource_id,
                                    const ResourceListCallback& callback) {
  DCHECK(CalledOnValidThread());
  DVLOG(2) << "Listing resources in the directory ["
           << directory_resource_id << "]";

  SearchFilesInDirectory(directory_resource_id,
                         std::string() /* search_query */,
                         callback);
}

void DriveFileSyncClient::ListChanges(int64 start_changestamp,
                                      const ResourceListCallback& callback) {
  DCHECK(CalledOnValidThread());
  DVLOG(2) << "Listing changes since: " << start_changestamp;

  drive_service_->GetResourceList(
      GURL(),  // feed_url
      start_changestamp,
      std::string(),  // search_query
      std::string(),  // directory_resource_id
      base::Bind(&DriveFileSyncClient::DidGetResourceList,
                 AsWeakPtr(), callback));
}

void DriveFileSyncClient::ContinueListing(
    const GURL& feed_url,
    const ResourceListCallback& callback) {
  DCHECK(CalledOnValidThread());
  DVLOG(2) << "Continue listing on feed: " << feed_url;

  drive_service_->GetResourceList(
      feed_url,
      0,  // start_changestamp
      std::string(),  // search_query
      std::string(),  // directory_resource_id
      base::Bind(&DriveFileSyncClient::DidGetResourceList,
                 AsWeakPtr(), callback));
}

void DriveFileSyncClient::DownloadFile(
    const std::string& resource_id,
    const std::string& local_file_md5,
    const base::FilePath& local_file_path,
    const DownloadFileCallback& callback) {
  DCHECK(CalledOnValidThread());
  DVLOG(2) << "Downloading file [" << resource_id << "]";

  drive_service_->GetResourceEntry(
      resource_id,
      base::Bind(&DriveFileSyncClient::DidGetResourceEntry,
                 AsWeakPtr(),
                 base::Bind(&DriveFileSyncClient::DownloadFileInternal,
                            AsWeakPtr(), local_file_md5, local_file_path,
                            callback)));
}

void DriveFileSyncClient::UploadNewFile(
    const std::string& directory_resource_id,
    const base::FilePath& local_file_path,
    const std::string& title,
    const UploadFileCallback& callback) {
  DCHECK(CalledOnValidThread());
  DVLOG(2) << "Uploading new file into the directory ["
           << directory_resource_id << "] with title ["
           << title << "]";

  std::string mime_type;
  if (!net::GetWellKnownMimeTypeFromExtension(
          local_file_path.Extension(), &mime_type))
    mime_type = kMimeTypeOctetStream;

  UploadKey upload_key = RegisterUploadCallback(callback);
  ResourceEntryCallback did_upload_callback =
      base::Bind(&DriveFileSyncClient::DidUploadNewFile, AsWeakPtr(),
                 directory_resource_id, title, upload_key);
  drive_uploader_->UploadNewFile(
      directory_resource_id,
      base::FilePath(kDummyDrivePath),
      local_file_path,
      title,
      mime_type,
      base::Bind(&UploadResultAdapter, did_upload_callback));
}

void DriveFileSyncClient::UploadExistingFile(
    const std::string& resource_id,
    const std::string& remote_file_md5,
    const base::FilePath& local_file_path,
    const UploadFileCallback& callback) {
  DCHECK(CalledOnValidThread());
  DVLOG(2) << "Uploading existing file [" << resource_id << "]";
  drive_service_->GetResourceEntry(
      resource_id,
      base::Bind(&DriveFileSyncClient::DidGetResourceEntry,
                 AsWeakPtr(),
                 base::Bind(&DriveFileSyncClient::UploadExistingFileInternal,
                            AsWeakPtr(), remote_file_md5, local_file_path,
                            callback)));
}

void DriveFileSyncClient::DeleteFile(
    const std::string& resource_id,
    const std::string& remote_file_md5,
    const GDataErrorCallback& callback) {
  DCHECK(CalledOnValidThread());
  DVLOG(2) << "Deleting file: " << resource_id;

  // Load actual remote_file_md5 to check for conflict before deletion.
  if (!remote_file_md5.empty()) {
    drive_service_->GetResourceEntry(
        resource_id,
        base::Bind(&DriveFileSyncClient::DidGetResourceEntry,
                   AsWeakPtr(),
                   base::Bind(&DriveFileSyncClient::DeleteFileInternal,
                              AsWeakPtr(), remote_file_md5, callback)));
    return;
  }

  // Expected remote_file_md5 is empty so do a force delete.
  drive_service_->DeleteResource(
      resource_id,
      std::string(),
      base::Bind(&DriveFileSyncClient::DidDeleteFile,
                 AsWeakPtr(), callback));
  return;
}

GURL DriveFileSyncClient::ResourceIdToResourceLink(
    const std::string& resource_id) const {
  return url_generator_.GenerateEditUrl(resource_id);
}

void DriveFileSyncClient::EnsureSyncRootIsNotInMyDrive(
    const std::string& sync_root_resource_id) const {
  DCHECK(CalledOnValidThread());
  DVLOG(2) << "Ensuring the sync root directory is not in 'My Drive'.";

  drive_service_->RemoveResourceFromDirectory(
      drive_service_->GetRootResourceId(),
      sync_root_resource_id,
      base::Bind(&EmptyGDataErrorCodeCallback));
}

// static
std::string DriveFileSyncClient::OriginToDirectoryTitle(const GURL& origin) {
  DCHECK(origin.SchemeIs(extensions::kExtensionScheme));
  return origin.host();
}

// static
GURL DriveFileSyncClient::DirectoryTitleToOrigin(const std::string& title) {
  return extensions::Extension::GetBaseURLFromExtensionId(title);
}

void DriveFileSyncClient::OnReadyToPerformOperations() {
  DCHECK(CalledOnValidThread());
  FOR_EACH_OBSERVER(DriveFileSyncClientObserver, observers_, OnAuthenticated());
}

void DriveFileSyncClient::OnConnectionTypeChanged(
    net::NetworkChangeNotifier::ConnectionType type) {
  DCHECK(CalledOnValidThread());
  if (type != net::NetworkChangeNotifier::CONNECTION_NONE) {
    FOR_EACH_OBSERVER(DriveFileSyncClientObserver,
                      observers_, OnNetworkConnected());
    return;
  }
  // We're now disconnected, reset the drive_uploader_ to force stop
  // uploading, otherwise the uploader may get stuck.
  // TODO(kinuko): Check the uploader behavior if it's the expected behavior
  // (http://crbug.com/223818)
  CancelAllUploads(google_apis::GDATA_NO_CONNECTION);
}

void DriveFileSyncClient::DidGetResourceList(
    const ResourceListCallback& callback,
    google_apis::GDataErrorCode error,
    scoped_ptr<google_apis::ResourceList> resource_list) {
  DCHECK(CalledOnValidThread());

  if (error != google_apis::HTTP_SUCCESS) {
    DVLOG(2) << "Error on listing resource: " << error;
    callback.Run(error, scoped_ptr<google_apis::ResourceList>());
    return;
  }

  DVLOG(2) << "Got resource list";
  DCHECK(resource_list);
  callback.Run(error, resource_list.Pass());
}

void DriveFileSyncClient::DidGetResourceEntry(
    const ResourceEntryCallback& callback,
    google_apis::GDataErrorCode error,
    scoped_ptr<google_apis::ResourceEntry> entry) {
  DCHECK(CalledOnValidThread());

  if (error != google_apis::HTTP_SUCCESS) {
    DVLOG(2) << "Error on getting resource entry:" << error;
    callback.Run(error, scoped_ptr<google_apis::ResourceEntry>());
    return;
  }

  DVLOG(2) << "Got resource entry";
  DCHECK(entry);
  callback.Run(error, entry.Pass());
}

// static
std::string DriveFileSyncClient::FormatTitleQuery(const std::string& title) {
  // TODO(tzik): This pattern matches partial and case-insensitive,
  // and also matches files in subdirectories.
  // Refine the query after we migrate to Drive API.
  std::ostringstream out;
  out << "title:";

  // Escape single quote and back slash with '\\'.
  // https://developers.google.com/drive/search-parameters
  out << '\'';
  for (std::string::const_iterator itr = title.begin();
       itr != title.end(); ++itr) {
    switch (*itr) {
      case '\'':
      case '\\':
        out << '\\' << *itr;
        break;
      default:
        out << *itr;
        break;
    }
  }
  out << '\'';
  return out.str();
}

void DriveFileSyncClient::DownloadFileInternal(
    const std::string& local_file_md5,
    const base::FilePath& local_file_path,
    const DownloadFileCallback& callback,
    google_apis::GDataErrorCode error,
    scoped_ptr<google_apis::ResourceEntry> entry) {
  DCHECK(CalledOnValidThread());

  if (error != google_apis::HTTP_SUCCESS) {
    DVLOG(2) << "Error on getting resource entry for download";
    callback.Run(error, std::string());
    return;
  }
  DCHECK(entry);

  DVLOG(2) << "Got resource entry for download";
  // If local file and remote file are same, cancel the download.
  if (local_file_md5 == entry->file_md5()) {
    callback.Run(google_apis::HTTP_NOT_MODIFIED, local_file_md5);
    return;
  }

  DVLOG(2) << "Downloading file: " << entry->resource_id();
  drive_service_->DownloadFile(
      base::FilePath(kDummyDrivePath),
      local_file_path,
      entry->download_url(),
      base::Bind(&DriveFileSyncClient::DidDownloadFile,
                 AsWeakPtr(), entry->file_md5(), callback),
      google_apis::GetContentCallback());
}

void DriveFileSyncClient::DidDownloadFile(
    const std::string& downloaded_file_md5,
    const DownloadFileCallback& callback,
    google_apis::GDataErrorCode error,
    const base::FilePath& downloaded_file_path) {
  DCHECK(CalledOnValidThread());
  if (error == google_apis::HTTP_SUCCESS)
    DVLOG(2) << "Download completed";
  else
    DVLOG(2) << "Error on downloading file: " << error;

  callback.Run(error, downloaded_file_md5);
}

void DriveFileSyncClient::DidUploadNewFile(
    const std::string& parent_resource_id,
    const std::string& title,
    UploadKey upload_key,
    google_apis::GDataErrorCode error,
    scoped_ptr<google_apis::ResourceEntry> entry) {
  UploadFileCallback callback = GetAndUnregisterUploadCallback(upload_key);
  DCHECK(!callback.is_null());
  if (error != google_apis::HTTP_SUCCESS &&
      error != google_apis::HTTP_CREATED) {
    DVLOG(2) << "Error on uploading new file: " << error;
    callback.Run(error, std::string(), std::string());
    return;
  }

  DVLOG(2) << "Upload completed";
  EnsureTitleUniqueness(
      parent_resource_id, title,
      base::Bind(&DriveFileSyncClient::DidEnsureUniquenessForCreateFile,
                 AsWeakPtr(), entry->resource_id(), callback));
}

void DriveFileSyncClient::DidEnsureUniquenessForCreateFile(
    const std::string& expected_resource_id,
    const UploadFileCallback& callback,
    google_apis::GDataErrorCode error,
    scoped_ptr<google_apis::ResourceEntry> entry) {
  if (error == google_apis::HTTP_FOUND) {
    // The file was uploaded successfully and no conflict was detected.
    DCHECK(entry);
    DVLOG(2) << "No conflict detected on uploading new file";
    callback.Run(google_apis::HTTP_CREATED,
                 entry->resource_id(), entry->file_md5());
    return;
  }

  if (error == google_apis::HTTP_SUCCESS) {
    // The file was uploaded successfully but a conflict was detected.
    // The duplicated file was deleted successfully.
    DCHECK(entry);
    if (entry->resource_id() != expected_resource_id) {
      DVLOG(2) << "Conflict detected on uploading new file";
      callback.Run(google_apis::HTTP_CONFLICT,
                   std::string(), std::string());
      return;
    }

    DVLOG(2) << "Conflict detected on uploading new file and resolved";
    callback.Run(google_apis::HTTP_CREATED,
                 entry->resource_id(), entry->file_md5());
    return;
  }

  DVLOG(2) << "Error on uploading new file: " << error;
  callback.Run(error, std::string(), std::string());
}

void DriveFileSyncClient::UploadExistingFileInternal(
    const std::string& remote_file_md5,
    const base::FilePath& local_file_path,
    const UploadFileCallback& callback,
    google_apis::GDataErrorCode error,
    scoped_ptr<google_apis::ResourceEntry> entry) {
  DCHECK(CalledOnValidThread());

  if (error != google_apis::HTTP_SUCCESS) {
    DVLOG(2) << "Error on uploading existing file: " << error;
    callback.Run(error, std::string(), std::string());
    return;
  }
  DCHECK(entry);

  // If remote file's hash value is different from the expected one, conflict
  // might have occurred.
  if (!remote_file_md5.empty() && remote_file_md5 != entry->file_md5()) {
    DVLOG(2) << "Conflict detected before uploading existing file";
    callback.Run(google_apis::HTTP_CONFLICT, std::string(), std::string());
    return;
  }

  std::string mime_type;
  if (!net::GetWellKnownMimeTypeFromExtension(
          local_file_path.Extension(), &mime_type))
    mime_type = kMimeTypeOctetStream;

  UploadKey upload_key = RegisterUploadCallback(callback);
  ResourceEntryCallback did_upload_callback =
      base::Bind(&DriveFileSyncClient::DidUploadExistingFile,
                 AsWeakPtr(), upload_key);
  drive_uploader_->UploadExistingFile(
      entry->resource_id(),
      base::FilePath(kDummyDrivePath),
      local_file_path,
      mime_type,
      entry->etag(),
      base::Bind(&UploadResultAdapter, did_upload_callback));
}

bool DriveFileSyncClient::IsAuthenticated() const {
  return drive_service_->HasRefreshToken();
}

void DriveFileSyncClient::DidUploadExistingFile(
    UploadKey upload_key,
    google_apis::GDataErrorCode error,
    scoped_ptr<google_apis::ResourceEntry> entry) {
  DCHECK(CalledOnValidThread());
  UploadFileCallback callback = GetAndUnregisterUploadCallback(upload_key);
  DCHECK(!callback.is_null());
  if (error != google_apis::HTTP_SUCCESS) {
    DVLOG(2) << "Error on uploading existing file: " << error;
    callback.Run(error, std::string(), std::string());
    return;
  }

  DCHECK(entry);
  DVLOG(2) << "Upload completed";
  callback.Run(error, entry->resource_id(), entry->file_md5());
}

void DriveFileSyncClient::DeleteFileInternal(
    const std::string& remote_file_md5,
    const GDataErrorCallback& callback,
    google_apis::GDataErrorCode error,
    scoped_ptr<google_apis::ResourceEntry> entry) {
  DCHECK(CalledOnValidThread());

  if (error != google_apis::HTTP_SUCCESS) {
    DVLOG(2) << "Error on getting resource entry for deleting file: " << error;
    callback.Run(error);
    return;
  }
  DCHECK(entry);

  // If remote file's hash value is different from the expected one, conflict
  // might have occurred.
  if (!remote_file_md5.empty() && remote_file_md5 != entry->file_md5()) {
    DVLOG(2) << "Conflict detected before deleting file";
    callback.Run(google_apis::HTTP_CONFLICT);
    return;
  }
  DVLOG(2) << "Got resource entry for deleting file";

  // Move the file to trash (don't delete it completely).
  drive_service_->DeleteResource(
      entry->resource_id(),
      entry->etag(),
      base::Bind(&DriveFileSyncClient::DidDeleteFile,
                 AsWeakPtr(), callback));
}

void DriveFileSyncClient::DidDeleteFile(
    const GDataErrorCallback& callback,
    google_apis::GDataErrorCode error) {
  DCHECK(CalledOnValidThread());
  if (error == google_apis::HTTP_SUCCESS)
    DVLOG(2) << "Deletion completed";
  else
    DVLOG(2) << "Error on deleting file: " << error;

  callback.Run(error);
}

void DriveFileSyncClient::EnsureTitleUniqueness(
    const std::string& parent_resource_id,
    const std::string& expected_title,
    const ResourceEntryCallback& callback) {
  DCHECK(CalledOnValidThread());
  DVLOG(2) << "Checking if there's no conflict on entry creation";

  SearchFilesInDirectory(
      parent_resource_id,
      FormatTitleQuery(expected_title),
      base::Bind(&DriveFileSyncClient::DidListEntriesToEnsureUniqueness,
                 AsWeakPtr(), parent_resource_id, expected_title, callback));
}

void DriveFileSyncClient::DidListEntriesToEnsureUniqueness(
    const std::string& parent_resource_id,
    const std::string& expected_title,
    const ResourceEntryCallback& callback,
    google_apis::GDataErrorCode error,
    scoped_ptr<google_apis::ResourceList> feed) {
  DCHECK(CalledOnValidThread());
  if (error != google_apis::HTTP_SUCCESS) {
    DVLOG(2) << "Error on listing resource for ensuring title uniqueness";
    callback.Run(error, scoped_ptr<google_apis::ResourceEntry>());
    return;
  }
  DVLOG(2) << "Got resource list for ensuring title uniqueness";

  // This filtering is needed only on WAPI. Once we move to Drive API we can
  // drop this.
  GURL parent_link;
  ParentType parent_type = PARENT_TYPE_DIRECTORY;
  if (parent_resource_id.empty()) {
    parent_link = ResourceIdToResourceLink(
        drive_service_->GetRootResourceId());
    parent_type = PARENT_TYPE_ROOT_OR_EMPTY;
  } else {
    parent_link = ResourceIdToResourceLink(parent_resource_id);
  }
  ScopedVector<google_apis::ResourceEntry> entries;
  entries.swap(*feed->mutable_entries());
  FilterEntriesByTitleAndParent(&entries, expected_title, parent_link,
                                parent_type);

  if (entries.empty()) {
    DVLOG(2) << "Uploaded file is not found";
    callback.Run(google_apis::HTTP_NOT_FOUND,
                 scoped_ptr<google_apis::ResourceEntry>());
    return;
  }

  if (entries.size() >= 2) {
    DVLOG(2) << "Conflict detected on creating entry";
    for (size_t i = 0; i < entries.size() - 1; ++i) {
      // TODO(tzik): Replace published_time with creation time after we move to
      // Drive API.
      if (entries[i]->published_time() < entries.back()->published_time())
        std::swap(entries[i], entries.back());
    }

    scoped_ptr<google_apis::ResourceEntry> earliest_entry(entries.back());
    entries.back() = NULL;
    entries.get().pop_back();

    DeleteEntriesForEnsuringTitleUniqueness(
        entries.Pass(),
        base::Bind(&EntryAdapter, base::Passed(&earliest_entry), callback));
    return;
  }

  DVLOG(2) << "no conflict detected";
  DCHECK_EQ(1u, entries.size());
  scoped_ptr<google_apis::ResourceEntry> entry(entries.front());
  entries.weak_clear();
  callback.Run(google_apis::HTTP_FOUND, entry.Pass());
}

void DriveFileSyncClient::DeleteEntriesForEnsuringTitleUniqueness(
    ScopedVector<google_apis::ResourceEntry> entries,
    const GDataErrorCallback& callback) {
  DCHECK(CalledOnValidThread());
  DVLOG(2) << "Cleaning up conflict on entry creation";

  if (entries.empty()) {
    callback.Run(google_apis::HTTP_SUCCESS);
    return;
  }

  scoped_ptr<google_apis::ResourceEntry> entry(entries.back());
  entries.back() = NULL;
  entries.get().pop_back();

  // We don't care conflicts here as other clients may be also deleting this
  // file, so passing an empty etag.
  drive_service_->DeleteResource(
      entry->resource_id(),
      std::string(),  // empty etag
      base::Bind(
          &DriveFileSyncClient::DidDeleteEntriesForEnsuringTitleUniqueness,
          AsWeakPtr(), base::Passed(&entries), callback));
}

void DriveFileSyncClient::DidDeleteEntriesForEnsuringTitleUniqueness(
    ScopedVector<google_apis::ResourceEntry> entries,
    const GDataErrorCallback& callback,
    google_apis::GDataErrorCode error) {
  DCHECK(CalledOnValidThread());

  if (error != google_apis::HTTP_SUCCESS &&
      error != google_apis::HTTP_NOT_FOUND) {
    DVLOG(2) << "Error on deleting file: " << error;
    callback.Run(error);
    return;
  }

  DVLOG(2) << "Deletion completed";
  DeleteEntriesForEnsuringTitleUniqueness(entries.Pass(), callback);
}

DriveFileSyncClient::UploadKey DriveFileSyncClient::RegisterUploadCallback(
    const UploadFileCallback& callback) {
  const bool inserted = upload_callback_map_.insert(
      std::make_pair(upload_next_key_, callback)).second;
  CHECK(inserted);
  return upload_next_key_++;
}

DriveFileSyncClient::UploadFileCallback
DriveFileSyncClient::GetAndUnregisterUploadCallback(
    UploadKey key) {
  UploadFileCallback callback;
  UploadCallbackMap::iterator found = upload_callback_map_.find(key);
  if (found == upload_callback_map_.end())
    return callback;
  callback = found->second;
  upload_callback_map_.erase(found);
  return callback;
}

void DriveFileSyncClient::CancelAllUploads(google_apis::GDataErrorCode error) {
  if (upload_callback_map_.empty())
    return;
  for (UploadCallbackMap::iterator iter = upload_callback_map_.begin();
       iter != upload_callback_map_.end(); ++iter) {
    iter->second.Run(error, std::string(), std::string());
  }
  upload_callback_map_.clear();
  drive_uploader_.reset(new google_apis::DriveUploader(drive_service_.get()));
}

}  // namespace sync_file_system