summaryrefslogtreecommitdiffstats
path: root/chrome/browser/chromeos/drive/file_system.cc
blob: e5c150762e901798b1fa384fb03976f3a63a56eb (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
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
// 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/drive/file_system.h"

#include "base/bind.h"
#include "base/file_util.h"
#include "base/message_loop_proxy.h"
#include "base/metrics/histogram.h"
#include "base/platform_file.h"
#include "base/prefs/pref_change_registrar.h"
#include "base/prefs/pref_service.h"
#include "base/stringprintf.h"
#include "base/threading/sequenced_worker_pool.h"
#include "chrome/browser/chromeos/drive/change_list_loader.h"
#include "chrome/browser/chromeos/drive/change_list_processor.h"
#include "chrome/browser/chromeos/drive/drive.pb.h"
#include "chrome/browser/chromeos/drive/file_cache.h"
#include "chrome/browser/chromeos/drive/file_system_observer.h"
#include "chrome/browser/chromeos/drive/file_system_util.h"
#include "chrome/browser/chromeos/drive/job_scheduler.h"
#include "chrome/browser/chromeos/drive/resource_entry_conversion.h"
#include "chrome/browser/chromeos/drive/search_metadata.h"
#include "chrome/browser/google_apis/drive_api_parser.h"
#include "chrome/browser/google_apis/drive_api_util.h"
#include "chrome/browser/google_apis/drive_service_interface.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_details.h"

using content::BrowserThread;

namespace drive {
namespace {

const char kMimeTypeJson[] = "application/json";

//================================ Helper functions ============================

// Creates a temporary JSON file representing a document with |alternate_url|
// and |resource_id| under |document_dir| on blocking pool.
FileError CreateDocumentJsonFileOnBlockingPool(
    const base::FilePath& document_dir,
    const GURL& alternate_url,
    const std::string& resource_id,
    base::FilePath* temp_file_path) {
  DCHECK(temp_file_path);

  FileError error = FILE_ERROR_FAILED;

  if (file_util::CreateTemporaryFileInDir(document_dir, temp_file_path)) {
    std::string document_content = base::StringPrintf(
        "{\"url\": \"%s\", \"resource_id\": \"%s\"}",
        alternate_url.spec().c_str(), resource_id.c_str());
    int document_size = static_cast<int>(document_content.size());
    if (file_util::WriteFile(*temp_file_path, document_content.data(),
                             document_size) == document_size) {
      error = FILE_ERROR_OK;
    }
  }

  if (error != FILE_ERROR_OK)
    temp_file_path->clear();
  return error;
}

// Helper function for binding |path| to GetEntryInfoWithFilePathCallback and
// create GetEntryInfoCallback.
void RunGetEntryInfoWithFilePathCallback(
    const GetEntryInfoWithFilePathCallback& callback,
    const base::FilePath& path,
    FileError error,
    scoped_ptr<ResourceEntry> entry) {
  DCHECK(!callback.is_null());
  callback.Run(error, path, entry.Pass());
}

// Callback for ResourceMetadata::GetLargestChangestamp.
// |callback| must not be null.
void OnGetLargestChangestamp(
    FileSystemMetadata metadata,  // Will be modified.
    const GetFilesystemMetadataCallback& callback,
    int64 largest_changestamp) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  metadata.largest_changestamp = largest_changestamp;
  callback.Run(metadata);
}

// Thin adapter to map GetFileCallback to FileOperationCallback.
void GetFileCallbackToFileOperationCallbackAdapter(
    const FileOperationCallback& callback,
    FileError error,
    const base::FilePath& unused_file_path,
    scoped_ptr<ResourceEntry> unused_entry) {
  callback.Run(error);
}

// Wraps |callback| and always passes FILE_ERROR_OK when invoked.
// This is used for adopting |callback| to wait for a non-fatal operation.
void IgnoreError(const FileOperationCallback& callback, FileError error) {
  callback.Run(FILE_ERROR_OK);
}

// Creates a file with unique name in |dir| and stores the path to |temp_file|.
// Additionally, sets the permission of the file to allow read access from
// others and group member users (i.e, "-rw-r--r--").
// We need this wrapper because Drive cache files may be read from other
// processes (e.g., cros_disks for mounting zip files).
//
// Must be called on the blocking pool.
bool CreateTemporaryReadableFileInDir(const base::FilePath& dir,
                                      base::FilePath* temp_file) {
  if (!file_util::CreateTemporaryFileInDir(dir, temp_file))
    return false;
  return file_util::SetPosixFilePermissions(
      *temp_file,
      file_util::FILE_PERMISSION_READ_BY_USER |
      file_util::FILE_PERMISSION_WRITE_BY_USER |
      file_util::FILE_PERMISSION_READ_BY_GROUP |
      file_util::FILE_PERMISSION_READ_BY_OTHERS);
}

}  // namespace

// FileSystem::GetFileCompleteForOpenParams struct implementation.
struct FileSystem::GetFileCompleteForOpenParams {
  GetFileCompleteForOpenParams(const OpenFileCallback& callback,
                               const std::string& resource_id,
                               const std::string& md5);
  OpenFileCallback callback;
  std::string resource_id;
  std::string md5;
};

FileSystem::GetFileCompleteForOpenParams::GetFileCompleteForOpenParams(
    const OpenFileCallback& callback,
    const std::string& resource_id,
    const std::string& md5)
    : callback(callback),
      resource_id(resource_id),
      md5(md5) {
}

// FileSystem::GetResolvedFileParams struct implementation.
struct FileSystem::GetResolvedFileParams {
  GetResolvedFileParams(
      const base::FilePath& drive_file_path,
      const DriveClientContext& context,
      scoped_ptr<ResourceEntry> entry,
      const GetFileContentInitializedCallback& initialized_callback,
      const GetFileCallback& get_file_callback,
      const google_apis::GetContentCallback& get_content_callback)
      : drive_file_path(drive_file_path),
        context(context),
        entry(entry.Pass()),
        initialized_callback(initialized_callback),
        get_file_callback(get_file_callback),
        get_content_callback(get_content_callback) {
    DCHECK(!get_file_callback.is_null());
    DCHECK(this->entry);
  }

  void OnError(FileError error) {
    get_file_callback.Run(error, base::FilePath(), scoped_ptr<ResourceEntry>());
  }

  void OnCacheFileFound(const base::FilePath& local_file_path) {
    if (initialized_callback.is_null()) {
      return;
    }

    scoped_ptr<ResourceEntry> new_entry(new ResourceEntry(*entry));
    initialized_callback.Run(FILE_ERROR_OK,
                             new_entry.Pass(),
                             local_file_path,
                             base::Closure());
  }

  void OnStartDownloading(const base::Closure& cancel_download_closure) {
    if (initialized_callback.is_null()) {
      return;
    }

    scoped_ptr<ResourceEntry> new_entry(new ResourceEntry(*entry));
    initialized_callback.Run(FILE_ERROR_OK,
                             new_entry.Pass(),
                             base::FilePath(),
                             cancel_download_closure);
  }

  void OnComplete(const base::FilePath& local_file_path) {
    get_file_callback.Run(FILE_ERROR_OK, local_file_path,
                          scoped_ptr<ResourceEntry>(new ResourceEntry(*entry)));
  }

  const base::FilePath drive_file_path;
  const DriveClientContext context;
  scoped_ptr<ResourceEntry> entry;
  const GetFileContentInitializedCallback initialized_callback;
  const GetFileCallback get_file_callback;
  const google_apis::GetContentCallback get_content_callback;
};

// FileSystem::AddUploadedFileParams implementation.
struct FileSystem::AddUploadedFileParams {
  AddUploadedFileParams(const base::FilePath& file_content_path,
                        const FileOperationCallback& callback,
                        const std::string& resource_id,
                        const std::string& md5)
      : file_content_path(file_content_path),
        callback(callback),
        resource_id(resource_id),
        md5(md5) {
  }

  base::FilePath file_content_path;
  FileOperationCallback callback;
  std::string resource_id;
  std::string md5;
};


// FileSystem class implementation.

FileSystem::FileSystem(
    Profile* profile,
    internal::FileCache* cache,
    google_apis::DriveServiceInterface* drive_service,
    JobScheduler* scheduler,
    DriveWebAppsRegistry* webapps_registry,
    internal::ResourceMetadata* resource_metadata,
    base::SequencedTaskRunner* blocking_task_runner)
    : profile_(profile),
      cache_(cache),
      drive_service_(drive_service),
      scheduler_(scheduler),
      webapps_registry_(webapps_registry),
      resource_metadata_(resource_metadata),
      last_update_check_error_(FILE_ERROR_OK),
      hide_hosted_docs_(false),
      blocking_task_runner_(blocking_task_runner),
      weak_ptr_factory_(this) {
  // Should be created from the file browser extension API on UI thread.
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}

void FileSystem::Reload() {
  resource_metadata_->ResetOnUIThread(base::Bind(
      &FileSystem::ReloadAfterReset,
      weak_ptr_factory_.GetWeakPtr()));
}

void FileSystem::Initialize() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  SetupChangeListLoader();

  // Allocate the drive operation handlers.
  drive_operations_.Init(scheduler_,
                         this,  // FileSystemInterface
                         cache_,
                         resource_metadata_,
                         blocking_task_runner_,
                         this);  // OperationObserver

  PrefService* pref_service = profile_->GetPrefs();
  hide_hosted_docs_ = pref_service->GetBoolean(prefs::kDisableDriveHostedFiles);

  InitializePreferenceObserver();
}

void FileSystem::ReloadAfterReset(FileError error) {
  if (error != FILE_ERROR_OK) {
    LOG(ERROR) << "Failed to reset the resource metadata: "
               << FileErrorToString(error);
    return;
  }

  SetupChangeListLoader();

  change_list_loader_->LoadIfNeeded(
      DirectoryFetchInfo(),
      base::Bind(&FileSystem::OnUpdateChecked,
                 weak_ptr_factory_.GetWeakPtr()));
}

void FileSystem::SetupChangeListLoader() {
  change_list_loader_.reset(new ChangeListLoader(resource_metadata_,
                                                 scheduler_,
                                                 webapps_registry_));
  change_list_loader_->AddObserver(this);
}

void FileSystem::CheckForUpdates() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DVLOG(1) << "CheckForUpdates";

  if (change_list_loader_) {
    change_list_loader_->CheckForUpdates(
        base::Bind(&FileSystem::OnUpdateChecked,
                   weak_ptr_factory_.GetWeakPtr()));
  }
}

void FileSystem::OnUpdateChecked(FileError error) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DVLOG(1) << "CheckForUpdates finished: " << FileErrorToString(error);
  last_update_check_time_ = base::Time::Now();
  last_update_check_error_ = error;
}

FileSystem::~FileSystem() {
  // This should be called from UI thread, from DriveSystemService shutdown.
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  change_list_loader_->RemoveObserver(this);
}

void FileSystem::AddObserver(FileSystemObserver* observer) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  observers_.AddObserver(observer);
}

void FileSystem::RemoveObserver(FileSystemObserver* observer) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  observers_.RemoveObserver(observer);
}

void FileSystem::GetEntryInfoByResourceId(
    const std::string& resource_id,
    const GetEntryInfoWithFilePathCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!resource_id.empty());
  DCHECK(!callback.is_null());

  resource_metadata_->GetEntryInfoByResourceIdOnUIThread(
      resource_id,
      base::Bind(&FileSystem::GetEntryInfoByResourceIdAfterGetEntry,
                 weak_ptr_factory_.GetWeakPtr(),
                 callback));
}

void FileSystem::GetEntryInfoByResourceIdAfterGetEntry(
    const GetEntryInfoWithFilePathCallback& callback,
    FileError error,
    const base::FilePath& file_path,
    scoped_ptr<ResourceEntry> entry) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  if (error != FILE_ERROR_OK) {
    callback.Run(error, base::FilePath(), scoped_ptr<ResourceEntry>());
    return;
  }
  DCHECK(entry.get());

  CheckLocalModificationAndRun(
      entry.Pass(),
      base::Bind(&RunGetEntryInfoWithFilePathCallback,
                 callback,
                 file_path));
}

void FileSystem::TransferFileFromRemoteToLocal(
    const base::FilePath& remote_src_file_path,
    const base::FilePath& local_dest_file_path,
    const FileOperationCallback& callback) {

  drive_operations_.TransferFileFromRemoteToLocal(remote_src_file_path,
                                                  local_dest_file_path,
                                                  callback);
}

void FileSystem::TransferFileFromLocalToRemote(
    const base::FilePath& local_src_file_path,
    const base::FilePath& remote_dest_file_path,
    const FileOperationCallback& callback) {

  drive_operations_.TransferFileFromLocalToRemote(local_src_file_path,
                                                  remote_dest_file_path,
                                                  callback);
}

void FileSystem::Copy(const base::FilePath& src_file_path,
                      const base::FilePath& dest_file_path,
                      const FileOperationCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());
  drive_operations_.Copy(src_file_path, dest_file_path, callback);
}

void FileSystem::Move(const base::FilePath& src_file_path,
                      const base::FilePath& dest_file_path,
                      const FileOperationCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());
  drive_operations_.Move(src_file_path, dest_file_path, callback);
}

void FileSystem::Remove(const base::FilePath& file_path,
                        bool is_recursive,
                        const FileOperationCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());
  drive_operations_.Remove(file_path, is_recursive, callback);
}

void FileSystem::CreateDirectory(
    const base::FilePath& directory_path,
    bool is_exclusive,
    bool is_recursive,
    const FileOperationCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  change_list_loader_->LoadIfNeeded(
      DirectoryFetchInfo(),
      base::Bind(&FileSystem::CreateDirectoryAfterLoad,
                 weak_ptr_factory_.GetWeakPtr(),
                 directory_path, is_exclusive, is_recursive, callback));
}

void FileSystem::CreateDirectoryAfterLoad(
    const base::FilePath& directory_path,
    bool is_exclusive,
    bool is_recursive,
    const FileOperationCallback& callback,
    FileError load_error) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  if (load_error != FILE_ERROR_OK) {
    callback.Run(load_error);
    return;
  }

  drive_operations_.CreateDirectory(
      directory_path, is_exclusive, is_recursive, callback);
}

void FileSystem::CreateFile(const base::FilePath& file_path,
                            bool is_exclusive,
                            const FileOperationCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  drive_operations_.CreateFile(file_path, is_exclusive, callback);
}

void FileSystem::Pin(const base::FilePath& file_path,
                     const FileOperationCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  GetEntryInfoByPath(file_path,
                     base::Bind(&FileSystem::PinAfterGetEntryInfoByPath,
                                weak_ptr_factory_.GetWeakPtr(),
                                callback));
}

void FileSystem::PinAfterGetEntryInfoByPath(
    const FileOperationCallback& callback,
    FileError error,
    scoped_ptr<ResourceEntry> entry) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  // TODO(hashimoto): Support pinning directories. crbug.com/127831
  if (entry && entry->file_info().is_directory())
    error = FILE_ERROR_NOT_A_FILE;

  if (error != FILE_ERROR_OK) {
    callback.Run(error);
    return;
  }
  DCHECK(entry);

  cache_->PinOnUIThread(entry->resource_id(),
                        entry->file_specific_info().file_md5(), callback);
}

void FileSystem::Unpin(const base::FilePath& file_path,
                       const FileOperationCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  GetEntryInfoByPath(file_path,
                     base::Bind(&FileSystem::UnpinAfterGetEntryInfoByPath,
                                weak_ptr_factory_.GetWeakPtr(),
                                callback));
}

void FileSystem::UnpinAfterGetEntryInfoByPath(
    const FileOperationCallback& callback,
    FileError error,
    scoped_ptr<ResourceEntry> entry) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  // TODO(hashimoto): Support pinning directories. crbug.com/127831
  if (entry && entry->file_info().is_directory())
    error = FILE_ERROR_NOT_A_FILE;

  if (error != FILE_ERROR_OK) {
    callback.Run(error);
    return;
  }
  DCHECK(entry);

  cache_->UnpinOnUIThread(entry->resource_id(),
                          entry->file_specific_info().file_md5(), callback);
}

void FileSystem::GetFileByPath(const base::FilePath& file_path,
                               const GetFileCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  resource_metadata_->GetEntryInfoByPathOnUIThread(
      file_path,
      base::Bind(&FileSystem::OnGetEntryInfoCompleteForGetFileByPath,
                 weak_ptr_factory_.GetWeakPtr(),
                 file_path,
                 callback));
}

void FileSystem::OnGetEntryInfoCompleteForGetFileByPath(
    const base::FilePath& file_path,
    const GetFileCallback& callback,
    FileError error,
    scoped_ptr<ResourceEntry> entry) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  if (error != FILE_ERROR_OK) {
    callback.Run(error, base::FilePath(), scoped_ptr<ResourceEntry>());
    return;
  }
  DCHECK(entry);

  GetResolvedFileByPath(
      make_scoped_ptr(new GetResolvedFileParams(
          file_path,
          DriveClientContext(USER_INITIATED),
          entry.Pass(),
          GetFileContentInitializedCallback(),
          callback,
          google_apis::GetContentCallback())));
}

void FileSystem::GetFileByResourceId(
    const std::string& resource_id,
    const DriveClientContext& context,
    const GetFileCallback& get_file_callback,
    const google_apis::GetContentCallback& get_content_callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!resource_id.empty());
  DCHECK(!get_file_callback.is_null());

  resource_metadata_->GetEntryInfoByResourceIdOnUIThread(
      resource_id,
      base::Bind(&FileSystem::GetFileByResourceIdAfterGetEntry,
                 weak_ptr_factory_.GetWeakPtr(),
                 context,
                 get_file_callback,
                 get_content_callback));
}

void FileSystem::GetFileByResourceIdAfterGetEntry(
    const DriveClientContext& context,
    const GetFileCallback& get_file_callback,
    const google_apis::GetContentCallback& get_content_callback,
    FileError error,
    const base::FilePath& file_path,
    scoped_ptr<ResourceEntry> entry) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!get_file_callback.is_null());

  if (error != FILE_ERROR_OK) {
    get_file_callback.Run(FILE_ERROR_NOT_FOUND, base::FilePath(),
                          scoped_ptr<ResourceEntry>());
    return;
  }

  GetResolvedFileByPath(
      make_scoped_ptr(new GetResolvedFileParams(
          file_path,
          context,
          entry.Pass(),
          GetFileContentInitializedCallback(),
          get_file_callback,
          get_content_callback)));
}

void FileSystem::GetFileContentByPath(
    const base::FilePath& file_path,
    const GetFileContentInitializedCallback& initialized_callback,
    const google_apis::GetContentCallback& get_content_callback,
    const FileOperationCallback& completion_callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!initialized_callback.is_null());
  DCHECK(!get_content_callback.is_null());
  DCHECK(!completion_callback.is_null());

  resource_metadata_->GetEntryInfoByPathOnUIThread(
      file_path,
      base::Bind(&FileSystem::GetFileContentByPathAfterGetEntry,
                 weak_ptr_factory_.GetWeakPtr(),
                 file_path,
                 initialized_callback,
                 get_content_callback,
                 completion_callback));
}

void FileSystem::GetFileContentByPathAfterGetEntry(
    const base::FilePath& file_path,
    const GetFileContentInitializedCallback& initialized_callback,
    const google_apis::GetContentCallback& get_content_callback,
    const FileOperationCallback& completion_callback,
    FileError error,
    scoped_ptr<ResourceEntry> entry) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!initialized_callback.is_null());
  DCHECK(!get_content_callback.is_null());
  DCHECK(!completion_callback.is_null());

  if (error != FILE_ERROR_OK) {
    completion_callback.Run(error);
    return;
  }

  DCHECK(entry);
  GetResolvedFileByPath(
      make_scoped_ptr(new GetResolvedFileParams(
          file_path,
          DriveClientContext(USER_INITIATED),
          entry.Pass(),
          initialized_callback,
          base::Bind(&GetFileCallbackToFileOperationCallbackAdapter,
                     completion_callback),
          get_content_callback)));
}

void FileSystem::GetEntryInfoByPath(const base::FilePath& file_path,
                                    const GetEntryInfoCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  // ResourceMetadata may know about the entry even if the resource
  // metadata is not yet fully loaded. For instance, ResourceMetadata()
  // always knows about the root directory. For "fast fetch"
  // (crbug.com/178348) to work, it's needed to delay the resource metadata
  // loading until the first call to ReadDirectoryByPath().
  resource_metadata_->GetEntryInfoByPathOnUIThread(
      file_path,
      base::Bind(&FileSystem::GetEntryInfoByPathAfterGetEntry1,
                 weak_ptr_factory_.GetWeakPtr(),
                 file_path,
                 callback));
}

void FileSystem::GetEntryInfoByPathAfterGetEntry1(
    const base::FilePath& file_path,
    const GetEntryInfoCallback& callback,
    FileError error,
    scoped_ptr<ResourceEntry> entry) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  if (error == FILE_ERROR_OK) {
    CheckLocalModificationAndRun(entry.Pass(), callback);
    return;
  }

  // If the information about the path is not in the local ResourceMetadata,
  // try fetching information of the directory and retry.
  LoadDirectoryIfNeeded(
      file_path.DirName(),
      base::Bind(&FileSystem::GetEntryInfoByPathAfterLoad,
                 weak_ptr_factory_.GetWeakPtr(),
                 file_path,
                 callback));
}

void FileSystem::GetEntryInfoByPathAfterLoad(
    const base::FilePath& file_path,
    const GetEntryInfoCallback& callback,
    FileError error) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  if (error != FILE_ERROR_OK) {
    callback.Run(error, scoped_ptr<ResourceEntry>());
    return;
  }

  resource_metadata_->GetEntryInfoByPathOnUIThread(
      file_path,
      base::Bind(&FileSystem::GetEntryInfoByPathAfterGetEntry2,
                 weak_ptr_factory_.GetWeakPtr(),
                 callback));
}

void FileSystem::GetEntryInfoByPathAfterGetEntry2(
    const GetEntryInfoCallback& callback,
    FileError error,
    scoped_ptr<ResourceEntry> entry) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  if (error != FILE_ERROR_OK) {
    callback.Run(error, scoped_ptr<ResourceEntry>());
    return;
  }
  DCHECK(entry.get());

  CheckLocalModificationAndRun(entry.Pass(), callback);
}

void FileSystem::ReadDirectoryByPath(
    const base::FilePath& directory_path,
    const ReadDirectoryWithSettingCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  LoadDirectoryIfNeeded(
      directory_path,
      base::Bind(&FileSystem::ReadDirectoryByPathAfterLoad,
                 weak_ptr_factory_.GetWeakPtr(),
                 directory_path,
                 callback));
}

void FileSystem::LoadDirectoryIfNeeded(const base::FilePath& directory_path,
                                       const FileOperationCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  // As described in GetEntryInfoByPath(), ResourceMetadata may know
  // about the entry even if the file system is not yet fully loaded, hence we
  // should just ask ResourceMetadata first.
  resource_metadata_->GetEntryInfoByPathOnUIThread(
      directory_path,
      base::Bind(&FileSystem::LoadDirectoryIfNeededAfterGetEntry,
                 weak_ptr_factory_.GetWeakPtr(),
                 directory_path,
                 callback));
}

void FileSystem::LoadDirectoryIfNeededAfterGetEntry(
    const base::FilePath& directory_path,
    const FileOperationCallback& callback,
    FileError error,
    scoped_ptr<ResourceEntry> entry) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  if (error != FILE_ERROR_OK ||
      entry->resource_id() == util::kDriveOtherDirSpecialResourceId) {
    // If we don't know about the directory, or it is the "drive/other"
    // directory that has to gather all orphan entries, start loading full
    // resource list.
    change_list_loader_->LoadIfNeeded(DirectoryFetchInfo(), callback);
    return;
  }

  if (!entry->file_info().is_directory()) {
    callback.Run(FILE_ERROR_NOT_A_DIRECTORY);
    return;
  }

  // Pass the directory fetch info so we can fetch the contents of the
  // directory before loading change lists.
  DirectoryFetchInfo directory_fetch_info(
      entry->resource_id(),
      entry->directory_specific_info().changestamp());
  change_list_loader_->LoadIfNeeded(directory_fetch_info, callback);
}

void FileSystem::ReadDirectoryByPathAfterLoad(
    const base::FilePath& directory_path,
    const ReadDirectoryWithSettingCallback& callback,
    FileError error) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  if (error != FILE_ERROR_OK) {
    callback.Run(error,
                 hide_hosted_docs_,
                 scoped_ptr<ResourceEntryVector>());
    return;
  }

  resource_metadata_->ReadDirectoryByPathOnUIThread(
      directory_path,
      base::Bind(&FileSystem::ReadDirectoryByPathAfterRead,
                 weak_ptr_factory_.GetWeakPtr(),
                 callback));
}

void FileSystem::ReadDirectoryByPathAfterRead(
    const ReadDirectoryWithSettingCallback& callback,
    FileError error,
    scoped_ptr<ResourceEntryVector> entries) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  if (error != FILE_ERROR_OK) {
    callback.Run(error,
                 hide_hosted_docs_,
                 scoped_ptr<ResourceEntryVector>());
    return;
  }
  DCHECK(entries.get());  // This is valid for empty directories too.

  callback.Run(FILE_ERROR_OK, hide_hosted_docs_, entries.Pass());
}

void FileSystem::GetResolvedFileByPath(
    scoped_ptr<GetResolvedFileParams> params) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(params);

  if (params->entry->file_info().is_directory()) {
    params->OnError(FILE_ERROR_NOT_A_FILE);
    return;
  }

  // The file's entry should have its file specific info.
  DCHECK(params->entry->has_file_specific_info());

  // For a hosted document, we create a special JSON file to represent the
  // document instead of fetching the document content in one of the exported
  // formats. The JSON file contains the edit URL and resource ID of the
  // document.
  if (params->entry->file_specific_info().is_hosted_document()) {
    base::FilePath* temp_file_path = new base::FilePath;
    ResourceEntry* entry_ptr = params->entry.get();
    base::PostTaskAndReplyWithResult(
        blocking_task_runner_,
        FROM_HERE,
        base::Bind(&CreateDocumentJsonFileOnBlockingPool,
                   cache_->GetCacheDirectoryPath(
                       internal::FileCache::CACHE_TYPE_TMP_DOCUMENTS),
                   GURL(entry_ptr->file_specific_info().alternate_url()),
                   entry_ptr->resource_id(),
                   temp_file_path),
        base::Bind(
            &FileSystem::GetResolvedFileByPathAfterCreateDocumentJsonFile,
            weak_ptr_factory_.GetWeakPtr(),
            base::Passed(&params),
            base::Owned(temp_file_path)));
    return;
  }

  // Returns absolute path of the file if it were cached or to be cached.
  ResourceEntry* entry_ptr = params->entry.get();
  cache_->GetFileOnUIThread(
      entry_ptr->resource_id(),
      entry_ptr->file_specific_info().file_md5(),
      base::Bind(
          &FileSystem::GetResolvedFileByPathAfterGetFileFromCache,
          weak_ptr_factory_.GetWeakPtr(),
          base::Passed(&params)));
}

void FileSystem::GetResolvedFileByPathAfterCreateDocumentJsonFile(
    scoped_ptr<GetResolvedFileParams> params,
    const base::FilePath* file_path,
    FileError error) {
  DCHECK(params);
  DCHECK(file_path);

  if (error != FILE_ERROR_OK) {
    params->OnError(error);
    return;
  }

  params->OnCacheFileFound(*file_path);
  params->OnComplete(*file_path);
}

void FileSystem::GetResolvedFileByPathAfterGetFileFromCache(
    scoped_ptr<GetResolvedFileParams> params,
    FileError error,
    const base::FilePath& cache_file_path) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(params);

  // Have we found the file in cache? If so, return it back to the caller.
  if (error == FILE_ERROR_OK) {
    params->OnCacheFileFound(cache_file_path);
    params->OnComplete(cache_file_path);
    return;
  }

  // If cache file is not found, try to download the file from the server
  // instead. This logic is rather complicated but here's how this works:
  //
  // Retrieve fresh file metadata from server. We will extract file size and
  // download url from there. Note that the download url is transient.
  //
  // Check if we have enough space, based on the expected file size.
  // - if we don't have enough space, try to free up the disk space
  // - if we still don't have enough space, return "no space" error
  // - if we have enough space, start downloading the file from the server
  GetResolvedFileParams* params_ptr = params.get();
  scheduler_->GetResourceEntry(
      params_ptr->entry->resource_id(),
      params_ptr->context,
      base::Bind(&FileSystem::GetResolvedFileByPathAfterGetResourceEntry,
                 weak_ptr_factory_.GetWeakPtr(),
                 base::Passed(&params)));
}

void FileSystem::GetResolvedFileByPathAfterGetResourceEntry(
    scoped_ptr<GetResolvedFileParams> params,
    google_apis::GDataErrorCode status,
    scoped_ptr<google_apis::ResourceEntry> entry) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(params);

  const FileError error = util::GDataToFileError(status);
  if (error != FILE_ERROR_OK) {
    params->OnError(error);
    return;
  }

  // The download URL is:
  // 1) src attribute of content element, on GData WAPI.
  // 2) the value of the key 'downloadUrl', on Drive API v2.
  // In both cases, we can use ResourceEntry::download_url().
  const GURL& download_url = entry->download_url();

  // The download URL can be empty for non-downloadable files (such as files
  // shared from others with "prevent downloading by viewers" flag set.)
  if (download_url.is_empty()) {
    params->OnError(FILE_ERROR_ACCESS_DENIED);
    return;
  }

  DCHECK_EQ(params->entry->resource_id(), entry->resource_id());
  resource_metadata_->RefreshEntryOnUIThread(
      ConvertToResourceEntry(*entry),
      base::Bind(&FileSystem::GetResolvedFileByPathAfterRefreshEntry,
                 weak_ptr_factory_.GetWeakPtr(),
                 base::Passed(&params),
                 download_url));
}

void FileSystem::GetResolvedFileByPathAfterRefreshEntry(
    scoped_ptr<GetResolvedFileParams> params,
    const GURL& download_url,
    FileError error,
    const base::FilePath& drive_file_path,
    scoped_ptr<ResourceEntry> entry) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(params);

  if (error != FILE_ERROR_OK) {
    params->OnError(error);
    return;
  }

  int64 file_size = entry->file_info().size();
  params->entry = entry.Pass();  // Update the entry in |params|.
  cache_->FreeDiskSpaceIfNeededForOnUIThread(
      file_size,
      base::Bind(&FileSystem::GetResolvedFileByPathAfterFreeDiskSpace,
                 weak_ptr_factory_.GetWeakPtr(),
                 base::Passed(&params),
                 download_url));
}

void FileSystem::GetResolvedFileByPathAfterFreeDiskSpace(
    scoped_ptr<GetResolvedFileParams> params,
    const GURL& download_url,
    bool has_enough_space) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(params);

  if (!has_enough_space) {
    // If no enough space, return FILE_ERROR_NO_SPACE.
    params->OnError(FILE_ERROR_NO_SPACE);
    return;
  }

  // We have enough disk space. Create download destination file.
  const base::FilePath temp_download_directory = cache_->GetCacheDirectoryPath(
      internal::FileCache::CACHE_TYPE_TMP_DOWNLOADS);
  base::FilePath* file_path = new base::FilePath;
  base::PostTaskAndReplyWithResult(
      blocking_task_runner_,
      FROM_HERE,
      base::Bind(&CreateTemporaryReadableFileInDir,
                 temp_download_directory,
                 file_path),
      base::Bind(&FileSystem::GetResolveFileByPathAfterCreateTemporaryFile,
                 weak_ptr_factory_.GetWeakPtr(),
                 base::Passed(&params),
                 download_url,
                 base::Owned(file_path)));
}

void FileSystem::GetResolveFileByPathAfterCreateTemporaryFile(
    scoped_ptr<GetResolvedFileParams> params,
    const GURL& download_url,
    base::FilePath* temp_file,
    bool success) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(params);

  if (!success) {
    params->OnError(FILE_ERROR_FAILED);
    return;
  }

  GetResolvedFileParams* params_ptr = params.get();
  JobID id = scheduler_->DownloadFile(
      params_ptr->drive_file_path,
      *temp_file,
      download_url,
      params_ptr->context,
      base::Bind(&FileSystem::GetResolvedFileByPathAfterDownloadFile,
                 weak_ptr_factory_.GetWeakPtr(),
                 base::Passed(&params)),
      params_ptr->get_content_callback);
  params_ptr->OnStartDownloading(
      base::Bind(&FileSystem::CancelJobInScheduler,
                 weak_ptr_factory_.GetWeakPtr(),
                 id));
}

void FileSystem::GetResolvedFileByPathAfterDownloadFile(
    scoped_ptr<GetResolvedFileParams> params,
    google_apis::GDataErrorCode status,
    const base::FilePath& downloaded_file_path) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(params);

  // If user cancels download of a pinned-but-not-fetched file, mark file as
  // unpinned so that we do not sync the file again.
  if (status == google_apis::GDATA_CANCELLED) {
    cache_->GetCacheEntryOnUIThread(
        params->entry->resource_id(),
        params->entry->file_specific_info().file_md5(),
        base::Bind(
            &FileSystem::GetResolvedFileByPathAfterGetCacheEntryForCancel,
            weak_ptr_factory_.GetWeakPtr(),
            params->entry->resource_id(),
            params->entry->file_specific_info().file_md5()));
  }

  FileError error = util::GDataToFileError(status);
  if (error != FILE_ERROR_OK) {
    params->OnError(error);
    return;
  }

  ResourceEntry* entry = params->entry.get();
  cache_->StoreOnUIThread(
      entry->resource_id(),
      entry->file_specific_info().file_md5(),
      downloaded_file_path,
      internal::FileCache::FILE_OPERATION_MOVE,
      base::Bind(&FileSystem::GetResolvedFileByPathAfterStore,
                 weak_ptr_factory_.GetWeakPtr(),
                 base::Passed(&params),
                 downloaded_file_path));
}

void FileSystem::GetResolvedFileByPathAfterGetCacheEntryForCancel(
    const std::string& resource_id,
    const std::string& md5,
    bool success,
    const FileCacheEntry& cache_entry) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  // TODO(hshi): http://crbug.com/127138 notify when file properties change.
  // This allows file manager to clear the "Available offline" checkbox.
  if (success && cache_entry.is_pinned()) {
    cache_->UnpinOnUIThread(resource_id,
                            md5,
                            base::Bind(&util::EmptyFileOperationCallback));
  }
}

void FileSystem::GetResolvedFileByPathAfterStore(
    scoped_ptr<GetResolvedFileParams> params,
    const base::FilePath& downloaded_file_path,
    FileError error) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(params);

  if (error != FILE_ERROR_OK) {
    blocking_task_runner_->PostTask(
        FROM_HERE,
        base::Bind(base::IgnoreResult(&file_util::Delete),
                   downloaded_file_path,
                   false /* recursive*/));
    params->OnError(error);
    return;
  }
  // Storing to cache changes the "offline available" status, hence notify.
  OnDirectoryChanged(params->drive_file_path.DirName());

  ResourceEntry* entry = params->entry.get();
  cache_->GetFileOnUIThread(
      entry->resource_id(),
      entry->file_specific_info().file_md5(),
      base::Bind(&FileSystem::GetResolvedFileByPathAfterGetFile,
                 weak_ptr_factory_.GetWeakPtr(),
                 base::Passed(&params)));
}

void FileSystem::GetResolvedFileByPathAfterGetFile(
    scoped_ptr<GetResolvedFileParams> params,
    FileError error,
    const base::FilePath& cache_file) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(params);

  if (error != FILE_ERROR_OK) {
    params->OnError(error);
    return;
  }
  params->OnComplete(cache_file);
}

void FileSystem::RefreshDirectory(
    const base::FilePath& directory_path,
    const FileOperationCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  // Make sure the destination directory exists.
  resource_metadata_->GetEntryInfoByPathOnUIThread(
      directory_path,
      base::Bind(&FileSystem::RefreshDirectoryAfterGetEntryInfo,
                 weak_ptr_factory_.GetWeakPtr(),
                 directory_path,
                 callback));
}

void FileSystem::RefreshDirectoryAfterGetEntryInfo(
    const base::FilePath& directory_path,
    const FileOperationCallback& callback,
    FileError error,
    scoped_ptr<ResourceEntry> entry) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  if (error != FILE_ERROR_OK) {
    callback.Run(error);
    return;
  }
  if (!entry->file_info().is_directory()) {
    callback.Run(FILE_ERROR_NOT_A_DIRECTORY);
    return;
  }
  if (util::IsSpecialResourceId(entry->resource_id())) {
    // Do not load special directories. Just return.
    callback.Run(FILE_ERROR_OK);
    return;
  }

  change_list_loader_->LoadDirectoryFromServer(
      entry->resource_id(),
      callback);
}

void FileSystem::UpdateFileByResourceId(
    const std::string& resource_id,
    const DriveClientContext& context,
    const FileOperationCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  drive_operations_.UpdateFileByResourceId(resource_id, context, callback);
}

void FileSystem::GetAvailableSpace(
    const GetAvailableSpaceCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  scheduler_->GetAboutResource(
      base::Bind(&FileSystem::OnGetAboutResource,
                 weak_ptr_factory_.GetWeakPtr(),
                 callback));
}

void FileSystem::OnGetAboutResource(
    const GetAvailableSpaceCallback& callback,
    google_apis::GDataErrorCode status,
    scoped_ptr<google_apis::AboutResource> about_resource) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  FileError error = util::GDataToFileError(status);
  if (error != FILE_ERROR_OK) {
    callback.Run(error, -1, -1);
    return;
  }
  DCHECK(about_resource);

  callback.Run(FILE_ERROR_OK,
               about_resource->quota_bytes_total(),
               about_resource->quota_bytes_used());
}

void FileSystem::OnSearch(const SearchCallback& search_callback,
                          ScopedVector<ChangeList> change_lists,
                          FileError error) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!search_callback.is_null());

  if (error != FILE_ERROR_OK) {
    search_callback.Run(error,
                        GURL(),
                        scoped_ptr<std::vector<SearchResultInfo> >());
    return;
  }

  // The search results will be returned using virtual directory.
  // The directory is not really part of the file system, so it has no parent or
  // root.
  std::vector<SearchResultInfo>* results(new std::vector<SearchResultInfo>());
  scoped_ptr<std::vector<SearchResultInfo> > result_vec(results);

  DCHECK_EQ(1u, change_lists.size());
  const ChangeList* change_list = change_lists[0];

  // TODO(tbarzic): Limit total number of returned results for the query.
  const GURL& next_feed = change_list->next_url();

  const base::Closure callback = base::Bind(
      search_callback, FILE_ERROR_OK, next_feed, base::Passed(&result_vec));

  const std::vector<ResourceEntry>& entries = change_list->entries();
  if (entries.empty()) {
    callback.Run();
    return;
  }

  DVLOG(1) << "OnSearch number of entries=" << entries.size();
  // Go through all entries generated by the feed and add them to the search
  // result directory.
  for (size_t i = 0; i < entries.size(); ++i) {
    // Run the callback if this is the last iteration of the loop.
    const bool should_run_callback = (i + 1 == entries.size());
    const ResourceEntry& entry = entries[i];

    const GetEntryInfoWithFilePathCallback entry_info_callback =
        base::Bind(&FileSystem::AddToSearchResults,
                   weak_ptr_factory_.GetWeakPtr(),
                   results,
                   should_run_callback,
                   callback);

    resource_metadata_->RefreshEntryOnUIThread(entry, entry_info_callback);
  }
}

void FileSystem::AddToSearchResults(
    std::vector<SearchResultInfo>* results,
    bool should_run_callback,
    const base::Closure& callback,
    FileError error,
    const base::FilePath& drive_file_path,
    scoped_ptr<ResourceEntry> entry) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  // If a result is not present in our local file system snapshot, call
  // CheckForUpdates to refresh the snapshot with a delta feed. This may happen
  // if the entry has recently been added to the drive (and we still haven't
  // received its delta feed).
  if (error == FILE_ERROR_OK) {
    DCHECK(entry.get());
    results->push_back(SearchResultInfo(drive_file_path, *entry.get()));
    DVLOG(1) << "AddToSearchResults " << drive_file_path.value();
  } else if (error == FILE_ERROR_NOT_FOUND) {
    CheckForUpdates();
  } else {
    NOTREACHED();
  }

  if (should_run_callback)
    callback.Run();
}

void FileSystem::Search(const std::string& search_query,
                        const GURL& next_feed,
                        const SearchCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  change_list_loader_->SearchFromServer(
      search_query,
      next_feed,
      base::Bind(&FileSystem::OnSearch,
                 weak_ptr_factory_.GetWeakPtr(),
                 callback));
}

void FileSystem::SearchMetadata(const std::string& query,
                                int options,
                                int at_most_num_matches,
                                const SearchMetadataCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (hide_hosted_docs_)
    options |= SEARCH_METADATA_EXCLUDE_HOSTED_DOCUMENTS;

  drive::SearchMetadata(blocking_task_runner_,
                        resource_metadata_,
                        query,
                        options,
                        at_most_num_matches,
                        callback);
}

void FileSystem::OnDirectoryChangedByOperation(
    const base::FilePath& directory_path) {
  OnDirectoryChanged(directory_path);
}

void FileSystem::OnDirectoryChanged(const base::FilePath& directory_path) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  FOR_EACH_OBSERVER(FileSystemObserver, observers_,
                    OnDirectoryChanged(directory_path));
}

void FileSystem::OnFeedFromServerLoaded() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  FOR_EACH_OBSERVER(FileSystemObserver, observers_,
                    OnFeedFromServerLoaded());
}

void FileSystem::OnInitialFeedLoaded() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  FOR_EACH_OBSERVER(FileSystemObserver,
                    observers_,
                    OnInitialLoadFinished());
}

void FileSystem::AddUploadedFile(
    scoped_ptr<google_apis::ResourceEntry> entry,
    const base::FilePath& file_content_path,
    const FileOperationCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(entry.get());
  DCHECK(!entry->resource_id().empty());
  DCHECK(!entry->file_md5().empty());
  DCHECK(!callback.is_null());

  AddUploadedFileParams params(file_content_path,
                               callback,
                               entry->resource_id(),
                               entry->file_md5());

  resource_metadata_->AddEntryOnUIThread(
      ConvertToResourceEntry(*entry),
      base::Bind(&FileSystem::AddUploadedFileToCache,
                 weak_ptr_factory_.GetWeakPtr(), params));
}

void FileSystem::AddUploadedFileToCache(
    const AddUploadedFileParams& params,
    FileError error,
    const base::FilePath& file_path) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!params.resource_id.empty());
  DCHECK(!params.md5.empty());
  DCHECK(!params.callback.is_null());

  // Depending on timing, a metadata may have inserted via delta feed already.
  // So, FILE_ERROR_EXISTS is not an error.
  if (error != FILE_ERROR_OK && error != FILE_ERROR_EXISTS) {
    params.callback.Run(error);
    return;
  }

  OnDirectoryChanged(file_path.DirName());

  // At this point, upload to the server is fully succeeded. Failure to store to
  // cache is not a fatal error, so we wrap the callback with IgnoreError, and
  // always return success to the caller.
  cache_->StoreOnUIThread(params.resource_id,
                          params.md5,
                          params.file_content_path,
                          internal::FileCache::FILE_OPERATION_COPY,
                          base::Bind(&IgnoreError, params.callback));
}

void FileSystem::GetMetadata(
    const GetFilesystemMetadataCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  FileSystemMetadata metadata;
  metadata.refreshing = change_list_loader_->IsRefreshing();

  // Metadata related to delta update.
  metadata.last_update_check_time = last_update_check_time_;
  metadata.last_update_check_error = last_update_check_error_;

  resource_metadata_->GetLargestChangestampOnUIThread(
      base::Bind(&OnGetLargestChangestamp, metadata, callback));
}

void FileSystem::MarkCacheFileAsMounted(
    const base::FilePath& drive_file_path,
    const OpenFileCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  GetEntryInfoByPath(
      drive_file_path,
      base::Bind(&FileSystem::MarkCacheFileAsMountedAfterGetEntryInfo,
                 weak_ptr_factory_.GetWeakPtr(), callback));
}

void FileSystem::MarkCacheFileAsMountedAfterGetEntryInfo(
    const OpenFileCallback& callback,
    FileError error,
    scoped_ptr<ResourceEntry> entry) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  if (error != FILE_ERROR_OK) {
    callback.Run(error, base::FilePath());
    return;
  }

  DCHECK(entry);
  cache_->MarkAsMountedOnUIThread(entry->resource_id(),
                                  entry->file_specific_info().file_md5(),
                                  callback);
}

void FileSystem::MarkCacheFileAsUnmounted(
    const base::FilePath& cache_file_path,
    const FileOperationCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  if (!cache_->IsUnderFileCacheDirectory(cache_file_path)) {
    callback.Run(FILE_ERROR_FAILED);
    return;
  }
  cache_->MarkAsUnmountedOnUIThread(cache_file_path, callback);
}

void FileSystem::GetCacheEntryByResourceId(
    const std::string& resource_id,
    const std::string& md5,
    const GetCacheEntryCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!resource_id.empty());
  DCHECK(!callback.is_null());

  cache_->GetCacheEntryOnUIThread(resource_id, md5, callback);
}

void FileSystem::OnDisableDriveHostedFilesChanged() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  PrefService* pref_service = profile_->GetPrefs();
  SetHideHostedDocuments(
      pref_service->GetBoolean(prefs::kDisableDriveHostedFiles));
}

void FileSystem::SetHideHostedDocuments(bool hide) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (hide == hide_hosted_docs_)
    return;

  hide_hosted_docs_ = hide;

  // Kick off directory refresh when this setting changes.
  FOR_EACH_OBSERVER(FileSystemObserver, observers_,
                    OnDirectoryChanged(util::GetDriveGrandRootPath()));
}

//============= FileSystem: internal helper functions =====================

void FileSystem::InitializePreferenceObserver() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  pref_registrar_.reset(new PrefChangeRegistrar());
  pref_registrar_->Init(profile_->GetPrefs());
  pref_registrar_->Add(
      prefs::kDisableDriveHostedFiles,
      base::Bind(&FileSystem::OnDisableDriveHostedFilesChanged,
                 base::Unretained(this)));
}

void FileSystem::OpenFile(const base::FilePath& file_path,
                          const OpenFileCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  // If the file is already opened, it cannot be opened again before closed.
  // This is for avoiding simultaneous modification to the file, and moreover
  // to avoid an inconsistent cache state (suppose an operation sequence like
  // Open->Open->modify->Close->modify->Close; the second modify may not be
  // synchronized to the server since it is already Closed on the cache).
  if (open_files_.find(file_path) != open_files_.end()) {
    base::MessageLoopProxy::current()->PostTask(
        FROM_HERE,
        base::Bind(callback, FILE_ERROR_IN_USE, base::FilePath()));
    return;
  }
  open_files_.insert(file_path);

  resource_metadata_->GetEntryInfoByPathOnUIThread(
      file_path,
      base::Bind(&FileSystem::OnGetEntryInfoCompleteForOpenFile,
                 weak_ptr_factory_.GetWeakPtr(),
                 file_path,
                 base::Bind(&FileSystem::OnOpenFileFinished,
                            weak_ptr_factory_.GetWeakPtr(),
                            file_path,
                            callback)));
}

void FileSystem::OnGetEntryInfoCompleteForOpenFile(
    const base::FilePath& file_path,
    const OpenFileCallback& callback,
    FileError error,
    scoped_ptr<ResourceEntry> entry) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());
  DCHECK(entry.get() || error != FILE_ERROR_OK);

  if (entry.get() && !entry->has_file_specific_info())
    error = FILE_ERROR_NOT_FOUND;

  if (error == FILE_ERROR_OK) {
    if (entry->file_specific_info().file_md5().empty() ||
        entry->file_specific_info().is_hosted_document()) {
      // No support for opening a directory or hosted document.
      error = FILE_ERROR_INVALID_OPERATION;
    }
  }

  if (error != FILE_ERROR_OK) {
    callback.Run(error, base::FilePath());
    return;
  }

  DCHECK(!entry->resource_id().empty());
  // Extract a pointer before we call Pass() so we can use it below.
  ResourceEntry* entry_ptr = entry.get();
  GetResolvedFileByPath(
      make_scoped_ptr(new GetResolvedFileParams(
          file_path,
          DriveClientContext(USER_INITIATED),
          entry.Pass(),
          GetFileContentInitializedCallback(),
          base::Bind(&FileSystem::OnGetFileCompleteForOpenFile,
                     weak_ptr_factory_.GetWeakPtr(),
                     GetFileCompleteForOpenParams(
                         callback,
                         entry_ptr->resource_id(),
                         entry_ptr->file_specific_info().file_md5())),
          google_apis::GetContentCallback())));
}

void FileSystem::OnGetFileCompleteForOpenFile(
    const GetFileCompleteForOpenParams& params,
    FileError error,
    const base::FilePath& file_path,
    scoped_ptr<ResourceEntry> entry) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!params.callback.is_null());

  if (error != FILE_ERROR_OK) {
    params.callback.Run(error, base::FilePath());
    return;
  }

  // OpenFile ensures that the file is a regular file.
  DCHECK(entry && !entry->file_specific_info().is_hosted_document());

  cache_->MarkDirtyOnUIThread(
      params.resource_id,
      params.md5,
      base::Bind(&FileSystem::OnMarkDirtyInCacheCompleteForOpenFile,
                 weak_ptr_factory_.GetWeakPtr(),
                 params));
}

void FileSystem::OnMarkDirtyInCacheCompleteForOpenFile(
    const GetFileCompleteForOpenParams& params,
    FileError error) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!params.callback.is_null());

  if (error != FILE_ERROR_OK) {
    params.callback.Run(error, base::FilePath());
    return;
  }

  cache_->GetFileOnUIThread(params.resource_id, params.md5, params.callback);
}

void FileSystem::OnOpenFileFinished(
    const base::FilePath& file_path,
    const OpenFileCallback& callback,
    FileError result,
    const base::FilePath& cache_file_path) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  // All the invocation of |callback| from operations initiated from OpenFile
  // must go through here. Removes the |file_path| from the remembered set when
  // the file was not successfully opened.
  if (result != FILE_ERROR_OK)
    open_files_.erase(file_path);

  callback.Run(result, cache_file_path);
}

void FileSystem::CloseFile(const base::FilePath& file_path,
                           const FileOperationCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  if (open_files_.find(file_path) == open_files_.end()) {
    // The file is not being opened.
    base::MessageLoopProxy::current()->PostTask(
        FROM_HERE,
        base::Bind(callback, FILE_ERROR_NOT_FOUND));
    return;
  }

  // Step 1 of CloseFile: Get resource_id and md5 for |file_path|.
  resource_metadata_->GetEntryInfoByPathOnUIThread(
      file_path,
      base::Bind(&FileSystem::CloseFileAfterGetEntryInfo,
                 weak_ptr_factory_.GetWeakPtr(),
                 file_path,
                 base::Bind(&FileSystem::CloseFileFinalize,
                            weak_ptr_factory_.GetWeakPtr(),
                            file_path,
                            callback)));
}

void FileSystem::CloseFileAfterGetEntryInfo(
    const base::FilePath& file_path,
    const FileOperationCallback& callback,
    FileError error,
    scoped_ptr<ResourceEntry> entry) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  if (entry.get() && !entry->has_file_specific_info())
    error = FILE_ERROR_NOT_FOUND;

  if (error != FILE_ERROR_OK) {
    callback.Run(error);
    return;
  }

  // Step 2 of CloseFile: Commit the modification in cache. This will trigger
  // background upload.
  // TODO(benchan,kinaba): Call ClearDirtyInCache instead of CommitDirtyInCache
  // if the file has not been modified. Come up with a way to detect the
  // intactness effectively, or provide a method for user to declare it when
  // calling CloseFile().
  cache_->CommitDirtyOnUIThread(entry->resource_id(),
                                entry->file_specific_info().file_md5(),
                                callback);
}

void FileSystem::CloseFileFinalize(const base::FilePath& file_path,
                                   const FileOperationCallback& callback,
                                   FileError result) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  // Step 3 of CloseFile.
  // All the invocation of |callback| from operations initiated from CloseFile
  // must go through here. Removes the |file_path| from the remembered set so
  // that subsequent operations can open the file again.
  open_files_.erase(file_path);

  // Then invokes the user-supplied callback function.
  callback.Run(result);
}

void FileSystem::CheckLocalModificationAndRun(
    scoped_ptr<ResourceEntry> entry,
    const GetEntryInfoCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(entry.get());
  DCHECK(!callback.is_null());

  // For entries that will never be cached, use the original entry info as is.
  if (!entry->has_file_specific_info() ||
      entry->file_specific_info().is_hosted_document()) {
    callback.Run(FILE_ERROR_OK, entry.Pass());
    return;
  }

  // Checks if the file is cached and modified locally.
  const std::string resource_id = entry->resource_id();
  const std::string md5 = entry->file_specific_info().file_md5();
  cache_->GetCacheEntryOnUIThread(
      resource_id,
      md5,
      base::Bind(
          &FileSystem::CheckLocalModificationAndRunAfterGetCacheEntry,
          weak_ptr_factory_.GetWeakPtr(),
          base::Passed(&entry),
          callback));
}

void FileSystem::CheckLocalModificationAndRunAfterGetCacheEntry(
    scoped_ptr<ResourceEntry> entry,
    const GetEntryInfoCallback& callback,
    bool success,
    const FileCacheEntry& cache_entry) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  // When no dirty cache is found, use the original entry info as is.
  if (!success || !cache_entry.is_dirty()) {
    callback.Run(FILE_ERROR_OK, entry.Pass());
    return;
  }

  // Gets the cache file path.
  const std::string& resource_id = entry->resource_id();
  const std::string& md5 = entry->file_specific_info().file_md5();
  cache_->GetFileOnUIThread(
      resource_id,
      md5,
      base::Bind(
          &FileSystem::CheckLocalModificationAndRunAfterGetCacheFile,
          weak_ptr_factory_.GetWeakPtr(),
          base::Passed(&entry),
          callback));
}

void FileSystem::CheckLocalModificationAndRunAfterGetCacheFile(
    scoped_ptr<ResourceEntry> entry,
    const GetEntryInfoCallback& callback,
    FileError error,
    const base::FilePath& local_cache_path) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  // When no dirty cache is found, use the original entry info as is.
  if (error != FILE_ERROR_OK) {
    callback.Run(FILE_ERROR_OK, entry.Pass());
    return;
  }

  // If the cache is dirty, obtain the file info from the cache file itself.
  base::PlatformFileInfo* file_info = new base::PlatformFileInfo;
  base::PostTaskAndReplyWithResult(
      blocking_task_runner_,
      FROM_HERE,
      base::Bind(&file_util::GetFileInfo,
                 local_cache_path,
                 base::Unretained(file_info)),
      base::Bind(&FileSystem::CheckLocalModificationAndRunAfterGetFileInfo,
                 weak_ptr_factory_.GetWeakPtr(),
                 base::Passed(&entry),
                 callback,
                 base::Owned(file_info)));
}

void FileSystem::CheckLocalModificationAndRunAfterGetFileInfo(
    scoped_ptr<ResourceEntry> entry,
    const GetEntryInfoCallback& callback,
    base::PlatformFileInfo* file_info,
    bool get_file_info_result) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  if (!get_file_info_result) {
    callback.Run(FILE_ERROR_NOT_FOUND, scoped_ptr<ResourceEntry>());
    return;
  }

  PlatformFileInfoProto entry_file_info;
  util::ConvertPlatformFileInfoToResourceEntry(*file_info, &entry_file_info);
  *entry->mutable_file_info() = entry_file_info;
  callback.Run(FILE_ERROR_OK, entry.Pass());
}

void FileSystem::CancelJobInScheduler(JobID id) {
  scheduler_->CancelJob(id);
}

}  // namespace drive