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
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/gdata/gdata_file_system.h"
#include <errno.h>
#include <sys/stat.h>
#include <set>
#include <utility>
#include "base/bind.h"
#include "base/chromeos/chromeos_version.h"
#include "base/eintr_wrapper.h"
#include "base/file_util.h"
#include "base/json/json_file_value_serializer.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/message_loop.h"
#include "base/message_loop_proxy.h"
#include "base/metrics/histogram.h"
#include "base/platform_file.h"
#include "base/sys_info.h"
#include "base/threading/platform_thread.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/threading/thread_restrictions.h"
#include "base/synchronization/waitable_event.h"
#include "base/values.h"
#include "chrome/browser/chromeos/gdata/drive_webapps_registry.h"
#include "chrome/browser/chromeos/gdata/gdata.pb.h"
#include "chrome/browser/chromeos/gdata/gdata_documents_service.h"
#include "chrome/browser/chromeos/gdata/gdata_download_observer.h"
#include "chrome/browser/chromeos/gdata/gdata_protocol_handler.h"
#include "chrome/browser/chromeos/gdata/gdata_sync_client.h"
#include "chrome/browser/chromeos/gdata/gdata_system_service.h"
#include "chrome/browser/chromeos/gdata/gdata_upload_file_info.h"
#include "chrome/browser/chromeos/gdata/gdata_util.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_details.h"
#include "net/base/mime_util.h"
#include "net/url_request/url_request_filter.h"
using content::BrowserThread;
namespace gdata {
namespace {
const char kMimeTypeJson[] = "application/json";
const char kMimeTypeOctetStream[] = "application/octet-stream";
const char kWildCard[] = "*";
const char kLocallyModifiedFileExtension[] = "local";
const char kMountedArchiveFileExtension[] = "mounted";
const FilePath::CharType kGDataCacheVersionDir[] = FILE_PATH_LITERAL("v1");
const FilePath::CharType kGDataCacheMetaDir[] = FILE_PATH_LITERAL("meta");
const FilePath::CharType kGDataCachePinnedDir[] = FILE_PATH_LITERAL("pinned");
const FilePath::CharType kGDataCacheOutgoingDir[] =
FILE_PATH_LITERAL("outgoing");
const FilePath::CharType kGDataCachePersistentDir[] =
FILE_PATH_LITERAL("persistent");
const FilePath::CharType kGDataCacheTmpDir[] = FILE_PATH_LITERAL("tmp");
const FilePath::CharType kGDataCacheTmpDownloadsDir[] =
FILE_PATH_LITERAL("tmp/downloads");
const FilePath::CharType kGDataCacheTmpDocumentsDir[] =
FILE_PATH_LITERAL("tmp/documents");
const FilePath::CharType kAccountMetadataFile[] =
FILE_PATH_LITERAL("account_metadata.json");
const FilePath::CharType kFilesystemProtoFile[] =
FILE_PATH_LITERAL("file_system.pb");
const FilePath::CharType kSymLinkToDevNull[] = FILE_PATH_LITERAL("/dev/null");
// GData update check interval (in seconds).
#ifndef NDEBUG
const int kGDataUpdateCheckIntervalInSec = 5;
#else
const int kGDataUpdateCheckIntervalInSec = 60;
#endif
// Schedule for dumping root file system proto buffers to disk depending its
// total protobuffer size in MB.
typedef struct {
double size;
int timeout;
} SerializationTimetable;
SerializationTimetable kSerializeTimetable[] = {
#ifndef NDEBUG
{0.5, 0}, // Less than 0.5MB, dump immediately.
{-1, 1}, // Any size, dump if older than 1 minue.
#else
{0.5, 0}, // Less than 0.5MB, dump immediately.
{1.0, 15}, // Less than 1.0MB, dump after 15 minutes.
{2.0, 30},
{4.0, 60},
{-1, 120}, // Any size, dump if older than 120 minues.
#endif
};
// Defines set of parameters sent to callback OnProtoLoaded().
struct LoadRootFeedParams {
LoadRootFeedParams(
FilePath search_file_path,
bool should_load_from_server,
const FindEntryCallback& callback)
: search_file_path(search_file_path),
should_load_from_server(should_load_from_server),
load_error(base::PLATFORM_FILE_OK),
callback(callback) {
}
~LoadRootFeedParams() {
}
FilePath search_file_path;
bool should_load_from_server;
std::string proto;
base::PlatformFileError load_error;
base::Time last_modified;
const FindEntryCallback callback;
};
// Returns true if file system is due to be serialized on disk based on it
// |serialized_size| and |last_serialized| timestamp.
bool ShouldSerializeFileSystemNow(size_t serialized_size,
const base::Time& last_serialized) {
const double size_in_mb = serialized_size / 1048576.0;
const int last_proto_dump_in_min =
(base::Time::Now() - last_serialized).InMinutes();
for (size_t i = 0; i < arraysize(kSerializeTimetable); i++) {
if ((size_in_mb < kSerializeTimetable[i].size ||
kSerializeTimetable[i].size == -1) &&
last_proto_dump_in_min >= kSerializeTimetable[i].timeout) {
return true;
}
}
return false;
}
// Returns the home directory path, or an empty string if the home directory
// is not found.
// Copied from webkit/chromeos/cros_mount_point_provider.h.
// TODO(satorux): Share the code.
std::string GetHomeDirectory() {
if (base::chromeos::IsRunningOnChromeOS())
return "/home/chronos/user";
const char* home = getenv("HOME");
if (home)
return home;
return "";
}
// Used to tweak GetAmountOfFreeDiskSpace() behavior for testing.
FreeDiskSpaceGetterInterface* global_free_disk_getter_for_testing = NULL;
// Gets the amount of free disk space. Use
// |global_free_disk_getter_for_testing| if set.
int64 GetAmountOfFreeDiskSpace() {
if (global_free_disk_getter_for_testing)
return global_free_disk_getter_for_testing->AmountOfFreeDiskSpace();
return base::SysInfo::AmountOfFreeDiskSpace(
FilePath::FromUTF8Unsafe(GetHomeDirectory()));
}
// Returns true if we have sufficient space to store the given number of
// bytes, while keeping kMinFreeSpace bytes on the disk.
bool HasEnoughSpaceFor(int64 num_bytes) {
int64 free_space = GetAmountOfFreeDiskSpace();
// Substract this as if this portion does not exist.
free_space -= kMinFreeSpace;
return (free_space >= num_bytes);
}
// Remove all files under the given directory, non-recursively.
// Do not remove recursively as we don't want to touch <gache>/tmp/downloads,
// which is used for user initiated downloads like "Save As"
void RemoveAllFiles(const FilePath& directory) {
using file_util::FileEnumerator;
FileEnumerator enumerator(directory, false /* recursive */,
FileEnumerator::FILES);
for (FilePath file_path = enumerator.Next(); !file_path.empty();
file_path = enumerator.Next()) {
DVLOG(1) << "Removing " << file_path.value();
if (!file_util::Delete(file_path, false /* recursive */))
LOG(WARNING) << "Failed to delete " << file_path.value();
}
}
// Converts gdata error code into file platform error code.
base::PlatformFileError GDataToPlatformError(GDataErrorCode status) {
switch (status) {
case HTTP_SUCCESS:
case HTTP_CREATED:
return base::PLATFORM_FILE_OK;
case HTTP_UNAUTHORIZED:
case HTTP_FORBIDDEN:
return base::PLATFORM_FILE_ERROR_ACCESS_DENIED;
case HTTP_NOT_FOUND:
return base::PLATFORM_FILE_ERROR_NOT_FOUND;
case GDATA_PARSE_ERROR:
case GDATA_FILE_ERROR:
return base::PLATFORM_FILE_ERROR_ABORT;
default:
return base::PLATFORM_FILE_ERROR_FAILED;
}
}
// Converts system error to file platform error code.
// This is copied and modified from base/platform_file_posix.cc.
// TODO(kuan): base/platform.h should probably export this.
base::PlatformFileError SystemToPlatformError(int error) {
switch (error) {
case 0:
return base::PLATFORM_FILE_OK;
case EACCES:
case EISDIR:
case EROFS:
case EPERM:
return base::PLATFORM_FILE_ERROR_ACCESS_DENIED;
case ETXTBSY:
return base::PLATFORM_FILE_ERROR_IN_USE;
case EEXIST:
return base::PLATFORM_FILE_ERROR_EXISTS;
case ENOENT:
return base::PLATFORM_FILE_ERROR_NOT_FOUND;
case EMFILE:
return base::PLATFORM_FILE_ERROR_TOO_MANY_OPENED;
case ENOMEM:
return base::PLATFORM_FILE_ERROR_NO_MEMORY;
case ENOSPC:
return base::PLATFORM_FILE_ERROR_NO_SPACE;
case ENOTDIR:
return base::PLATFORM_FILE_ERROR_NOT_A_DIRECTORY;
case EINTR:
return base::PLATFORM_FILE_ERROR_ABORT;
default:
return base::PLATFORM_FILE_ERROR_FAILED;
}
}
//================================ Helper functions ============================
// Creates cache directory and its sub-directories if they don't exist.
// TODO(glotov): take care of this when the setup and cleanup part is landed,
// noting that these directories need to be created for development in linux box
// and unittest. (http://crosbug.com/27577)
base::PlatformFileError CreateCacheDirectories(
const std::vector<FilePath>& paths_to_create) {
base::PlatformFileError error = base::PLATFORM_FILE_OK;
for (size_t i = 0; i < paths_to_create.size(); ++i) {
if (file_util::DirectoryExists(paths_to_create[i]))
continue;
if (!file_util::CreateDirectory(paths_to_create[i])) {
// Error creating this directory, record error and proceed with next one.
error = SystemToPlatformError(errno);
PLOG(ERROR) << "Error creating directory " << paths_to_create[i].value();
} else {
DVLOG(1) << "Created directory " << paths_to_create[i].value();
}
}
return error;
}
// Changes the permissions of |file_path| to |permissions|.
// Returns the platform error code of the operation.
base::PlatformFileError ChangeFilePermissions(const FilePath& file_path,
mode_t permissions) {
base::PlatformFileError error = base::PLATFORM_FILE_OK;
if (HANDLE_EINTR(chmod(file_path.value().c_str(), permissions)) != 0) {
error = SystemToPlatformError(errno);
PLOG(ERROR) << "Error changing permissions of " << file_path.value();
} else {
DVLOG(1) << "Changed permissions of " << file_path.value();
}
return error;
}
// Modifies cache state of file on IO thread pool, which involves:
// - moving or copying file (per |file_operation_type|) from |source_path| to
// |dest_path| if they're different
// - deleting symlink if |symlink_path| is not empty
// - creating symlink if |symlink_path| is not empty and |create_symlink| is
// true.
base::PlatformFileError ModifyCacheState(
const FilePath& source_path,
const FilePath& dest_path,
GDataFileSystem::FileOperationType file_operation_type,
const FilePath& symlink_path,
bool create_symlink) {
// Move or copy |source_path| to |dest_path| if they are different.
if (source_path != dest_path) {
bool success = false;
if (file_operation_type == GDataFileSystem::FILE_OPERATION_MOVE)
success = file_util::Move(source_path, dest_path);
else if (file_operation_type ==
GDataFileSystem::FILE_OPERATION_COPY)
success = file_util::CopyFile(source_path, dest_path);
if (!success) {
base::PlatformFileError error = SystemToPlatformError(errno);
PLOG(ERROR) << "Error "
<< (file_operation_type ==
GDataFileSystem::FILE_OPERATION_MOVE ?
"moving " : "copying ")
<< source_path.value()
<< " to " << dest_path.value();
return error;
} else {
DVLOG(1) << (file_operation_type ==
GDataFileSystem::FILE_OPERATION_MOVE ?
"Moved " : "Copied ")
<< source_path.value()
<< " to " << dest_path.value();
}
} else {
DVLOG(1) << "No need to move file: source = destination";
}
if (symlink_path.empty())
return base::PLATFORM_FILE_OK;
// Remove symlink regardless of |create_symlink| because creating a link will
// not overwrite an existing one.
// Cannot use file_util::Delete which uses stat64 to check if path exists
// before deleting it. If path is a symlink, stat64 dereferences it to the
// target file, so it's in essence checking if the target file exists.
// Here in this function, if |symlink_path| references |source_path| and
// |source_path| has just been moved to |dest_path| (e.g. during unpinning),
// symlink will dereference to a non-existent file. This results in stat64
// failing and file_util::Delete bailing out without deleting the symlink.
// We clearly want the symlink deleted even if it dereferences to nothing.
// Unfortunately, deleting the symlink before moving the files won't work for
// the case where move operation fails, but the symlink has already been
// deleted, which shouldn't happen. An example scenario is where an existing
// file is stored to cache and pinned for a specific resource id and md5, then
// a non-existent file is stored to cache for the same resource id and md5.
// The 2nd store-to-cache operation fails when moving files, but the symlink
// created by previous pin operation has already been deleted.
// We definitely want to keep the pinned state of the symlink if subsequent
// operations fail.
// This problem is filed at http://crbug.com/119430.
// We try to save one file operation by not checking if link exists before
// deleting it, so unlink may return error if link doesn't exist, but it
// doesn't really matter to us.
bool deleted = HANDLE_EINTR(unlink(symlink_path.value().c_str())) == 0;
if (deleted) {
DVLOG(1) << "Deleted symlink " << symlink_path.value();
} else {
// Since we didn't check if symlink exists before deleting it, don't log
// if symlink doesn't exist.
if (errno != ENOENT)
PLOG(WARNING) << "Error deleting symlink " << symlink_path.value();
}
if (!create_symlink)
return base::PLATFORM_FILE_OK;
// Create new symlink to |dest_path|.
if (!file_util::CreateSymbolicLink(dest_path, symlink_path)) {
base::PlatformFileError error = SystemToPlatformError(errno);
PLOG(ERROR) << "Error creating symlink " << symlink_path.value()
<< " for " << dest_path.value();
return error;
} else {
DVLOG(1) << "Created symlink " << symlink_path.value()
<< " to " << dest_path.value();
}
return base::PLATFORM_FILE_OK;
}
// Deletes all files that match |path_to_delete_pattern| except for
// |path_to_keep| on IO thread pool.
// If |path_to_keep| is empty, all files in |path_to_delete_pattern| are
// deleted.
void DeleteFilesSelectively(const FilePath& path_to_delete_pattern,
const FilePath& path_to_keep) {
// Enumerate all files in directory of |path_to_delete_pattern| that match
// base name of |path_to_delete_pattern|.
// If a file is not |path_to_keep|, delete it.
bool success = true;
file_util::FileEnumerator enumerator(
path_to_delete_pattern.DirName(),
false, // not recursive
static_cast<file_util::FileEnumerator::FileType>(
file_util::FileEnumerator::FILES |
file_util::FileEnumerator::SHOW_SYM_LINKS),
path_to_delete_pattern.BaseName().value());
for (FilePath current = enumerator.Next(); !current.empty();
current = enumerator.Next()) {
// If |path_to_keep| is not empty and same as current, don't delete it.
if (!path_to_keep.empty() && current == path_to_keep)
continue;
success = HANDLE_EINTR(unlink(current.value().c_str())) == 0;
if (!success)
DVLOG(1) << "Error deleting " << current.value();
else
DVLOG(1) << "Deleted " << current.value();
}
}
// Recursively extracts the paths set of all sub-directories of |entry|.
void GetChildDirectoryPaths(GDataEntry* entry,
std::set<FilePath>* changed_dirs) {
GDataDirectory* dir = entry->AsGDataDirectory();
if (!dir)
return;
for (GDataDirectoryCollection::const_iterator it =
dir->child_directories().begin();
it != dir->child_directories().end(); ++it) {
GDataDirectory* child_dir = it->second;
changed_dirs->insert(child_dir->GetFilePath());
GetChildDirectoryPaths(child_dir, changed_dirs);
}
}
// Helper function for removing |entry| from |directory|. If |entry| is a
// directory too, it will collect all its children file paths into
// |changed_dirs| as well.
void RemoveEntryFromDirectoryAndCollectChangedDirectories(
GDataDirectory* directory,
GDataEntry* entry,
std::set<FilePath>* changed_dirs) {
// Get the list of all sub-directory paths, so we can notify their listeners
// that they are smoked.
GetChildDirectoryPaths(entry, changed_dirs);
directory->RemoveEntry(entry);
}
// Helper function for adding new |file| from the feed into |directory|. It
// checks the type of file and updates |changed_dirs| if this file adding
// opertation needs to raise directory notification update. If file is being
// added to |orphaned_entries_dir| such notifications are not raised since
// we ignore such files and don't add them to the file system now.
void AddEntryToDirectoryAndCollectChangedDirectories(
GDataEntry* entry,
GDataDirectory* directory,
GDataRootDirectory* orphaned_entries_dir,
std::set<FilePath>* changed_dirs) {
directory->AddEntry(entry);
if (entry->AsGDataDirectory() && directory != orphaned_entries_dir)
changed_dirs->insert(entry->GetFilePath());
}
// Invoked upon completion of TransferRegularFile initiated by Copy.
//
// |callback| is run on the thread represented by |relay_proxy|.
void OnTransferRegularFileCompleteForCopy(
const FileOperationCallback& callback,
scoped_refptr<base::MessageLoopProxy> relay_proxy,
base::PlatformFileError error) {
if (!callback.is_null())
relay_proxy->PostTask(FROM_HERE, base::Bind(callback, error));
}
// Runs GetFileCallback with pointers dereferenced.
// Used for PostTaskAndReply().
void RunGetFileCallbackHelper(const GetFileCallback& callback,
base::PlatformFileError* error,
FilePath* file_path,
std::string* mime_type,
GDataFileType* file_type) {
DCHECK(error);
DCHECK(file_path);
DCHECK(mime_type);
DCHECK(file_type);
if (!callback.is_null())
callback.Run(*error, *file_path, *mime_type, *file_type);
}
// Ditto for FileOperationCallback
void RunFileOperationCallbackHelper(
const FileOperationCallback& callback,
base::PlatformFileError* error) {
DCHECK(error);
if (!callback.is_null())
callback.Run(*error);
}
// Ditto for CacheOperationCallback.
void RunCacheOperationCallbackHelper(
const CacheOperationCallback& callback,
base::PlatformFileError* error,
const std::string& resource_id,
const std::string& md5) {
DCHECK(error);
if (!callback.is_null())
callback.Run(*error, resource_id, md5);
}
// Ditto for GetFileFromCacheCallback.
void RunGetFileFromCacheCallbackHelper(
const GetFileFromCacheCallback& callback,
base::PlatformFileError* error,
const std::string& resource_id,
const std::string& md5,
FilePath* cache_file_path) {
DCHECK(error);
DCHECK(cache_file_path);
if (!callback.is_null())
callback.Run(*error, resource_id, md5, *cache_file_path);
}
// Ditto for SetMountedStateCallback
void RunSetMountedStateCallbackHelper(
const SetMountedStateCallback& callback,
base::PlatformFileError* error,
FilePath* cache_file_path) {
DCHECK(error);
DCHECK(cache_file_path);
if (!callback.is_null())
callback.Run(*error, *cache_file_path);
}
void RunGetCacheStateCallbackHelper(
const GetCacheStateCallback& callback,
base::PlatformFileError* error,
int* cache_state) {
DCHECK(error);
DCHECK(cache_state);
if (!callback.is_null())
callback.Run(*error, *cache_state);
}
// The class to wait for the initial load of root feed and runs the callback
// after the initialization.
class InitialLoadObserver : public GDataFileSystemInterface::Observer {
public:
InitialLoadObserver(GDataFileSystemInterface* file_system,
const base::Closure& callback)
: file_system_(file_system), callback_(callback) {}
virtual void OnInitialLoadFinished() OVERRIDE {
if (!callback_.is_null())
base::MessageLoopProxy::current()->PostTask(FROM_HERE, callback_);
file_system_->RemoveObserver(this);
base::MessageLoopProxy::current()->DeleteSoon(FROM_HERE, this);
}
private:
GDataFileSystemInterface* file_system_;
base::Closure callback_;
};
// Saves the string |serialized_proto| to a file at |path| on a blocking thread.
void SaveProtoOnIOThreadPool(const FilePath& path,
scoped_ptr<std::string> serialized_proto) {
const int file_size = static_cast<int>(serialized_proto->length());
if (file_util::WriteFile(path, serialized_proto->data(), file_size) !=
file_size) {
LOG(WARNING) << "GData proto file can't be stored at "
<< path.value();
if (!file_util::Delete(path, true)) {
LOG(WARNING) << "GData proto file can't be deleted at "
<< path.value();
}
}
}
// Loads the file at |path| into the string |serialized_proto| on a blocking
// thread.
void LoadProtoOnIOThreadPool(const FilePath& path,
LoadRootFeedParams* params) {
base::PlatformFileInfo info;
if (!file_util::GetFileInfo(path, &info)) {
params->load_error = base::PLATFORM_FILE_ERROR_NOT_FOUND;
return;
}
params->last_modified = info.last_modified;
if (!file_util::ReadFileToString(path, ¶ms->proto)) {
LOG(WARNING) << "Proto file not found at " << path.value();
params->load_error = base::PLATFORM_FILE_ERROR_NOT_FOUND;
return;
}
params->load_error = base::PLATFORM_FILE_OK;
}
// Loads json file content content from |file_path| on IO thread pool.
void LoadJsonFileOnIOThreadPool(
const FilePath& file_path,
base::PlatformFileError* error,
base::Value* result) {
scoped_ptr<base::Value> root_value;
std::string contents;
if (!file_util::ReadFileToString(file_path, &contents)) {
*error = base::PLATFORM_FILE_ERROR_NOT_FOUND;
return;
}
int unused_error_code = -1;
std::string unused_error_message;
root_value.reset(base::JSONReader::ReadAndReturnError(
contents, base::JSON_PARSE_RFC, &unused_error_code,
&unused_error_message));
bool has_root = root_value.get();
if (!has_root)
LOG(WARNING) << "Cached content read failed for file " << file_path.value();
if (!has_root) {
*error = base::PLATFORM_FILE_ERROR_FAILED;
return;
}
base::ListValue* result_list = NULL;
base::DictionaryValue* result_dict = NULL;
if (result->GetAsList(&result_list) &&
root_value->GetType() == Value::TYPE_LIST) {
*error = base::PLATFORM_FILE_OK;
result_list->Swap(reinterpret_cast<base::ListValue*>(root_value.get()));
} else if (result->GetAsDictionary(&result_dict) &&
root_value->GetType() == Value::TYPE_DICTIONARY) {
*error = base::PLATFORM_FILE_OK;
result_dict->Swap(
reinterpret_cast<base::DictionaryValue*>(root_value.get()));
} else {
*error = base::PLATFORM_FILE_ERROR_FAILED;
}
}
// Saves json file content content in |feed| to |file_pathname| on IO thread
// pool.
void SaveFeedOnIOThreadPool(
const FilePath& file_path,
scoped_ptr<base::Value> feed) {
std::string json;
#ifndef NDEBUG
base::JSONWriter::WriteWithOptions(feed.get(),
base::JSONWriter::OPTIONS_PRETTY_PRINT,
&json);
#else
base::JSONWriter::Write(feed.get(), &json);
#endif
int file_size = static_cast<int>(json.length());
if (file_util::WriteFile(file_path, json.data(), file_size) != file_size) {
LOG(WARNING) << "GData metadata file can't be stored at "
<< file_path.value();
if (!file_util::Delete(file_path, true)) {
LOG(WARNING) << "GData metadata file can't be deleted at "
<< file_path.value();
return;
}
}
}
// Reads properties of |local_file| and fills in values of UploadFileInfo.
// TODO(satorux,achuith): We should just get the file size in this function.
// The rest of the work can be done on UI/IO thread.
void CreateUploadFileInfoOnIOThreadPool(
const FilePath& local_file,
const FilePath& remote_dest_file,
base::PlatformFileError* error,
UploadFileInfo* upload_file_info) {
DCHECK(error);
DCHECK(upload_file_info);
int64 file_size = 0;
if (!file_util::GetFileSize(local_file, &file_size)) {
*error = base::PLATFORM_FILE_ERROR_NOT_FOUND;
return;
}
upload_file_info->file_path = local_file;
upload_file_info->file_size = file_size;
// Extract the final path from DownloadItem.
upload_file_info->gdata_path = remote_dest_file;
// Use the file name as the title.
upload_file_info->title = remote_dest_file.BaseName().value();
upload_file_info->content_length = file_size;
upload_file_info->all_bytes_present = true;
std::string mime_type;
if (!net::GetMimeTypeFromExtension(local_file.Extension(),
&upload_file_info->content_type)) {
upload_file_info->content_type= kMimeTypeOctetStream;
}
*error = base::PLATFORM_FILE_OK;
}
// Checks if a local file at |local_file_path| is a JSON file referencing a
// hosted document on IO thread poll, and if so, gets the resource ID of the
// document.
void GetDocumentResourceIdOnIOThreadPool(
const FilePath& local_file_path,
std::string* resource_id) {
DCHECK(resource_id);
if (DocumentEntry::HasHostedDocumentExtension(local_file_path)) {
std::string error;
DictionaryValue* dict_value = NULL;
JSONFileValueSerializer serializer(local_file_path);
scoped_ptr<Value> value(serializer.Deserialize(NULL, &error));
if (value.get() && value->GetAsDictionary(&dict_value))
dict_value->GetString("resource_id", resource_id);
}
}
// Creates a temporary JSON file representing a document with |edit_url|
// and |resource_id| under |document_dir| on IO thread pool.
void CreateDocumentJsonFileOnIOThreadPool(
const FilePath& document_dir,
const GURL& edit_url,
const std::string& resource_id,
base::PlatformFileError* error,
FilePath* temp_file_path,
std::string* mime_type,
GDataFileType* file_type) {
DCHECK(error);
DCHECK(temp_file_path);
DCHECK(mime_type);
DCHECK(file_type);
*error = base::PLATFORM_FILE_ERROR_FAILED;
if (file_util::CreateTemporaryFileInDir(document_dir, temp_file_path)) {
std::string document_content = base::StringPrintf(
"{\"url\": \"%s\", \"resource_id\": \"%s\"}",
edit_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 = base::PLATFORM_FILE_OK;
}
}
*mime_type = kMimeTypeJson;
*file_type = HOSTED_DOCUMENT;
if (*error != base::PLATFORM_FILE_OK)
temp_file_path->clear();
}
// Tests if we are allowed to create new directory in the provided directory.
bool ShouldCreateDirectory(const FilePath& directory_path) {
// We allow directory creation for paths that are on gdata file system
// (GDATA_SEARCH_PATH_INVALID) and paths that reference actual gdata file
// system path (GDATA_SEARCH_PATH_RESULT_CHILD).
util::GDataSearchPathType path_type =
util::GetSearchPathStatus(directory_path);
return path_type == util::GDATA_SEARCH_PATH_INVALID ||
path_type == util::GDATA_SEARCH_PATH_RESULT_CHILD;
}
// Copies a file from |src_file_path| to |dest_file_path| on the local
// file system using file_util::CopyFile. |error| is set to
// base::PLATFORM_FILE_OK on success or base::PLATFORM_FILE_ERROR_FAILED
// otherwise.
void CopyLocalFileOnIOThreadPool(
const FilePath& src_file_path,
const FilePath& dest_file_path,
base::PlatformFileError* error) {
DCHECK(error);
*error = file_util::CopyFile(src_file_path, dest_file_path) ?
base::PLATFORM_FILE_OK : base::PLATFORM_FILE_ERROR_FAILED;
}
// Relays the given FindEntryCallback to another thread via |replay_proxy|.
void RelayFindEntryCallback(scoped_refptr<base::MessageLoopProxy> relay_proxy,
const FindEntryCallback& callback,
base::PlatformFileError error,
const FilePath& directory_path,
GDataEntry* entry) {
relay_proxy->PostTask(FROM_HERE,
base::Bind(callback, error, directory_path, entry));
}
// Ditto for FileOperationCallback.
void RelayFileOperationCallback(
scoped_refptr<base::MessageLoopProxy> relay_proxy,
const FileOperationCallback& callback,
base::PlatformFileError error) {
relay_proxy->PostTask(FROM_HERE, base::Bind(callback, error));
}
// Ditto for GetFileCallback.
void RelayGetFileCallback(
scoped_refptr<base::MessageLoopProxy> relay_proxy,
const GetFileCallback& callback,
base::PlatformFileError error,
const FilePath& file_path,
const std::string& mime_type,
GDataFileType file_type) {
relay_proxy->PostTask(
FROM_HERE,
base::Bind(callback, error, file_path, mime_type, file_type));
}
// Ditto for GetDownloadDataCallback.
void RelayGetDownloadDataCallback(
scoped_refptr<base::MessageLoopProxy> relay_proxy,
const GetDownloadDataCallback& callback,
GDataErrorCode error,
scoped_ptr<std::string> download_data) {
// Unlike other callbacks, GetDownloadDataCallback is optional, hence it
// can be null here.
if (callback.is_null())
return;
relay_proxy->PostTask(
FROM_HERE,
base::Bind(callback, error, base::Passed(&download_data)));
}
// Ditto for GetCacheStateCallback.
void RelayGetCacheStateCallback(
scoped_refptr<base::MessageLoopProxy> relay_proxy,
const GetCacheStateCallback& callback,
base::PlatformFileError error,
int cache_state) {
relay_proxy->PostTask(FROM_HERE,
base::Bind(callback, error, cache_state));
}
// Ditto for GetAvailableSpaceCallback.
void RelayGetAvailableSpaceCallback(
scoped_refptr<base::MessageLoopProxy> relay_proxy,
const GetAvailableSpaceCallback& callback,
base::PlatformFileError error,
int64 bytes_total,
int64 bytes_used) {
relay_proxy->PostTask(FROM_HERE,
base::Bind(callback, error, bytes_total, bytes_used));
}
// Ditto for SetMountedStateCallback.
void RelaySetMountedStateCallback(
scoped_refptr<base::MessageLoopProxy> relay_proxy,
const SetMountedStateCallback& callback,
base::PlatformFileError error,
const FilePath& file_path) {
relay_proxy->PostTask(FROM_HERE,
base::Bind(callback, error, file_path));
}
// Ditto for GetEntryInfoCallback.
void RelayGetEntryInfoCallback(
scoped_refptr<base::MessageLoopProxy> relay_proxy,
const GetEntryInfoCallback& callback,
base::PlatformFileError error,
const FilePath& entry_path,
scoped_ptr<GDataEntryProto> entry_proto) {
relay_proxy->PostTask(
FROM_HERE,
base::Bind(callback, error, entry_path, base::Passed(&entry_proto)));
}
// Ditto for GetFileInfoCallback.
void RelayGetFileInfoCallback(
scoped_refptr<base::MessageLoopProxy> relay_proxy,
const GetFileInfoCallback& callback,
base::PlatformFileError error,
scoped_ptr<GDataFileProto> file_proto) {
relay_proxy->PostTask(
FROM_HERE,
base::Bind(callback, error, base::Passed(&file_proto)));
}
// Ditto for ReadDirectoryCallback.
void RelayReadDirectoryCallback(
scoped_refptr<base::MessageLoopProxy> relay_proxy,
const ReadDirectoryCallback& callback,
base::PlatformFileError error,
scoped_ptr<GDataDirectoryProto> directory_proto) {
relay_proxy->PostTask(
FROM_HERE,
base::Bind(callback, error, base::Passed(&directory_proto)));
}
} // namespace
// GDataFileProperties struct implementation.
GDataFileProperties::GDataFileProperties() : is_hosted_document(false) {
}
GDataFileProperties::~GDataFileProperties() {
}
// GDataFileSystem::GetDocumentsParams struct implementation.
GDataFileSystem::GetDocumentsParams::GetDocumentsParams(
int start_changestamp,
int root_feed_changestamp,
std::vector<DocumentFeed*>* feed_list,
bool should_fetch_multiple_feeds,
const FilePath& search_file_path,
const std::string& search_query,
const std::string& directory_resource_id,
const FindEntryCallback& callback)
: start_changestamp(start_changestamp),
root_feed_changestamp(root_feed_changestamp),
feed_list(feed_list),
should_fetch_multiple_feeds(should_fetch_multiple_feeds),
search_file_path(search_file_path),
search_query(search_query),
directory_resource_id(directory_resource_id),
callback(callback) {
}
GDataFileSystem::GetDocumentsParams::~GetDocumentsParams() {
STLDeleteElements(feed_list.get());
}
// GDataFileSystem::CreateDirectoryParams struct implementation.
GDataFileSystem::CreateDirectoryParams::CreateDirectoryParams(
const FilePath& created_directory_path,
const FilePath& target_directory_path,
bool is_exclusive,
bool is_recursive,
const FileOperationCallback& callback)
: created_directory_path(created_directory_path),
target_directory_path(target_directory_path),
is_exclusive(is_exclusive),
is_recursive(is_recursive),
callback(callback) {
}
GDataFileSystem::CreateDirectoryParams::~CreateDirectoryParams() {
}
//=================== GetFileFromCacheParams implementation ===================
GDataFileSystem::GetFileFromCacheParams::GetFileFromCacheParams(
const FilePath& virtual_file_path,
const FilePath& local_tmp_path,
const GURL& content_url,
const std::string& resource_id,
const std::string& md5,
const std::string& mime_type,
const GetFileCallback& get_file_callback,
const GetDownloadDataCallback& get_download_data_callback)
: virtual_file_path(virtual_file_path),
local_tmp_path(local_tmp_path),
content_url(content_url),
resource_id(resource_id),
md5(md5),
mime_type(mime_type),
get_file_callback(get_file_callback),
get_download_data_callback(get_download_data_callback) {
}
GDataFileSystem::GetFileFromCacheParams::~GetFileFromCacheParams() {
}
// GDataFileSystem class implementatsion.
GDataFileSystem::GDataFileSystem(Profile* profile,
DocumentsServiceInterface* documents_service)
: profile_(profile),
documents_service_(documents_service),
on_io_completed_(new base::WaitableEvent(
true /* manual reset */, true /* initially signaled */)),
cache_initialization_started_(false),
num_pending_tasks_(0),
update_timer_(true /* retain_user_task */, true /* is_repeating */),
hide_hosted_docs_(false),
ui_weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(
new base::WeakPtrFactory<GDataFileSystem>(this))),
ui_weak_ptr_(ui_weak_ptr_factory_->GetWeakPtr()),
sequence_token_(BrowserThread::GetBlockingPool()->GetSequenceToken()) {
// Should be created from the file browser extension API on UI thread.
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}
void GDataFileSystem::Initialize() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
FilePath cache_base_path;
chrome::GetUserCacheDirectory(profile_->GetPath(), &cache_base_path);
gdata_cache_path_ = cache_base_path.Append(chrome::kGDataCacheDirname);
gdata_cache_path_ = gdata_cache_path_.Append(kGDataCacheVersionDir);
SetCachePaths(gdata_cache_path_);
documents_service_->Initialize(profile_);
root_.reset(new GDataRootDirectory);
PrefService* pref_service = profile_->GetPrefs();
hide_hosted_docs_ = pref_service->GetBoolean(prefs::kDisableGDataHostedFiles);
InitializePreferenceObserver();
}
void GDataFileSystem::CheckForUpdates() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
base::AutoLock lock(lock_);
ContentOrigin initial_origin = root_->origin();
if (initial_origin == FROM_SERVER) {
root_->set_origin(REFRESHING);
ReloadFeedFromServerIfNeeded(initial_origin,
root_->largest_changestamp(),
root_->GetFilePath(),
base::Bind(&GDataFileSystem::OnUpdateChecked,
ui_weak_ptr_,
initial_origin));
}
}
void GDataFileSystem::OnUpdateChecked(ContentOrigin initial_origin,
base::PlatformFileError error,
const FilePath& /* directory_path */,
GDataEntry* /* entry */) {
if (error != base::PLATFORM_FILE_OK) {
base::AutoLock lock(lock_);
root_->set_origin(initial_origin);
}
}
bool GDataFileSystem::SetCacheRootPathForTesting(const FilePath& root_path) {
if (cache_initialization_started_)
return false;
cache_paths_.clear();
SetCachePaths(root_path);
return true;
}
GDataFileSystem::~GDataFileSystem() {
// This should be called from UI thread, from GDataSystemService shutdown.
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
pref_registrar_.reset(NULL);
// ui_weak_ptr_factory_ must be deleted on UI thread.
ui_weak_ptr_factory_.reset();
{
// http://crbug.com/125220
base::ThreadRestrictions::ScopedAllowWait allow_wait;
// We should wait if there is any pending tasks posted to the worker
// thread pool. on_io_completed_ won't be signaled iff |num_pending_tasks_|
// is greater that 0.
// We don't have to lock with |num_pending_tasks_lock_| here, since number
// of pending tasks can only decrease at this point (Number of pending class
// can be increased only on UI and IO thread. We are on UI thread, and there
// will be no more tasks run on IO thread.
on_io_completed_->Wait();
}
// Now that we are sure that there are no more pending tasks bound to this on
// other threads, we are safe to destroy the data members.
// Cancel all the in-flight operations.
// This asynchronously cancels the URL fetch operations.
documents_service_->CancelAll();
documents_service_.reset();
// Lock to let root destroy cache map and resource map.
base::AutoLock lock(lock_);
root_.reset(NULL);
// Let's make sure that num_pending_tasks_lock_ has been released on all
// other threads.
base::AutoLock tasks_lock(num_pending_tasks_lock_);
}
void GDataFileSystem::AddObserver(Observer* observer) {
observers_.AddObserver(observer);
}
void GDataFileSystem::RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
void GDataFileSystem::StartUpdates() {
DCHECK(!update_timer_.IsRunning());
update_timer_.Start(FROM_HERE,
base::TimeDelta::FromSeconds(
kGDataUpdateCheckIntervalInSec),
base::Bind(&GDataFileSystem::CheckForUpdates,
ui_weak_ptr_));
}
void GDataFileSystem::StopUpdates() {
DCHECK(update_timer_.IsRunning());
update_timer_.Stop();
}
void GDataFileSystem::Authenticate(const AuthStatusCallback& callback) {
// TokenFetcher, used in DocumentsService, must be run on UI thread.
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
documents_service_->Authenticate(callback);
}
void GDataFileSystem::FindEntryByResourceIdSync(
const std::string& resource_id,
FindEntryDelegate* delegate) {
base::AutoLock lock(lock_); // To access the cache map.
GDataFile* file = NULL;
GDataEntry* entry = root_->GetEntryByResourceId(resource_id);
if (entry)
file = entry->AsGDataFile();
if (file) {
delegate->OnDone(base::PLATFORM_FILE_OK, file->parent()->GetFilePath(),
file);
} else {
delegate->OnDone(base::PLATFORM_FILE_ERROR_NOT_FOUND, FilePath(), NULL);
}
}
void GDataFileSystem::FindEntryByPathAsyncOnUIThread(
const FilePath& search_file_path,
const FindEntryCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
base::AutoLock lock(lock_);
if (root_->origin() == INITIALIZING) {
// If root feed is not initialized but the initilization process has
// already started, add an observer to execute the remaining task after
// the end of the initialization.
AddObserver(new InitialLoadObserver(
this,
base::Bind(&GDataFileSystem::FindEntryByPathSyncOnUIThread,
ui_weak_ptr_,
search_file_path,
callback)));
return;
} else if (root_->origin() == UNINITIALIZED) {
// Load root feed from this disk cache. Upon completion, kick off server
// fetching.
root_->set_origin(INITIALIZING);
LoadRootFeedFromCache(true, // should_load_from_server
search_file_path,
callback);
return;
}
// Post a task to the same thread, rather than calling it here, as
// FindEntryByPathAsync() is asynchronous.
base::MessageLoopProxy::current()->PostTask(
FROM_HERE,
base::Bind(&GDataFileSystem::FindEntryByPathSyncOnUIThread,
ui_weak_ptr_,
search_file_path,
callback));
}
void GDataFileSystem::FindEntryByPathSyncOnUIThread(
const FilePath& search_file_path,
const FindEntryCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
base::AutoLock lock(lock_); // To access root_.
FindEntryCallbackRelayDelegate delegate(callback);
root_->FindEntryByPath(search_file_path, &delegate);
}
void GDataFileSystem::ReloadFeedFromServerIfNeeded(
ContentOrigin initial_origin,
int local_changestamp,
const FilePath& search_file_path,
const FindEntryCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// First fetch the latest changestamp to see if there were any new changes
// there at all.
documents_service_->GetAccountMetadata(
base::Bind(&GDataFileSystem::OnGetAccountMetadata,
ui_weak_ptr_,
initial_origin,
local_changestamp,
search_file_path,
callback));
}
void GDataFileSystem::OnGetAccountMetadata(
ContentOrigin initial_origin,
int local_changestamp,
const FilePath& search_file_path,
const FindEntryCallback& callback,
GDataErrorCode status,
scoped_ptr<base::Value> feed_data) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
base::PlatformFileError error = GDataToPlatformError(status);
if (error != base::PLATFORM_FILE_OK) {
// Get changes starting from the next changestamp from what we have locally.
LoadFeedFromServer(initial_origin,
local_changestamp + 1, 0,
true, /* should_fetch_multiple_feeds */
search_file_path,
std::string() /* no search query */,
std::string() /* no directory resource ID */,
callback,
base::Bind(&GDataFileSystem::OnFeedFromServerLoaded,
ui_weak_ptr_));
return;
}
scoped_ptr<AccountMetadataFeed> account_metadata;
if (feed_data.get())
account_metadata = AccountMetadataFeed::CreateFrom(*feed_data);
if (!account_metadata.get()) {
LoadFeedFromServer(initial_origin,
local_changestamp + 1, 0,
true, /* should_fetch_multiple_feeds */
search_file_path,
std::string() /* no search query */,
std::string() /* no directory resource ID */,
callback,
base::Bind(&GDataFileSystem::OnFeedFromServerLoaded,
ui_weak_ptr_));
return;
}
GDataSystemService* service =
GDataSystemServiceFactory::GetForProfile(profile_);
service->webapps_registry()->UpdateFromFeed(account_metadata.get());
bool changes_detected = true;
if (local_changestamp >= account_metadata->largest_changestamp()) {
if (local_changestamp > account_metadata->largest_changestamp()) {
LOG(WARNING) << "Cached client feed is fresher than server, client = "
<< local_changestamp
<< ", server = "
<< account_metadata->largest_changestamp();
}
{
base::AutoLock lock(lock_);
root_->set_origin(initial_origin);
root_->set_refresh_time(base::Time::Now());
}
changes_detected = false;
}
// No changes detected, continue with search as planned.
if (!changes_detected) {
if (!callback.is_null())
FindEntryByPathSyncOnUIThread(search_file_path, callback);
NotifyInitialLoadFinished();
return;
}
SaveFeed(feed_data.Pass(), FilePath(kAccountMetadataFile));
// Load changes from the server.
LoadFeedFromServer(initial_origin,
local_changestamp > 0 ? local_changestamp + 1 : 0,
account_metadata->largest_changestamp(),
true, /* should_fetch_multiple_feeds */
search_file_path,
std::string() /* no search query */,
std::string() /* no directory resource ID */,
callback,
base::Bind(&GDataFileSystem::OnFeedFromServerLoaded,
ui_weak_ptr_));
}
void GDataFileSystem::LoadFeedFromServer(
ContentOrigin initial_origin,
int start_changestamp,
int root_feed_changestamp,
bool should_fetch_multiple_feeds,
const FilePath& search_file_path,
const std::string& search_query,
const std::string& directory_resource_id,
const FindEntryCallback& entry_found_callback,
const LoadDocumentFeedCallback& feed_load_callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// ...then also kick off document feed fetching from the server as well.
// |feed_list| will contain the list of all collected feed updates that
// we will receive through calls of DocumentsService::GetDocuments().
scoped_ptr<std::vector<DocumentFeed*> > feed_list(
new std::vector<DocumentFeed*>);
// Kick off document feed fetching here if we don't have complete data
// to finish this call.
documents_service_->GetDocuments(
GURL(), // root feed start.
start_changestamp,
search_query,
directory_resource_id,
base::Bind(&GDataFileSystem::OnGetDocuments,
ui_weak_ptr_,
initial_origin,
feed_load_callback,
base::Owned(new GetDocumentsParams(start_changestamp,
root_feed_changestamp,
feed_list.release(),
should_fetch_multiple_feeds,
search_file_path,
search_query,
directory_resource_id,
entry_found_callback))));
}
void GDataFileSystem::OnFeedFromServerLoaded(GetDocumentsParams* params,
base::PlatformFileError error) {
if (error != base::PLATFORM_FILE_OK) {
if (!params->callback.is_null()) {
params->callback.Run(error, FilePath(),
reinterpret_cast<GDataEntry*>(NULL));
}
return;
}
error = UpdateFromFeed(*params->feed_list,
FROM_SERVER,
params->start_changestamp,
params->root_feed_changestamp);
if (error != base::PLATFORM_FILE_OK) {
if (!params->callback.is_null()) {
params->callback.Run(error, FilePath(),
reinterpret_cast<GDataEntry*>(NULL));
}
return;
}
// Save file system metadata to disk.
SaveFileSystemAsProto();
// If we had someone to report this too, then this retrieval was done in a
// context of search... so continue search.
if (!params->callback.is_null()) {
FindEntryByPathSyncOnUIThread(params->search_file_path, params->callback);
}
}
void GDataFileSystem::TransferFileFromRemoteToLocal(
const FilePath& remote_src_file_path,
const FilePath& local_dest_file_path,
const FileOperationCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
GetFileByPath(remote_src_file_path,
base::Bind(&GDataFileSystem::OnGetFileCompleteForTransferFile,
ui_weak_ptr_,
local_dest_file_path,
callback),
GetDownloadDataCallback());
}
void GDataFileSystem::TransferFileFromLocalToRemote(
const FilePath& local_src_file_path,
const FilePath& remote_dest_file_path,
const FileOperationCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
base::AutoLock lock(lock_);
// Make sure the destination directory exists
GDataEntry* dest_dir = GetGDataEntryByPath(
remote_dest_file_path.DirName());
if (!dest_dir || !dest_dir->AsGDataDirectory()) {
base::MessageLoopProxy::current()->PostTask(FROM_HERE,
base::Bind(callback, base::PLATFORM_FILE_ERROR_NOT_FOUND));
NOTREACHED();
return;
}
std::string* resource_id = new std::string;
PostBlockingPoolSequencedTaskAndReply(
FROM_HERE,
base::Bind(&GetDocumentResourceIdOnIOThreadPool,
local_src_file_path,
resource_id),
base::Bind(&GDataFileSystem::TransferFileForResourceId,
ui_weak_ptr_,
local_src_file_path,
remote_dest_file_path,
callback,
base::Owned(resource_id)));
}
void GDataFileSystem::TransferFileForResourceId(
const FilePath& local_file_path,
const FilePath& remote_dest_file_path,
const FileOperationCallback& callback,
std::string* resource_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(resource_id);
if (resource_id->empty()) {
// If |resource_id| is empty, upload the local file as a regular file.
TransferRegularFile(local_file_path, remote_dest_file_path, callback);
return;
}
// Otherwise, copy the document on the server side and add the new copy
// to the destination directory (collection).
CopyDocumentToDirectory(
remote_dest_file_path.DirName(),
*resource_id,
// Drop the document extension, which should not be
// in the document title.
remote_dest_file_path.BaseName().RemoveExtension().value(),
callback);
}
void GDataFileSystem::TransferRegularFile(
const FilePath& local_file_path,
const FilePath& remote_dest_file_path,
const FileOperationCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
base::PlatformFileError* error =
new base::PlatformFileError(base::PLATFORM_FILE_OK);
UploadFileInfo* upload_file_info = new UploadFileInfo;
PostBlockingPoolSequencedTaskAndReply(
FROM_HERE,
base::Bind(&CreateUploadFileInfoOnIOThreadPool,
local_file_path,
remote_dest_file_path,
error,
upload_file_info),
base::Bind(&GDataFileSystem::StartFileUploadOnUIThread,
ui_weak_ptr_,
callback,
error,
upload_file_info));
}
void GDataFileSystem::StartFileUploadOnUIThread(
const FileOperationCallback& callback,
base::PlatformFileError* error,
UploadFileInfo* upload_file_info) {
// This method needs to run on the UI thread as required by
// GDataUploader::UploadFile().
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(error);
DCHECK(upload_file_info);
GDataSystemService* service =
GDataSystemServiceFactory::GetForProfile(profile_);
if (*error == base::PLATFORM_FILE_OK) {
if (!service)
*error = base::PLATFORM_FILE_ERROR_FAILED;
}
if (*error != base::PLATFORM_FILE_OK) {
if (!callback.is_null())
callback.Run(*error);
return;
}
upload_file_info->completion_callback =
base::Bind(&GDataFileSystem::OnTransferCompleted,
ui_weak_ptr_,
callback);
service->uploader()->UploadFile(scoped_ptr<UploadFileInfo>(upload_file_info));
}
void GDataFileSystem::OnTransferCompleted(
const FileOperationCallback& callback,
base::PlatformFileError error,
UploadFileInfo* upload_file_info) {
DCHECK(upload_file_info);
if (error == base::PLATFORM_FILE_OK && upload_file_info->entry.get()) {
AddUploadedFile(upload_file_info->gdata_path.DirName(),
upload_file_info->entry.get(),
upload_file_info->file_path,
FILE_OPERATION_COPY);
}
if (!callback.is_null())
callback.Run(error);
// In case of error upload_file_info will be deleted by the uploader.
if (error != base::PLATFORM_FILE_OK)
return;
// TODO(achuith): GDataFileSystem should not have to call DeleteUpload.
GDataSystemService* service =
GDataSystemServiceFactory::GetForProfile(profile_);
if (service)
service->uploader()->DeleteUpload(upload_file_info);
}
void GDataFileSystem::Copy(const FilePath& src_file_path,
const FilePath& dest_file_path,
const FileOperationCallback& callback) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
const bool posted = BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&GDataFileSystem::CopyOnUIThread,
ui_weak_ptr_,
src_file_path,
dest_file_path,
base::Bind(&RelayFileOperationCallback,
base::MessageLoopProxy::current(),
callback)));
DCHECK(posted);
return;
}
CopyOnUIThread(src_file_path, dest_file_path, callback);
}
void GDataFileSystem::CopyOnUIThread(const FilePath& original_src_file_path,
const FilePath& original_dest_file_path,
const FileOperationCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
base::PlatformFileError error = base::PLATFORM_FILE_OK;
FilePath dest_parent_path = original_dest_file_path.DirName();
FilePath src_file_path;
FilePath dest_file_path;
std::string src_file_resource_id;
bool src_file_is_hosted_document = false;
{
base::AutoLock lock(lock_);
GDataEntry* src_entry = GetGDataEntryByPath(original_src_file_path);
GDataEntry* dest_parent = GetGDataEntryByPath(dest_parent_path);
if (!src_entry || !dest_parent) {
error = base::PLATFORM_FILE_ERROR_NOT_FOUND;
} else if (!dest_parent->AsGDataDirectory()) {
error = base::PLATFORM_FILE_ERROR_NOT_A_DIRECTORY;
} else if (!src_entry->AsGDataFile() || dest_parent->is_detached()) {
// TODO(benchan): Implement copy for directories. In the interim,
// we handle recursive directory copy in the file manager.
error = base::PLATFORM_FILE_ERROR_INVALID_OPERATION;
} else {
src_file_resource_id = src_entry->resource_id();
src_file_is_hosted_document =
src_entry->AsGDataFile()->is_hosted_document();
// |original_src_file_path| and |original_dest_file_path| don't have to
// necessary be equal to |src_entry|'s or |dest_entry|'s file path (e.g.
// paths used to display gdata content search results).
// That's why, instead of using |original_src_file_path| and
// |original_dest_file_path|, we will get file paths to use in copy
// operation from the entries.
src_file_path = src_entry->GetFilePath();
dest_parent_path = dest_parent->GetFilePath();
dest_file_path = dest_parent_path.Append(
original_dest_file_path.BaseName());
}
}
if (error != base::PLATFORM_FILE_OK) {
if (!callback.is_null())
MessageLoop::current()->PostTask(FROM_HERE, base::Bind(callback, error));
return;
}
DCHECK(!src_file_path.empty());
DCHECK(!dest_file_path.empty());
if (src_file_is_hosted_document) {
CopyDocumentToDirectory(dest_parent_path,
src_file_resource_id,
// Drop the document extension, which should not be
// in the document title.
dest_file_path.BaseName().RemoveExtension().value(),
callback);
return;
}
// TODO(benchan): Reimplement this once the server API supports
// copying of regular files directly on the server side.
GetFileByPath(src_file_path,
base::Bind(&GDataFileSystem::OnGetFileCompleteForCopy,
ui_weak_ptr_,
dest_file_path,
callback),
GetDownloadDataCallback());
}
void GDataFileSystem::OnGetFileCompleteForCopy(
const FilePath& remote_dest_file_path,
const FileOperationCallback& callback,
base::PlatformFileError error,
const FilePath& local_file_path,
const std::string& unused_mime_type,
GDataFileType file_type) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (error != base::PLATFORM_FILE_OK) {
if (!callback.is_null())
callback.Run(error);
return;
}
// This callback is only triggered for a regular file via Copy() and runs
// on the same thread as Copy (IO thread). As TransferRegularFile must run
// on the UI thread, we thus need to post a task to the UI thread.
// Also, upon the completion of TransferRegularFile, we need to run |callback|
// on the same thread as Copy (IO thread), and the transition from UI thread
// to IO thread is handled by OnTransferRegularFileCompleteForCopy.
DCHECK_EQ(REGULAR_FILE, file_type);
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&GDataFileSystem::TransferRegularFile,
ui_weak_ptr_,
local_file_path, remote_dest_file_path,
base::Bind(OnTransferRegularFileCompleteForCopy,
callback,
base::MessageLoopProxy::current())));
}
void GDataFileSystem::OnGetFileCompleteForTransferFile(
const FilePath& local_dest_file_path,
const FileOperationCallback& callback,
base::PlatformFileError error,
const FilePath& local_file_path,
const std::string& unused_mime_type,
GDataFileType file_type) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (error != base::PLATFORM_FILE_OK) {
if (!callback.is_null())
callback.Run(error);
return;
}
// GetFileByPath downloads the file from gdata to a local cache, which is then
// copied to the actual destination path on the local file system using
// CopyLocalFileOnIOThreadPool.
base::PlatformFileError* copy_file_error =
new base::PlatformFileError(base::PLATFORM_FILE_OK);
PostBlockingPoolSequencedTaskAndReply(
FROM_HERE,
base::Bind(&CopyLocalFileOnIOThreadPool,
local_file_path,
local_dest_file_path,
copy_file_error),
base::Bind(&RunFileOperationCallbackHelper,
callback,
base::Owned(copy_file_error)));
}
void GDataFileSystem::CopyDocumentToDirectory(
const FilePath& dir_path,
const std::string& resource_id,
const FilePath::StringType& new_name,
const FileOperationCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
FilePathUpdateCallback add_file_to_directory_callback =
base::Bind(&GDataFileSystem::AddEntryToDirectory,
ui_weak_ptr_,
dir_path,
callback);
documents_service_->CopyDocument(resource_id, new_name,
base::Bind(&GDataFileSystem::OnCopyDocumentCompleted,
ui_weak_ptr_,
add_file_to_directory_callback));
}
void GDataFileSystem::Rename(const FilePath& file_path,
const FilePath::StringType& new_name,
const FilePathUpdateCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// It is a no-op if the file is renamed to the same name.
if (file_path.BaseName().value() == new_name) {
if (!callback.is_null()) {
MessageLoop::current()->PostTask(
FROM_HERE, base::Bind(callback, base::PLATFORM_FILE_OK, file_path));
}
return;
}
base::AutoLock lock(lock_);
GDataEntry* entry = GetGDataEntryByPath(file_path);
if (!entry) {
if (!callback.is_null()) {
MessageLoop::current()->PostTask(FROM_HERE,
base::Bind(callback, base::PLATFORM_FILE_ERROR_NOT_FOUND, file_path));
}
return;
}
// Drop the .g<something> extension from |new_name| if the file being
// renamed is a hosted document and |new_name| has the same .g<something>
// extension as the file.
FilePath::StringType file_name = new_name;
if (entry->AsGDataFile() && entry->AsGDataFile()->is_hosted_document()) {
FilePath new_file(file_name);
if (new_file.Extension() == entry->AsGDataFile()->document_extension()) {
file_name = new_file.RemoveExtension().value();
}
}
documents_service_->RenameResource(
entry->edit_url(),
file_name,
base::Bind(&GDataFileSystem::OnRenameResourceCompleted,
ui_weak_ptr_,
file_path,
file_name,
callback));
}
void GDataFileSystem::Move(const FilePath& src_file_path,
const FilePath& dest_file_path,
const FileOperationCallback& callback) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
const bool posted = BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&GDataFileSystem::MoveOnUIThread,
ui_weak_ptr_,
src_file_path,
dest_file_path,
base::Bind(&RelayFileOperationCallback,
base::MessageLoopProxy::current(),
callback)));
DCHECK(posted);
return;
}
MoveOnUIThread(src_file_path, dest_file_path, callback);
}
void GDataFileSystem::MoveOnUIThread(const FilePath& original_src_file_path,
const FilePath& original_dest_file_path,
const FileOperationCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
base::PlatformFileError error = base::PLATFORM_FILE_OK;
FilePath dest_parent_path = original_dest_file_path.DirName();
FilePath src_file_path;
FilePath dest_file_path;
FilePath dest_name = original_dest_file_path.BaseName();
{
// This scoped lock needs to be released before calling Rename() below.
base::AutoLock lock(lock_);
GDataEntry* src_entry = GetGDataEntryByPath(original_src_file_path);
GDataEntry* dest_parent = GetGDataEntryByPath(dest_parent_path);
if (!src_entry || !dest_parent) {
error = base::PLATFORM_FILE_ERROR_NOT_FOUND;
} else if (!dest_parent->AsGDataDirectory()) {
error = base::PLATFORM_FILE_ERROR_NOT_A_DIRECTORY;
} else if (dest_parent->is_detached()) {
// We allow moving to a directory without file system root only if it's
// done as part of renaming (i.e. source and destination parent paths are
// the same).
if (original_src_file_path.DirName() != dest_parent_path) {
error = base::PLATFORM_FILE_ERROR_INVALID_OPERATION;
} else {
// If we are indeed renaming, we have to strip resource id from the file
// name.
std::string resource_id;
std::string file_name;
util::ParseSearchFileName(dest_name.value(), &resource_id, &file_name);
if (!file_name.empty())
dest_name = FilePath(file_name);
}
}
if (error != base::PLATFORM_FILE_OK) {
if (!callback.is_null()) {
MessageLoop::current()->PostTask(FROM_HERE,
base::Bind(callback, error));
}
return;
}
// |original_src_file_path| and |original_dest_file_path| don't have to
// necessary be equal to |src_entry|'s or |dest_entry|'s file path (e.g.
// paths used to display gdata content search results).
// That's why, instead of using |original_src_file_path| and
// |original_dest_file_path|, we will get file paths to use in move
// operation from the entries.
src_file_path = src_entry->GetFilePath();
if (!dest_parent->is_detached())
dest_parent_path = dest_parent->GetFilePath();
dest_file_path = dest_parent_path.Append(dest_name);
}
DCHECK(!src_file_path.empty());
DCHECK(!dest_file_path.empty());
// If the file/directory is moved to the same directory, just rename it.
if (original_src_file_path.DirName() == dest_parent_path) {
FilePathUpdateCallback final_file_path_update_callback =
base::Bind(&GDataFileSystem::OnFilePathUpdated,
ui_weak_ptr_,
callback);
Rename(original_src_file_path, dest_name.value(),
final_file_path_update_callback);
return;
}
// Otherwise, the move operation involves three steps:
// 1. Renames the file at |src_file_path| to basename(|dest_file_path|)
// within the same directory. The rename operation is a no-op if
// basename(|src_file_path|) equals to basename(|dest_file_path|).
// 2. Removes the file from its parent directory (the file is not deleted),
// which effectively moves the file to the root directory.
// 3. Adds the file to the parent directory of |dest_file_path|, which
// effectively moves the file from the root directory to the parent
// directory of |dest_file_path|.
FilePathUpdateCallback add_file_to_directory_callback =
base::Bind(&GDataFileSystem::AddEntryToDirectory,
ui_weak_ptr_,
dest_file_path.DirName(),
callback);
FilePathUpdateCallback remove_file_from_directory_callback =
base::Bind(&GDataFileSystem::RemoveEntryFromDirectory,
ui_weak_ptr_,
src_file_path.DirName(),
add_file_to_directory_callback);
Rename(src_file_path, dest_file_path.BaseName().value(),
remove_file_from_directory_callback);
}
void GDataFileSystem::AddEntryToDirectory(
const FilePath& dir_path,
const FileOperationCallback& callback,
base::PlatformFileError error,
const FilePath& file_path) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
base::AutoLock lock(lock_);
GDataEntry* entry = GetGDataEntryByPath(file_path);
GDataEntry* dir_entry = GetGDataEntryByPath(dir_path);
if (error == base::PLATFORM_FILE_OK) {
if (!entry || !dir_entry) {
error = base::PLATFORM_FILE_ERROR_NOT_FOUND;
} else {
if (!dir_entry->AsGDataDirectory())
error = base::PLATFORM_FILE_ERROR_NOT_A_DIRECTORY;
}
}
// Returns if there is an error or |dir_path| is the root directory.
if (error != base::PLATFORM_FILE_OK || dir_entry->AsGDataRootDirectory()) {
if (!callback.is_null())
MessageLoop::current()->PostTask(FROM_HERE, base::Bind(callback, error));
return;
}
documents_service_->AddResourceToDirectory(
dir_entry->content_url(),
entry->edit_url(),
base::Bind(&GDataFileSystem::OnAddEntryToDirectoryCompleted,
ui_weak_ptr_,
callback,
file_path,
dir_path));
}
void GDataFileSystem::RemoveEntryFromDirectory(
const FilePath& dir_path,
const FilePathUpdateCallback& callback,
base::PlatformFileError error,
const FilePath& file_path) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
base::AutoLock lock(lock_);
GDataEntry* entry = GetGDataEntryByPath(file_path);
GDataEntry* dir = GetGDataEntryByPath(dir_path);
if (error == base::PLATFORM_FILE_OK) {
if (!entry || !dir) {
error = base::PLATFORM_FILE_ERROR_NOT_FOUND;
} else {
if (!dir->AsGDataDirectory())
error = base::PLATFORM_FILE_ERROR_NOT_A_DIRECTORY;
}
}
// Returns if there is an error or |dir_path| is the root directory.
if (error != base::PLATFORM_FILE_OK || dir->AsGDataRootDirectory()) {
if (!callback.is_null()) {
MessageLoop::current()->PostTask(FROM_HERE,
base::Bind(callback, error, file_path));
}
return;
}
documents_service_->RemoveResourceFromDirectory(
dir->content_url(),
entry->edit_url(),
entry->resource_id(),
base::Bind(&GDataFileSystem::OnRemoveEntryFromDirectoryCompleted,
ui_weak_ptr_,
callback,
file_path,
dir_path));
}
void GDataFileSystem::Remove(const FilePath& file_path,
bool is_recursive,
const FileOperationCallback& callback) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
const bool posted = BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&GDataFileSystem::RemoveOnUIThread,
ui_weak_ptr_,
file_path,
is_recursive,
base::Bind(&RelayFileOperationCallback,
base::MessageLoopProxy::current(),
callback)));
DCHECK(posted);
return;
}
RemoveOnUIThread(file_path, is_recursive, callback);
}
void GDataFileSystem::RemoveOnUIThread(
const FilePath& file_path,
bool is_recursive,
const FileOperationCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
base::AutoLock lock(lock_);
GDataEntry* entry = GetGDataEntryByPath(file_path);
if (!entry) {
if (!callback.is_null()) {
MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(callback, base::PLATFORM_FILE_ERROR_NOT_FOUND));
}
return;
}
documents_service_->DeleteDocument(
entry->edit_url(),
base::Bind(&GDataFileSystem::OnRemovedDocument,
ui_weak_ptr_,
callback,
entry->GetFilePath()));
}
void GDataFileSystem::CreateDirectory(
const FilePath& directory_path,
bool is_exclusive,
bool is_recursive,
const FileOperationCallback& callback) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
const bool posted = BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&GDataFileSystem::CreateDirectoryOnUIThread,
ui_weak_ptr_,
directory_path,
is_exclusive,
is_recursive,
base::Bind(&RelayFileOperationCallback,
base::MessageLoopProxy::current(),
callback)));
DCHECK(posted);
return;
}
CreateDirectoryOnUIThread(
directory_path, is_exclusive, is_recursive, callback);
}
void GDataFileSystem::CreateDirectoryOnUIThread(
const FilePath& directory_path,
bool is_exclusive,
bool is_recursive,
const FileOperationCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!ShouldCreateDirectory(directory_path)) {
if (!callback.is_null()) {
MessageLoop::current()->PostTask(FROM_HERE,
base::Bind(callback, base::PLATFORM_FILE_ERROR_INVALID_OPERATION));
}
return;
}
FilePath last_parent_dir_path;
FilePath first_missing_path;
GURL last_parent_dir_url;
FindMissingDirectoryResult result =
FindFirstMissingParentDirectory(directory_path,
&last_parent_dir_url,
&first_missing_path);
switch (result) {
case FOUND_INVALID: {
if (!callback.is_null()) {
MessageLoop::current()->PostTask(FROM_HERE,
base::Bind(callback, base::PLATFORM_FILE_ERROR_NOT_FOUND));
}
return;
}
case DIRECTORY_ALREADY_PRESENT: {
if (!callback.is_null()) {
MessageLoop::current()->PostTask(FROM_HERE,
base::Bind(callback,
is_exclusive ? base::PLATFORM_FILE_ERROR_EXISTS :
base::PLATFORM_FILE_OK));
}
return;
}
case FOUND_MISSING: {
// There is a missing folder to be created here, move on with the rest of
// this function.
break;
}
default: {
NOTREACHED();
break;
}
}
// Do we have a parent directory here as well? We can't then create target
// directory if this is not a recursive operation.
if (directory_path != first_missing_path && !is_recursive) {
if (!callback.is_null()) {
MessageLoop::current()->PostTask(FROM_HERE,
base::Bind(callback, base::PLATFORM_FILE_ERROR_NOT_FOUND));
}
return;
}
documents_service_->CreateDirectory(
last_parent_dir_url,
first_missing_path.BaseName().value(),
base::Bind(&GDataFileSystem::OnCreateDirectoryCompleted,
ui_weak_ptr_,
CreateDirectoryParams(
first_missing_path,
directory_path,
is_exclusive,
is_recursive,
callback)));
}
void GDataFileSystem::GetFileByPath(
const FilePath& file_path,
const GetFileCallback& get_file_callback,
const GetDownloadDataCallback& get_download_data_callback) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
const bool posted = BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&GDataFileSystem::GetFileByPathOnUIThread,
ui_weak_ptr_,
file_path,
base::Bind(&RelayGetFileCallback,
base::MessageLoopProxy::current(),
get_file_callback),
base::Bind(&RelayGetDownloadDataCallback,
base::MessageLoopProxy::current(),
get_download_data_callback)));
DCHECK(posted);
return;
}
GetFileByPathOnUIThread(file_path, get_file_callback,
get_download_data_callback);
}
void GDataFileSystem::GetFileByPathOnUIThread(
const FilePath& file_path,
const GetFileCallback& get_file_callback,
const GetDownloadDataCallback& get_download_data_callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
GDataFileProperties file_properties;
if (!GetFileInfoByPath(file_path, &file_properties)) {
if (!get_file_callback.is_null()) {
MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(get_file_callback,
base::PLATFORM_FILE_ERROR_NOT_FOUND,
FilePath(),
std::string(),
REGULAR_FILE));
}
return;
}
// 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 (file_properties.is_hosted_document) {
InitializeCacheIfNecessary();
base::PlatformFileError* error =
new base::PlatformFileError(base::PLATFORM_FILE_OK);
FilePath* temp_file_path = new FilePath;
std::string* mime_type = new std::string;
GDataFileType* file_type = new GDataFileType(REGULAR_FILE);
PostBlockingPoolSequencedTaskAndReply(
FROM_HERE,
base::Bind(&CreateDocumentJsonFileOnIOThreadPool,
GetCacheDirectoryPath(
GDataRootDirectory::CACHE_TYPE_TMP_DOCUMENTS),
file_properties.alternate_url,
file_properties.resource_id,
error,
temp_file_path,
mime_type,
file_type),
base::Bind(&RunGetFileCallbackHelper,
get_file_callback,
base::Owned(error),
base::Owned(temp_file_path),
base::Owned(mime_type),
base::Owned(file_type)));
return;
}
// Returns absolute path of the file if it were cached or to be cached.
FilePath local_tmp_path = GetCacheFilePath(file_properties.resource_id,
file_properties.file_md5,
GDataRootDirectory::CACHE_TYPE_TMP,
CACHED_FILE_FROM_SERVER);
GetFileFromCacheByResourceIdAndMd5(
file_properties.resource_id,
file_properties.file_md5,
base::Bind(
&GDataFileSystem::OnGetFileFromCache,
ui_weak_ptr_,
GetFileFromCacheParams(file_path,
local_tmp_path,
file_properties.content_url,
file_properties.resource_id,
file_properties.file_md5,
file_properties.mime_type,
get_file_callback,
get_download_data_callback)));
}
void GDataFileSystem::GetFileByResourceId(
const std::string& resource_id,
const GetFileCallback& get_file_callback,
const GetDownloadDataCallback& get_download_data_callback) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
const bool posted = BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&GDataFileSystem::GetFileByResourceIdOnUIThread,
ui_weak_ptr_,
resource_id,
base::Bind(&RelayGetFileCallback,
base::MessageLoopProxy::current(),
get_file_callback),
base::Bind(&RelayGetDownloadDataCallback,
base::MessageLoopProxy::current(),
get_download_data_callback)));
DCHECK(posted);
return;
}
GetFileByResourceIdOnUIThread(resource_id, get_file_callback,
get_download_data_callback);
}
void GDataFileSystem::GetFileByResourceIdOnUIThread(
const std::string& resource_id,
const GetFileCallback& get_file_callback,
const GetDownloadDataCallback& get_download_data_callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
FilePath file_path;
{
base::AutoLock lock(lock_); // To access the cache map.
GDataEntry* entry = root_->GetEntryByResourceId(resource_id);
if (entry) {
GDataFile* file = entry->AsGDataFile();
if (file)
file_path = file->GetFilePath();
}
}
// Report an error immediately if the file for the resource ID is not
// found.
if (file_path.empty()) {
if (!get_file_callback.is_null()) {
base::MessageLoopProxy::current()->PostTask(
FROM_HERE,
base::Bind(get_file_callback,
base::PLATFORM_FILE_ERROR_NOT_FOUND,
FilePath(),
std::string(),
REGULAR_FILE));
}
return;
}
GetFileByPath(file_path, get_file_callback, get_download_data_callback);
}
void GDataFileSystem::OnGetFileFromCache(const GetFileFromCacheParams& params,
base::PlatformFileError error,
const std::string& resource_id,
const std::string& md5,
const FilePath& cache_file_path) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Have we found the file in cache? If so, return it back to the caller.
if (error == base::PLATFORM_FILE_OK) {
if (!params.get_file_callback.is_null()) {
params.get_file_callback.Run(error,
cache_file_path,
params.mime_type,
REGULAR_FILE);
}
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:
//
// 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
int64 file_size = 0;
{
base::AutoLock lock(lock_); // To access the root directory.
GDataEntry* entry = root_->GetEntryByResourceId(resource_id);
if (entry)
file_size = entry->file_info().size;
}
bool* has_enough_space = new bool(false);
PostBlockingPoolSequencedTaskAndReply(
FROM_HERE,
base::Bind(&GDataFileSystem::FreeDiskSpaceIfNeededFor,
base::Unretained(this),
file_size,
has_enough_space),
base::Bind(&GDataFileSystem::StartDownloadFileIfEnoughSpace,
ui_weak_ptr_,
params,
cache_file_path,
base::Owned(has_enough_space)));
}
void GDataFileSystem::FreeDiskSpaceIfNeededFor(int64 num_bytes,
bool* has_enough_space) {
// Do nothing and return if we have enough space.
*has_enough_space = HasEnoughSpaceFor(num_bytes);
if (*has_enough_space)
return;
// Otherwise, try to free up the disk space.
DVLOG(1) << "Freeing up disk space for " << num_bytes;
base::AutoLock lock(lock_); // To access the cache map.
// First remove temporary files from the cache map.
root_->RemoveTemporaryFilesFromCacheMap();
// Then remove all files under "tmp" directory.
RemoveAllFiles(GetCacheDirectoryPath(GDataRootDirectory::CACHE_TYPE_TMP));
// Check the disk space again.
*has_enough_space = HasEnoughSpaceFor(num_bytes);
}
void GDataFileSystem::FreeDiskSpaceIfNeeded(bool* has_enough_space) {
FreeDiskSpaceIfNeededFor(0, has_enough_space);
}
void GDataFileSystem::StartDownloadFileIfEnoughSpace(
const GetFileFromCacheParams& params,
const FilePath& cache_file_path,
bool* has_enough_space) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!*has_enough_space) {
// If no enough space, return PLATFORM_FILE_ERROR_NO_SPACE.
if (!params.get_file_callback.is_null()) {
params.get_file_callback.Run(base::PLATFORM_FILE_ERROR_NO_SPACE,
cache_file_path,
params.mime_type,
REGULAR_FILE);
}
return;
}
// We have enough disk space. Start downloading the file.
documents_service_->DownloadFile(
params.virtual_file_path,
params.local_tmp_path,
params.content_url,
base::Bind(&GDataFileSystem::OnFileDownloaded,
ui_weak_ptr_,
params),
params.get_download_data_callback);
}
void GDataFileSystem::SetCachePaths(const FilePath& root_path) {
DCHECK(cache_paths_.empty() && !cache_initialization_started_);
// Insert into |cache_paths_| in order defined in enum CacheSubDirectoryType.
cache_paths_.push_back(root_path.Append(kGDataCacheMetaDir));
cache_paths_.push_back(root_path.Append(kGDataCachePinnedDir));
cache_paths_.push_back(root_path.Append(kGDataCacheOutgoingDir));
cache_paths_.push_back(root_path.Append(kGDataCachePersistentDir));
cache_paths_.push_back(root_path.Append(kGDataCacheTmpDir));
cache_paths_.push_back(root_path.Append(kGDataCacheTmpDownloadsDir));
cache_paths_.push_back(root_path.Append(kGDataCacheTmpDocumentsDir));
}
void GDataFileSystem::InitiateUpload(
const std::string& file_name,
const std::string& content_type,
int64 content_length,
const FilePath& destination_directory,
const FilePath& virtual_path,
const InitiateUploadCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
GURL destination_directory_url =
GetUploadUrlForDirectory(destination_directory);
if (destination_directory_url.is_empty()) {
if (!callback.is_null()) {
MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(callback,
HTTP_BAD_REQUEST, GURL()));
}
return;
}
documents_service_->InitiateUpload(
InitiateUploadParams(file_name,
content_type,
content_length,
destination_directory_url,
virtual_path),
callback);
}
void GDataFileSystem::ResumeUpload(
const ResumeUploadParams& params,
const ResumeFileUploadCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
documents_service_->ResumeUpload(params, callback);
}
void GDataFileSystem::GetEntryInfoByPathAsync(
const FilePath& file_path,
const GetEntryInfoCallback& callback) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
const bool posted = BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&GDataFileSystem::GetEntryInfoByPathAsyncOnUIThread,
ui_weak_ptr_,
file_path,
base::Bind(&RelayGetEntryInfoCallback,
base::MessageLoopProxy::current(),
callback)));
DCHECK(posted);
return;
}
GetEntryInfoByPathAsyncOnUIThread(file_path, callback);
}
void GDataFileSystem::GetEntryInfoByPathAsyncOnUIThread(
const FilePath& file_path,
const GetEntryInfoCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
FindEntryByPathAsyncOnUIThread(
file_path,
base::Bind(&GDataFileSystem::OnGetEntryInfo,
ui_weak_ptr_,
callback));
}
void GDataFileSystem::OnGetEntryInfo(const GetEntryInfoCallback& callback,
base::PlatformFileError error,
const FilePath& directory_path,
GDataEntry* entry) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (error != base::PLATFORM_FILE_OK) {
if (!callback.is_null())
callback.Run(error, FilePath(), scoped_ptr<GDataEntryProto>());
return;
}
DCHECK(entry);
scoped_ptr<GDataEntryProto> entry_proto(new GDataEntryProto);
entry->ToProto(entry_proto.get());
if (!callback.is_null())
callback.Run(base::PLATFORM_FILE_OK,
entry->GetFilePath(),
entry_proto.Pass());
}
void GDataFileSystem::GetFileInfoByPathAsync(
const FilePath& file_path,
const GetFileInfoCallback& callback) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
const bool posted = BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&GDataFileSystem::GetFileInfoByPathAsyncOnUIThread,
ui_weak_ptr_,
file_path,
base::Bind(&RelayGetFileInfoCallback,
base::MessageLoopProxy::current(),
callback)));
DCHECK(posted);
return;
}
GetFileInfoByPathAsyncOnUIThread(file_path, callback);
}
void GDataFileSystem::GetFileInfoByPathAsyncOnUIThread(
const FilePath& file_path,
const GetFileInfoCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
FindEntryByPathAsyncOnUIThread(
file_path,
base::Bind(&GDataFileSystem::OnGetFileInfo,
ui_weak_ptr_,
callback));
}
void GDataFileSystem::OnGetFileInfo(const GetFileInfoCallback& callback,
base::PlatformFileError error,
const FilePath& directory_path,
GDataEntry* entry) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (error != base::PLATFORM_FILE_OK) {
if (!callback.is_null())
callback.Run(error, scoped_ptr<GDataFileProto>());
return;
}
DCHECK(entry);
GDataFile* file = entry->AsGDataFile();
if (!file) {
if (!callback.is_null())
callback.Run(base::PLATFORM_FILE_ERROR_NOT_FOUND,
scoped_ptr<GDataFileProto>());
return;
}
scoped_ptr<GDataFileProto> file_proto(new GDataFileProto);
file->ToProto(file_proto.get());
if (!callback.is_null())
callback.Run(base::PLATFORM_FILE_OK, file_proto.Pass());
}
void GDataFileSystem::ReadDirectoryByPathAsync(
const FilePath& file_path,
const ReadDirectoryCallback& callback) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
const bool posted = BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&GDataFileSystem::ReadDirectoryByPathAsyncOnUIThread,
ui_weak_ptr_,
file_path,
base::Bind(&RelayReadDirectoryCallback,
base::MessageLoopProxy::current(),
callback)));
DCHECK(posted);
return;
}
ReadDirectoryByPathAsyncOnUIThread(file_path, callback);
}
void GDataFileSystem::ReadDirectoryByPathAsyncOnUIThread(
const FilePath& file_path,
const ReadDirectoryCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
FindEntryByPathAsyncOnUIThread(
file_path,
base::Bind(&GDataFileSystem::OnReadDirectory,
ui_weak_ptr_,
callback));
}
void GDataFileSystem::OnReadDirectory(const ReadDirectoryCallback& callback,
base::PlatformFileError error,
const FilePath& directory_path,
GDataEntry* entry) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (error != base::PLATFORM_FILE_OK) {
if (!callback.is_null())
callback.Run(error, scoped_ptr<GDataDirectoryProto>());
return;
}
DCHECK(entry);
GDataDirectory* directory = entry->AsGDataDirectory();
if (!directory) {
if (!callback.is_null())
callback.Run(base::PLATFORM_FILE_ERROR_NOT_FOUND,
scoped_ptr<GDataDirectoryProto>());
return;
}
scoped_ptr<GDataDirectoryProto> directory_proto(new GDataDirectoryProto);
directory->ToProto(directory_proto.get());
if (!callback.is_null())
callback.Run(base::PLATFORM_FILE_OK, directory_proto.Pass());
}
void GDataFileSystem::RequestDirectoryRefresh(
const FilePath& file_path) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
const bool posted = BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&GDataFileSystem::RequestDirectoryRefreshOnUIThread,
ui_weak_ptr_,
file_path));
DCHECK(posted);
return;
}
RequestDirectoryRefreshOnUIThread(file_path);
}
void GDataFileSystem::RequestDirectoryRefreshOnUIThread(
const FilePath& file_path) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
base::AutoLock lock(lock_); // To use GetGDataEntryByPath() and root_.
GDataEntry* entry = GetGDataEntryByPath(file_path);
if (!entry || !entry->AsGDataDirectory()) {
LOG(ERROR) << "Directory entry not found: " << file_path.value();
return;
}
if (entry->resource_id().empty()) {
// This can happen if the directory is a virtual directory for search.
LOG(ERROR) << "Resource ID not found: " << file_path.value();
return;
}
LoadFeedFromServer(root_->origin(),
0, // Not delta feed.
0, // Not used.
true, // multiple feeds
file_path,
std::string(), // No search query
entry->resource_id(),
FindEntryCallback(), // Not used.
base::Bind(&GDataFileSystem::OnRequestDirectoryRefresh,
ui_weak_ptr_));
}
void GDataFileSystem::OnRequestDirectoryRefresh(
GetDocumentsParams* params,
base::PlatformFileError error) {
DCHECK(params);
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
const FilePath& directory_path = params->search_file_path;
if (error != base::PLATFORM_FILE_OK) {
LOG(ERROR) << "Failed to refresh directory: " << directory_path.value()
<< ": " << error;
return;
}
base::AutoLock lock(lock_); // To use FeedToFileResourceMap() and root_.
int unused_delta_feed_changestamp = 0;
int unused_num_regular_files = 0;
int unused_num_hosted_documents = 0;
FileResourceIdMap file_map;
error = FeedToFileResourceMap(*params->feed_list,
&file_map,
&unused_delta_feed_changestamp,
&unused_num_regular_files,
&unused_num_hosted_documents);
if (error != base::PLATFORM_FILE_OK) {
LOG(ERROR) << "Failed to convert feed: " << directory_path.value()
<< ": " << error;
return;
}
GDataEntry* directory_entry = root_->GetEntryByResourceId(
params->directory_resource_id);
if (!directory_entry || !directory_entry->AsGDataDirectory()) {
LOG(ERROR) << "Directory entry is gone: " << directory_path.value()
<< ": " << params->directory_resource_id;
return;
}
GDataDirectory* directory = directory_entry->AsGDataDirectory();
// Remove the existing files.
directory->RemoveChildFiles();
// Go through all entires generated by the feed and add files.
for (FileResourceIdMap::const_iterator it = file_map.begin();
it != file_map.end(); ++it) {
scoped_ptr<GDataEntry> entry(it->second);
// Skip if it's not a file (i.e. directory).
if (!entry->AsGDataFile())
continue;
directory->AddEntry(entry.release());
}
// Note that there may be no change in the directory, but it's expensive to
// check if the new metadata matches the existing one, so we just always
// notify that the directory is changed.
NotifyDirectoryChanged(directory_path);
DVLOG(1) << "Directory refreshed: " << directory_path.value();
}
bool GDataFileSystem::GetFileInfoByPath(
const FilePath& file_path, GDataFileProperties* properties) {
DCHECK(properties);
base::AutoLock lock(lock_);
GDataEntry* entry = GetGDataEntryByPath(file_path);
if (!entry)
return false;
properties->file_info = entry->file_info();
properties->resource_id = entry->resource_id();
GDataFile* regular_file = entry->AsGDataFile();
if (regular_file) {
properties->file_md5 = regular_file->file_md5();
properties->mime_type = regular_file->content_mime_type();
properties->content_url = regular_file->content_url();
properties->alternate_url = regular_file->alternate_url();
properties->is_hosted_document = regular_file->is_hosted_document();
}
return true;
}
GDataEntry* GDataFileSystem::GetGDataEntryByPath(
const FilePath& file_path) {
lock_.AssertAcquired();
// Find directory element within the cached file system snapshot.
ReadOnlyFindEntryDelegate find_delegate;
root_->FindEntryByPath(file_path, &find_delegate);
return find_delegate.entry();
}
void GDataFileSystem::GetCacheState(const std::string& resource_id,
const std::string& md5,
const GetCacheStateCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI) ||
BrowserThread::CurrentlyOn(BrowserThread::IO));
// Always post a task to the UI thread to call GetCacheStateOnUIThread even if
// GetCacheState is called on the UI thread. This ensures that, regardless of
// whether GDataFileSystem is locked or not, GDataFileSystem is unlocked when
// GetCacheStateOnUIThread is called.
const bool posted = BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&GDataFileSystem::GetCacheStateOnUIThread,
ui_weak_ptr_,
resource_id,
md5,
base::Bind(&RelayGetCacheStateCallback,
base::MessageLoopProxy::current(),
callback)));
DCHECK(posted);
}
void GDataFileSystem::GetCacheStateOnUIThread(
const std::string& resource_id,
const std::string& md5,
const GetCacheStateCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
InitializeCacheIfNecessary();
base::PlatformFileError* error =
new base::PlatformFileError(base::PLATFORM_FILE_OK);
int* cache_state = new int(GDataFile::CACHE_STATE_NONE);
// GetCacheStateOnIOThreadPool won't do file IO, but post it to the thread
// pool, as it must be performed after the cache is initialized.
PostBlockingPoolSequencedTaskAndReply(
FROM_HERE,
base::Bind(&GDataFileSystem::GetCacheStateOnIOThreadPool,
base::Unretained(this),
resource_id,
md5,
error,
cache_state),
base::Bind(&RunGetCacheStateCallbackHelper,
callback,
base::Owned(error),
base::Owned(cache_state)));
}
void GDataFileSystem::GetAvailableSpace(
const GetAvailableSpaceCallback& callback) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
const bool posted = BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&GDataFileSystem::GetAvailableSpaceOnUIThread,
ui_weak_ptr_,
base::Bind(&RelayGetAvailableSpaceCallback,
base::MessageLoopProxy::current(),
callback)));
DCHECK(posted);
return;
}
GetAvailableSpaceOnUIThread(callback);
}
void GDataFileSystem::GetAvailableSpaceOnUIThread(
const GetAvailableSpaceCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
documents_service_->GetAccountMetadata(
base::Bind(&GDataFileSystem::OnGetAvailableSpace,
ui_weak_ptr_,
callback));
}
void GDataFileSystem::SetPinState(const FilePath& file_path,
bool to_pin,
const FileOperationCallback& callback) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
const bool posted = BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&GDataFileSystem::SetPinStateOnUIThread,
ui_weak_ptr_,
file_path,
to_pin,
base::Bind(&RelayFileOperationCallback,
base::MessageLoopProxy::current(),
callback)));
DCHECK(posted);
return;
}
SetPinStateOnUIThread(file_path, to_pin, callback);
}
void GDataFileSystem::SetPinStateOnUIThread(
const FilePath& file_path,
bool to_pin,
const FileOperationCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
std::string resource_id, md5;
{
base::AutoLock lock(lock_);
GDataEntry* entry = GetGDataEntryByPath(file_path);
GDataFile* file = entry ? entry->AsGDataFile() : NULL;
if (!file) {
if (!callback.is_null()) {
MessageLoop::current()->PostTask(FROM_HERE, base::Bind(callback,
base::PLATFORM_FILE_ERROR_NOT_FOUND));
}
return;
}
resource_id = file->resource_id();
md5 = file->file_md5();
}
CacheOperationCallback cache_callback;
if (!callback.is_null()) {
cache_callback = base::Bind(&GDataFileSystem::OnSetPinStateCompleted,
ui_weak_ptr_,
callback);
}
if (to_pin)
Pin(resource_id, md5, cache_callback);
else
Unpin(resource_id, md5, cache_callback);
}
void GDataFileSystem::SetMountedState(const FilePath& file_path,
bool to_mount,
const SetMountedStateCallback& callback) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
const bool posted = BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&GDataFileSystem::SetMountedStateOnUIThread,
ui_weak_ptr_,
file_path,
to_mount,
base::Bind(&RelaySetMountedStateCallback,
base::MessageLoopProxy::current(),
callback)));
DCHECK(posted);
return;
}
SetMountedStateOnUIThread(file_path, to_mount, callback);
}
void GDataFileSystem::SetMountedStateOnUIThread(
const FilePath& file_path,
bool to_mount,
const SetMountedStateCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
InitializeCacheIfNecessary();
base::PlatformFileError* error =
new base::PlatformFileError(base::PLATFORM_FILE_OK);
FilePath* cache_file_path = new FilePath;
PostBlockingPoolSequencedTaskAndReply(
FROM_HERE,
base::Bind(&GDataFileSystem::SetMountedStateOnIOThreadPool,
base::Unretained(this),
file_path,
to_mount,
error,
cache_file_path),
base::Bind(&RunSetMountedStateCallbackHelper,
callback,
base::Owned(error),
base::Owned(cache_file_path)));
}
void GDataFileSystem::SetMountedStateOnIOThreadPool(
const FilePath& file_path,
bool to_mount,
base::PlatformFileError *error,
FilePath* cache_file_path) {
DCHECK(error);
DCHECK(cache_file_path);
// Lock to access cache map.
base::AutoLock lock(lock_);
// Parse file path to obtain resource_id, md5 and extra_extension.
std::string resource_id;
std::string md5;
std::string extra_extension;
util::ParseCacheFilePath(file_path, &resource_id, &md5, &extra_extension);
// The extra_extension shall be ".mounted" iff we're unmounting.
DCHECK(!to_mount == (extra_extension == kMountedArchiveFileExtension));
// Get cache entry associated with the resource_id and md5
GDataRootDirectory::CacheEntry* entry = root_->GetCacheEntry(resource_id,
md5);
if (!entry) {
*error = base::PLATFORM_FILE_ERROR_NOT_FOUND;
return;
}
if (to_mount == entry->IsMounted()) {
*error = base::PLATFORM_FILE_ERROR_INVALID_OPERATION;
return;
}
// Get the subdir type and path for the unmounted state.
GDataRootDirectory::CacheSubDirectoryType unmounted_subdir =
entry->IsPinned() ? GDataRootDirectory::CACHE_TYPE_PERSISTENT :
GDataRootDirectory::CACHE_TYPE_TMP;
FilePath unmounted_path = GetCacheFilePath(resource_id, md5, unmounted_subdir,
CACHED_FILE_FROM_SERVER);
// Get the subdir type and path for the mounted state.
GDataRootDirectory::CacheSubDirectoryType mounted_subdir =
GDataRootDirectory::CACHE_TYPE_PERSISTENT;
FilePath mounted_path = GetCacheFilePath(resource_id, md5, mounted_subdir,
CACHED_FILE_MOUNTED);
// Determine the source and destination paths for moving the cache blob.
FilePath source_path;
GDataRootDirectory::CacheSubDirectoryType dest_subdir;
int cache_state = entry->cache_state;
if (to_mount) {
source_path = unmounted_path;
*cache_file_path = mounted_path;
dest_subdir = mounted_subdir;
cache_state = GDataFile::SetCacheMounted(cache_state);
} else {
source_path = mounted_path;
*cache_file_path = unmounted_path;
dest_subdir = unmounted_subdir;
cache_state = GDataFile::ClearCacheMounted(cache_state);
}
// Move cache blob from source path to destination path.
*error = ModifyCacheState(source_path, *cache_file_path,
GDataFileSystem::FILE_OPERATION_MOVE,
FilePath(), false);
if (*error == base::PLATFORM_FILE_OK) {
// Now that cache operation is complete, update cache map
root_->UpdateCacheMap(resource_id, md5, dest_subdir, cache_state);
}
}
void GDataFileSystem::OnSetPinStateCompleted(
const FileOperationCallback& callback,
base::PlatformFileError error,
const std::string& resource_id,
const std::string& md5) {
callback.Run(error);
}
void GDataFileSystem::OnGetAvailableSpace(
const GetAvailableSpaceCallback& callback,
GDataErrorCode status,
scoped_ptr<base::Value> data) {
base::PlatformFileError error = GDataToPlatformError(status);
if (error != base::PLATFORM_FILE_OK) {
callback.Run(error, -1, -1);
return;
}
scoped_ptr<AccountMetadataFeed> feed;
if (data.get())
feed = AccountMetadataFeed::CreateFrom(*data);
if (!feed.get()) {
callback.Run(base::PLATFORM_FILE_ERROR_FAILED, -1, -1);
return;
}
SaveFeed(data.Pass(), FilePath(kAccountMetadataFile));
callback.Run(base::PLATFORM_FILE_OK,
feed->quota_bytes_total(),
feed->quota_bytes_used());
}
GDataOperationRegistry* GDataFileSystem::GetOperationRegistry() {
return documents_service_->operation_registry();
}
void GDataFileSystem::OnCreateDirectoryCompleted(
const CreateDirectoryParams& params,
GDataErrorCode status,
scoped_ptr<base::Value> data) {
base::PlatformFileError error = GDataToPlatformError(status);
if (error != base::PLATFORM_FILE_OK) {
if (!params.callback.is_null())
params.callback.Run(error);
return;
}
base::DictionaryValue* dict_value = NULL;
base::Value* created_entry = NULL;
if (data.get() && data->GetAsDictionary(&dict_value) && dict_value)
dict_value->Get("entry", &created_entry);
error = AddNewDirectory(params.created_directory_path.DirName(),
created_entry);
if (error != base::PLATFORM_FILE_OK) {
if (!params.callback.is_null())
params.callback.Run(error);
return;
}
// Not done yet with recursive directory creation?
if (params.target_directory_path != params.created_directory_path &&
params.is_recursive) {
CreateDirectory(params.target_directory_path,
params.is_exclusive,
params.is_recursive,
params.callback);
return;
}
if (!params.callback.is_null()) {
// Finally done with the create request.
params.callback.Run(base::PLATFORM_FILE_OK);
}
}
void GDataFileSystem::OnSearch(const ReadDirectoryCallback& callback,
GetDocumentsParams* params,
base::PlatformFileError error) {
// 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.
scoped_ptr<GDataDirectory> search_dir(new GDataDirectory(NULL, NULL));
base::AutoLock lock(lock_);
int delta_feed_changestamp = 0;
int num_regular_files = 0;
int num_hosted_documents = 0;
FileResourceIdMap file_map;
if (error == base::PLATFORM_FILE_OK) {
error = FeedToFileResourceMap(*params->feed_list,
&file_map,
&delta_feed_changestamp,
&num_regular_files,
&num_hosted_documents);
}
if (error == base::PLATFORM_FILE_OK) {
std::set<FilePath> ignored;
// Go through all entires generated by the feed and add them to the search
// result directory.
for (FileResourceIdMap::const_iterator it = file_map.begin();
it != file_map.end(); ++it) {
scoped_ptr<GDataEntry> entry(it->second);
DCHECK_EQ(it->first, entry->resource_id());
DCHECK(!entry->is_deleted());
entry->set_title(entry->resource_id() + "." + entry->title());
search_dir->AddEntry(entry.release());
}
}
scoped_ptr<GDataDirectoryProto> directory_proto(new GDataDirectoryProto);
search_dir->ToProto(directory_proto.get());
if (!callback.is_null()) {
callback.Run(error, directory_proto.Pass());
}
}
void GDataFileSystem::SearchAsync(const std::string& search_query,
const ReadDirectoryCallback& callback) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
const bool posted = BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&GDataFileSystem::SearchAsyncOnUIThread,
ui_weak_ptr_,
search_query,
base::Bind(&RelayReadDirectoryCallback,
base::MessageLoopProxy::current(),
callback)));
DCHECK(posted);
return;
}
SearchAsyncOnUIThread(search_query, callback);
}
void GDataFileSystem::SearchAsyncOnUIThread(
const std::string& search_query,
const ReadDirectoryCallback& callback) {
scoped_ptr<std::vector<DocumentFeed*> > feed_list(
new std::vector<DocumentFeed*>);
base::AutoLock lock(lock_);
ContentOrigin initial_origin = root_->origin();
LoadFeedFromServer(initial_origin,
0, 0, // We don't use change stamps when fetching search
// data; we always fetch the whole result feed.
false, // Stop fetching search results after first feed
// chunk to avoid displaying huge number of search
// results (especially since we don't cache them).
FilePath(), // Not used.
search_query,
std::string(), // No directory resource ID.
FindEntryCallback(), // Not used.
base::Bind(&GDataFileSystem::OnSearch,
ui_weak_ptr_, callback));
}
void GDataFileSystem::OnGetDocuments(ContentOrigin initial_origin,
const LoadDocumentFeedCallback& callback,
GetDocumentsParams* params,
GDataErrorCode status,
scoped_ptr<base::Value> data) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
base::PlatformFileError error = GDataToPlatformError(status);
if (error == base::PLATFORM_FILE_OK &&
(!data.get() || data->GetType() != Value::TYPE_DICTIONARY)) {
error = base::PLATFORM_FILE_ERROR_FAILED;
}
if (error != base::PLATFORM_FILE_OK) {
{
base::AutoLock lock(lock_);
root_->set_origin(initial_origin);
}
if (!callback.is_null()) {
callback.Run(params, error);
}
return;
}
// TODO(zelidrag): Find a faster way to get next url rather than parsing
// the entire feed.
GURL next_feed_url;
scoped_ptr<DocumentFeed> current_feed(DocumentFeed::ExtractAndParse(*data));
if (!current_feed.get()) {
if (!callback.is_null()) {
callback.Run(params, base::PLATFORM_FILE_ERROR_FAILED);
}
return;
}
const bool has_next_feed_url = current_feed->GetNextFeedURL(&next_feed_url);
#ifndef NDEBUG
// Save initial root feed for analysis.
std::string file_name =
base::StringPrintf("DEBUG_feed_%d.json",
params->start_changestamp);
SaveFeed(data.Pass(), FilePath(file_name));
#endif
// Add the current feed to the list of collected feeds for this directory.
params->feed_list->push_back(current_feed.release());
// Compute and notify the number of entries fetched so far.
int num_accumulated_entries = 0;
for (size_t i = 0; i < params->feed_list->size(); ++i)
num_accumulated_entries += params->feed_list->at(i)->entries().size();
NotifyDocumentFeedFetched(num_accumulated_entries);
// Check if we need to collect more data to complete the directory list.
if (params->should_fetch_multiple_feeds && has_next_feed_url &&
!next_feed_url.is_empty()) {
// Kick of the remaining part of the feeds.
documents_service_->GetDocuments(
next_feed_url,
params->start_changestamp,
params->search_query,
params->directory_resource_id,
base::Bind(&GDataFileSystem::OnGetDocuments,
ui_weak_ptr_,
initial_origin,
callback,
base::Owned(
new GetDocumentsParams(
params->start_changestamp,
params->root_feed_changestamp,
params->feed_list.release(),
params->should_fetch_multiple_feeds,
params->search_file_path,
params->search_query,
params->directory_resource_id,
params->callback))));
return;
}
if (!callback.is_null())
callback.Run(params, error);
}
void GDataFileSystem::LoadRootFeedFromCache(
bool should_load_from_server,
const FilePath& search_file_path,
const FindEntryCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
const FilePath path =
GetCacheDirectoryPath(GDataRootDirectory::CACHE_TYPE_META).Append(
kFilesystemProtoFile);
LoadRootFeedParams* params = new LoadRootFeedParams(search_file_path,
should_load_from_server,
callback);
BrowserThread::GetBlockingPool()->PostTaskAndReply(FROM_HERE,
base::Bind(&LoadProtoOnIOThreadPool, path, params),
base::Bind(&GDataFileSystem::OnProtoLoaded,
ui_weak_ptr_,
base::Owned(params)));
}
void GDataFileSystem::OnProtoLoaded(LoadRootFeedParams* params) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
{
base::AutoLock lock(lock_);
// If we have already received updates from the server, bail out.
if (root_->origin() == FROM_SERVER)
return;
}
int local_changestamp = 0;
// Update directory structure only if everything is OK and we haven't yet
// received the feed from the server yet.
if (params->load_error == base::PLATFORM_FILE_OK) {
DVLOG(1) << "ParseFromString";
base::AutoLock lock(lock_); // To access root_.
if (root_->ParseFromString(params->proto)) {
root_->set_last_serialized(params->last_modified);
root_->set_serialized_size(params->proto.size());
NotifyInitialLoadFinished();
local_changestamp = root_->largest_changestamp();
} else {
params->load_error = base::PLATFORM_FILE_ERROR_FAILED;
LOG(WARNING) << "Parse of cached proto file failed";
}
}
FindEntryCallback callback = params->callback;
// If we got feed content from cache, try search over it.
if (!params->should_load_from_server ||
(params->load_error == base::PLATFORM_FILE_OK && !callback.is_null())) {
// Continue file content search operation if the delegate hasn't terminated
// this search branch already.
FindEntryByPathSyncOnUIThread(params->search_file_path, callback);
callback.Reset();
}
if (!params->should_load_from_server)
return;
// Decide the |initial_origin| to pass to ReloadFeedFromServerIfNeeded().
// This is used to restore directory content origin to its initial value when
// we fail to retrieve the feed from server.
// By default, if directory content is not yet initialized, restore content
// origin to UNINITIALIZED in case of failure.
ContentOrigin initial_origin = UNINITIALIZED;
{
base::AutoLock lock(lock_);
if (root_->origin() != INITIALIZING) {
// If directory content is already initialized, restore content origin
// to FROM_CACHE in case of failure.
initial_origin = FROM_CACHE;
root_->set_origin(REFRESHING);
}
}
// Kick of the retrieval of the feed from server. If we have previously
// |reported| to the original callback, then we just need to refresh the
// content without continuing search upon operation completion.
ReloadFeedFromServerIfNeeded(initial_origin,
local_changestamp,
params->search_file_path,
callback);
}
void GDataFileSystem::SaveFileSystemAsProto() {
DVLOG(1) << "SaveFileSystemAsProto";
base::AutoLock lock(lock_); // To access root_.
if (!ShouldSerializeFileSystemNow(root_->serialized_size(),
root_->last_serialized())) {
return;
}
const FilePath path =
GetCacheDirectoryPath(GDataRootDirectory::CACHE_TYPE_META).Append(
kFilesystemProtoFile);
scoped_ptr<std::string> serialized_proto(new std::string());
root_->SerializeToString(serialized_proto.get());
root_->set_last_serialized(base::Time::Now());
root_->set_serialized_size(serialized_proto->size());
PostBlockingPoolSequencedTask(
FROM_HERE,
base::Bind(&SaveProtoOnIOThreadPool, path,
base::Passed(serialized_proto.Pass())));
}
void GDataFileSystem::OnFilePathUpdated(const FileOperationCallback& callback,
base::PlatformFileError error,
const FilePath& file_path) {
if (!callback.is_null())
callback.Run(error);
}
void GDataFileSystem::OnRenameResourceCompleted(
const FilePath& file_path,
const FilePath::StringType& new_name,
const FilePathUpdateCallback& callback,
GDataErrorCode status,
const GURL& document_url) {
FilePath updated_file_path;
base::PlatformFileError error = GDataToPlatformError(status);
if (error == base::PLATFORM_FILE_OK)
error = RenameFileOnFilesystem(file_path, new_name, &updated_file_path);
if (!callback.is_null())
callback.Run(error, updated_file_path);
}
void GDataFileSystem::OnCopyDocumentCompleted(
const FilePathUpdateCallback& callback,
GDataErrorCode status,
scoped_ptr<base::Value> data) {
base::PlatformFileError error = GDataToPlatformError(status);
if (error != base::PLATFORM_FILE_OK) {
if (!callback.is_null())
callback.Run(error, FilePath());
return;
}
base::DictionaryValue* dict_value = NULL;
base::Value* entry_value = NULL;
if (data.get() && data->GetAsDictionary(&dict_value) && dict_value)
dict_value->Get("entry", &entry_value);
if (!entry_value) {
if (!callback.is_null())
callback.Run(base::PLATFORM_FILE_ERROR_FAILED, FilePath());
return;
}
scoped_ptr<DocumentEntry> doc_entry(DocumentEntry::CreateFrom(entry_value));
if (!doc_entry.get()) {
if (!callback.is_null())
callback.Run(base::PLATFORM_FILE_ERROR_FAILED, FilePath());
return;
}
FilePath file_path;
{
base::AutoLock lock(lock_);
GDataEntry* entry =
GDataEntry::FromDocumentEntry(
root_.get(), doc_entry.get(), root_.get());
if (!entry) {
if (!callback.is_null())
callback.Run(base::PLATFORM_FILE_ERROR_FAILED, FilePath());
return;
}
root_->AddEntry(entry);
file_path = entry->GetFilePath();
}
NotifyDirectoryChanged(file_path.DirName());
if (!callback.is_null())
callback.Run(error, file_path);
}
void GDataFileSystem::OnAddEntryToDirectoryCompleted(
const FileOperationCallback& callback,
const FilePath& file_path,
const FilePath& dir_path,
GDataErrorCode status,
const GURL& document_url) {
base::PlatformFileError error = GDataToPlatformError(status);
if (error == base::PLATFORM_FILE_OK)
error = AddEntryToDirectoryOnFilesystem(file_path, dir_path);
if (!callback.is_null())
callback.Run(error);
}
void GDataFileSystem::OnRemoveEntryFromDirectoryCompleted(
const FilePathUpdateCallback& callback,
const FilePath& file_path,
const FilePath& dir_path,
GDataErrorCode status,
const GURL& document_url) {
FilePath updated_file_path = file_path;
base::PlatformFileError error = GDataToPlatformError(status);
if (error == base::PLATFORM_FILE_OK)
error = RemoveEntryFromDirectoryOnFilesystem(file_path, dir_path,
&updated_file_path);
if (!callback.is_null())
callback.Run(error, updated_file_path);
}
void GDataFileSystem::SaveFeed(scoped_ptr<base::Value> feed,
const FilePath& name) {
InitializeCacheIfNecessary();
PostBlockingPoolSequencedTask(
FROM_HERE,
base::Bind(&SaveFeedOnIOThreadPool,
GetCacheDirectoryPath(
GDataRootDirectory::CACHE_TYPE_META).Append(name),
base::Passed(&feed)));
}
void GDataFileSystem::OnRemovedDocument(
const FileOperationCallback& callback,
const FilePath& file_path,
GDataErrorCode status,
const GURL& document_url) {
base::PlatformFileError error = GDataToPlatformError(status);
if (error == base::PLATFORM_FILE_OK)
error = RemoveEntryFromFileSystem(file_path);
if (!callback.is_null()) {
callback.Run(error);
}
}
void GDataFileSystem::OnFileDownloaded(
const GetFileFromCacheParams& params,
GDataErrorCode status,
const GURL& content_url,
const FilePath& downloaded_file_path) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// At this point, the disk can be full or nearly full for several reasons:
// - The expected file size was incorrect and the file was larger
// - There was an in-flight download operation and it used up space
// - The disk became full for some user actions we cannot control
// (ex. the user might have downloaded a large file from a regular web site)
//
// If we don't have enough space, we return PLATFORM_FILE_ERROR_NO_SPACE,
// and try to free up space, even if the file was downloaded successfully.
bool* has_enough_space = new bool(false);
PostBlockingPoolSequencedTaskAndReply(
FROM_HERE,
base::Bind(&GDataFileSystem::FreeDiskSpaceIfNeeded,
base::Unretained(this),
has_enough_space),
base::Bind(&GDataFileSystem::OnFileDownloadedAndSpaceChecked,
ui_weak_ptr_,
params,
status,
content_url,
downloaded_file_path,
base::Owned(has_enough_space)));
}
void GDataFileSystem::OnFileDownloadedAndSpaceChecked(
const GetFileFromCacheParams& params,
GDataErrorCode status,
const GURL& content_url,
const FilePath& downloaded_file_path,
bool* has_enough_space) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
base::PlatformFileError error = GDataToPlatformError(status);
// Make sure that downloaded file is properly stored in cache. We don't have
// to wait for this operation to finish since the user can already use the
// downloaded file.
if (error == base::PLATFORM_FILE_OK) {
if (*has_enough_space) {
StoreToCache(params.resource_id,
params.md5,
downloaded_file_path,
FILE_OPERATION_MOVE,
base::Bind(&GDataFileSystem::OnDownloadStoredToCache,
ui_weak_ptr_));
} else {
// If we don't have enough space, remove the downloaded file, and
// report "no space" error.
PostBlockingPoolSequencedTask(
FROM_HERE,
base::Bind(base::IgnoreResult(&file_util::Delete),
downloaded_file_path,
false /* recursive*/));
error = base::PLATFORM_FILE_ERROR_NO_SPACE;
}
}
if (!params.get_file_callback.is_null()) {
params.get_file_callback.Run(error,
downloaded_file_path,
params.mime_type,
REGULAR_FILE);
}
}
void GDataFileSystem::OnDownloadStoredToCache(base::PlatformFileError error,
const std::string& resource_id,
const std::string& md5) {
// Nothing much to do here for now.
}
base::PlatformFileError GDataFileSystem::RenameFileOnFilesystem(
const FilePath& file_path,
const FilePath::StringType& new_name,
FilePath* updated_file_path) {
DCHECK(updated_file_path);
base::AutoLock lock(lock_);
GDataEntry* entry = GetGDataEntryByPath(file_path);
if (!entry)
return base::PLATFORM_FILE_ERROR_NOT_FOUND;
DCHECK(entry->parent());
entry->set_title(new_name);
// After changing the title of the entry, call TakeFile() to remove the
// entry from its parent directory and then add it back in order to go
// through the file name de-duplication.
// TODO(achuith/satorux/zel): This code is fragile. The title has been
// changed, but not the file_name. TakeEntry removes the child based on the
// old file_name, and then re-adds the child by first assigning the new title
// to file_name. http://crbug.com/30157
if (!entry->parent()->TakeEntry(entry))
return base::PLATFORM_FILE_ERROR_FAILED;
*updated_file_path = entry->GetFilePath();
NotifyDirectoryChanged(updated_file_path->DirName());
return base::PLATFORM_FILE_OK;
}
base::PlatformFileError GDataFileSystem::AddEntryToDirectoryOnFilesystem(
const FilePath& file_path, const FilePath& dir_path) {
base::AutoLock lock(lock_);
GDataEntry* entry = GetGDataEntryByPath(file_path);
if (!entry)
return base::PLATFORM_FILE_ERROR_NOT_FOUND;
DCHECK_EQ(root_.get(), entry->parent());
GDataEntry* dir_entry = GetGDataEntryByPath(dir_path);
if (!dir_entry)
return base::PLATFORM_FILE_ERROR_NOT_FOUND;
GDataDirectory* dir = dir_entry->AsGDataDirectory();
if (!dir)
return base::PLATFORM_FILE_ERROR_NOT_A_DIRECTORY;
if (!dir->TakeEntry(entry))
return base::PLATFORM_FILE_ERROR_FAILED;
NotifyDirectoryChanged(dir_path);
return base::PLATFORM_FILE_OK;
}
base::PlatformFileError GDataFileSystem::RemoveEntryFromDirectoryOnFilesystem(
const FilePath& file_path, const FilePath& dir_path,
FilePath* updated_file_path) {
DCHECK(updated_file_path);
base::AutoLock lock(lock_);
GDataEntry* entry = GetGDataEntryByPath(file_path);
if (!entry)
return base::PLATFORM_FILE_ERROR_NOT_FOUND;
GDataEntry* dir = GetGDataEntryByPath(dir_path);
if (!dir)
return base::PLATFORM_FILE_ERROR_NOT_FOUND;
if (!dir->AsGDataDirectory())
return base::PLATFORM_FILE_ERROR_NOT_A_DIRECTORY;
DCHECK_EQ(dir->AsGDataDirectory(), entry->parent());
if (!root_->TakeEntry(entry))
return base::PLATFORM_FILE_ERROR_FAILED;
*updated_file_path = entry->GetFilePath();
NotifyDirectoryChanged(updated_file_path->DirName());
return base::PLATFORM_FILE_OK;
}
base::PlatformFileError GDataFileSystem::RemoveEntryFromFileSystem(
const FilePath& file_path) {
std::string resource_id;
base::PlatformFileError error = RemoveEntryFromGData(file_path, &resource_id);
if (error != base::PLATFORM_FILE_OK)
return error;
// If resource_id is not empty, remove its corresponding file from cache.
if (!resource_id.empty())
RemoveFromCache(resource_id, CacheOperationCallback());
return base::PLATFORM_FILE_OK;
}
base::PlatformFileError GDataFileSystem::UpdateFromFeed(
const std::vector<DocumentFeed*>& feed_list,
ContentOrigin origin,
int start_changestamp,
int root_feed_changestamp) {
DVLOG(1) << "Updating directory with a feed";
bool is_delta_feed = start_changestamp != 0;
// We need to lock here as well (despite FindEntryByPath lock) since directory
// instance below is a 'live' object.
base::AutoLock lock(lock_);
bool should_notify_initial_load = root_->origin() == INITIALIZING;
root_->set_origin(origin);
root_->set_refresh_time(base::Time::Now());
int delta_feed_changestamp = 0;
int num_regular_files = 0;
int num_hosted_documents = 0;
FileResourceIdMap file_map;
base::PlatformFileError error =
FeedToFileResourceMap(feed_list,
&file_map,
&delta_feed_changestamp,
&num_regular_files,
&num_hosted_documents);
if (error != base::PLATFORM_FILE_OK)
return error;
ApplyFeedFromFileUrlMap(
is_delta_feed,
is_delta_feed ? delta_feed_changestamp : root_feed_changestamp,
&file_map);
if (should_notify_initial_load)
NotifyInitialLoadFinished();
// Shouldn't record histograms when processing delta feeds.
if (!is_delta_feed) {
const int num_total_files = num_hosted_documents + num_regular_files;
UMA_HISTOGRAM_COUNTS("GData.NumberOfRegularFiles", num_regular_files);
UMA_HISTOGRAM_COUNTS("GData.NumberOfHostedDocuments",
num_hosted_documents);
UMA_HISTOGRAM_COUNTS("GData.NumberOfTotalFiles", num_total_files);
}
return base::PLATFORM_FILE_OK;
}
void GDataFileSystem::ApplyFeedFromFileUrlMap(
bool is_delta_feed,
int feed_changestamp,
FileResourceIdMap* file_map) {
lock_.AssertAcquired();
// Don't send directory content change notification while performing
// the initial content retrieval.
const bool should_notify_directory_changed = is_delta_feed;
std::set<FilePath> changed_dirs;
if (!is_delta_feed) { // Full update.
root_->RemoveChildren();
changed_dirs.insert(root_->GetFilePath());
}
root_->set_largest_changestamp(feed_changestamp);
scoped_ptr<GDataRootDirectory> orphaned_entries_dir(
new GDataRootDirectory);
// Go through all entires generated by the feed and apply them to the local
// snapshot of the file system.
for (FileResourceIdMap::iterator it = file_map->begin();
it != file_map->end();) {
// Ensure that the entry is deleted, unless the ownership is explicitly
// transferred by entry.release().
scoped_ptr<GDataEntry> entry(it->second);
DCHECK_EQ(it->first, entry->resource_id());
// Erase the entry so the deleted entry won't be referenced.
file_map->erase(it++);
GDataEntry* old_entry = root_->GetEntryByResourceId(entry->resource_id());
GDataDirectory* dest_dir = NULL;
if (entry->is_deleted()) { // Deleted file/directory.
DVLOG(1) << "Removing file " << entry->file_name();
if (!old_entry)
continue;
dest_dir = old_entry->parent();
if (!dest_dir) {
NOTREACHED();
continue;
}
RemoveEntryFromDirectoryAndCollectChangedDirectories(
dest_dir, old_entry, &changed_dirs);
} else if (old_entry) { // Change or move of existing entry.
// Please note that entry rename is just a special case of change here
// since name is just one of the properties that can change.
DVLOG(1) << "Changed file " << entry->file_name();
dest_dir = old_entry->parent();
if (!dest_dir) {
NOTREACHED();
continue;
}
// Move children files over if we are dealing with directories.
if (old_entry->AsGDataDirectory() && entry->AsGDataDirectory()) {
entry->AsGDataDirectory()->TakeOverEntries(
old_entry->AsGDataDirectory());
}
// Remove the old instance of this entry.
RemoveEntryFromDirectoryAndCollectChangedDirectories(
dest_dir, old_entry, &changed_dirs);
// Did we actually move the new file to another directory?
if (dest_dir->resource_id() != entry->parent_resource_id()) {
changed_dirs.insert(dest_dir->GetFilePath());
dest_dir = FindDirectoryForNewEntry(entry.get(),
*file_map,
orphaned_entries_dir.get());
}
DCHECK(dest_dir);
AddEntryToDirectoryAndCollectChangedDirectories(
entry.release(),
dest_dir,
orphaned_entries_dir.get(),
&changed_dirs);
} else { // Adding a new file.
dest_dir = FindDirectoryForNewEntry(entry.get(),
*file_map,
orphaned_entries_dir.get());
DCHECK(dest_dir);
AddEntryToDirectoryAndCollectChangedDirectories(
entry.release(),
dest_dir,
orphaned_entries_dir.get(),
&changed_dirs);
}
// Record changed directory if this was a delta feed and the parent
// directory is already properly rooted within its parent.
if (dest_dir && (dest_dir->parent() || dest_dir == root_.get()) &&
dest_dir != orphaned_entries_dir.get() && is_delta_feed) {
changed_dirs.insert(dest_dir->GetFilePath());
}
}
// All entry must be erased from the map.
DCHECK(file_map->empty());
if (should_notify_directory_changed) {
for (std::set<FilePath>::iterator dir_iter = changed_dirs.begin();
dir_iter != changed_dirs.end(); ++dir_iter) {
NotifyDirectoryChanged(*dir_iter);
}
}
}
GDataDirectory* GDataFileSystem::FindDirectoryForNewEntry(
GDataEntry* new_entry,
const FileResourceIdMap& file_map,
GDataRootDirectory* orphaned_entries_dir) {
GDataDirectory* dir = NULL;
// Added file.
const std::string& parent_id = new_entry->parent_resource_id();
if (parent_id.empty()) {
dir = root_.get();
DVLOG(1) << "Root parent for " << new_entry->file_name();
} else {
GDataEntry* entry = root_->GetEntryByResourceId(parent_id);
dir = entry ? entry->AsGDataDirectory() : NULL;
if (!dir) {
// The parent directory was also added with this set of feeds.
FileResourceIdMap::const_iterator find_iter =
file_map.find(parent_id);
dir = (find_iter != file_map.end() &&
find_iter->second) ?
find_iter->second->AsGDataDirectory() : NULL;
if (dir) {
DVLOG(1) << "Found parent for " << new_entry->file_name()
<< " in file_map " << parent_id;
} else {
DVLOG(1) << "Adding orphan " << new_entry->GetFilePath().value();
dir = orphaned_entries_dir;
}
}
}
return dir;
}
base::PlatformFileError GDataFileSystem::FeedToFileResourceMap(
const std::vector<DocumentFeed*>& feed_list,
FileResourceIdMap* file_map,
int* feed_changestamp,
int* num_regular_files,
int* num_hosted_documents) {
lock_.AssertAcquired();
base::PlatformFileError error = base::PLATFORM_FILE_OK;
*num_regular_files = 0;
*num_hosted_documents = 0;
for (size_t i = 0; i < feed_list.size(); ++i) {
const DocumentFeed* feed = feed_list[i];
// Get upload url from the root feed. Links for all other collections will
// be handled in GDatadirectory::FromDocumentEntry();
if (i == 0) {
const Link* root_feed_upload_link =
feed->GetLinkByType(Link::RESUMABLE_CREATE_MEDIA);
if (root_feed_upload_link)
root_->set_upload_url(root_feed_upload_link->href());
*feed_changestamp = feed->largest_changestamp();
DCHECK_GE(*feed_changestamp, 0);
}
for (ScopedVector<DocumentEntry>::const_iterator iter =
feed->entries().begin();
iter != feed->entries().end(); ++iter) {
DocumentEntry* doc = *iter;
GDataEntry* entry = GDataEntry::FromDocumentEntry(NULL, doc,
root_.get());
// Some document entries don't map into files (i.e. sites).
if (!entry)
continue;
// Count the number of files.
GDataFile* as_file = entry->AsGDataFile();
if (as_file) {
if (as_file->is_hosted_document())
++(*num_hosted_documents);
else
++(*num_regular_files);
}
FileResourceIdMap::iterator map_entry =
file_map->find(entry->resource_id());
// An entry with the same self link may already exist, so we need to
// release the existing GDataEntry instance before overwriting the
// entry with another GDataEntry instance.
if (map_entry != file_map->end()) {
LOG(WARNING) << "Found duplicate file "
<< map_entry->second->file_name();
delete map_entry->second;
file_map->erase(map_entry);
}
file_map->insert(
std::pair<std::string, GDataEntry*>(entry->resource_id(), entry));
}
}
if (error != base::PLATFORM_FILE_OK) {
// If the code above fails to parse a feed, any GDataEntry instance
// added to |file_by_url| is not managed by a GDataDirectory instance,
// so we need to explicitly release them here.
STLDeleteValues(file_map);
}
return error;
}
void GDataFileSystem::NotifyCacheInitialized() {
DVLOG(1) << "Cache initialized";
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&GDataFileSystem::NotifyCacheInitialized,
ui_weak_ptr_));
return;
}
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Notify the observers that the cache is initialized.
FOR_EACH_OBSERVER(Observer, observers_, OnCacheInitialized());
}
void GDataFileSystem::NotifyFilePinned(const std::string& resource_id,
const std::string& md5) {
DVLOG(1) << "File pinned " << resource_id << ": " << md5;
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&GDataFileSystem::NotifyFilePinned,
ui_weak_ptr_,
resource_id,
md5));
return;
}
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Notify the observers that a file is pinned with |resource_id| and |md5|.
FOR_EACH_OBSERVER(Observer, observers_, OnFilePinned(resource_id, md5));
}
void GDataFileSystem::NotifyFileUnpinned(const std::string& resource_id,
const std::string& md5) {
DVLOG(1) << "File unpinned " << resource_id << ": " << md5;
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&GDataFileSystem::NotifyFileUnpinned,
ui_weak_ptr_,
resource_id,
md5));
return;
}
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Notify the observers that a file is unpinned with |resource_id| and |md5|.
FOR_EACH_OBSERVER(Observer, observers_, OnFileUnpinned(resource_id, md5));
}
void GDataFileSystem::NotifyDirectoryChanged(const FilePath& directory_path) {
DVLOG(1) << "Content changed of " << directory_path.value();
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&GDataFileSystem::NotifyDirectoryChanged,
ui_weak_ptr_,
directory_path));
return;
}
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Notify the observers that content of |directory_path| has been changed.
FOR_EACH_OBSERVER(Observer, observers_, OnDirectoryChanged(directory_path));
}
void GDataFileSystem::NotifyInitialLoadFinished() {
DVLOG(1) << "Initial load finished";
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&GDataFileSystem::NotifyInitialLoadFinished, ui_weak_ptr_));
return;
}
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Notify the observers that root directory has been initialized.
FOR_EACH_OBSERVER(Observer, observers_, OnInitialLoadFinished());
}
void GDataFileSystem::NotifyDocumentFeedFetched(int num_accumulated_entries) {
DVLOG(1) << "Document feed fetched: " << num_accumulated_entries;
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&GDataFileSystem::NotifyDocumentFeedFetched,
ui_weak_ptr_,
num_accumulated_entries));
return;
}
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Notify the observers that a document feed is fetched.
FOR_EACH_OBSERVER(Observer, observers_,
OnDocumentFeedFetched(num_accumulated_entries));
}
base::PlatformFileError GDataFileSystem::AddNewDirectory(
const FilePath& directory_path, base::Value* entry_value) {
if (!entry_value)
return base::PLATFORM_FILE_ERROR_FAILED;
scoped_ptr<DocumentEntry> doc_entry(DocumentEntry::CreateFrom(entry_value));
if (!doc_entry.get())
return base::PLATFORM_FILE_ERROR_FAILED;
// We need to lock here as well (despite FindEntryByPath lock) since directory
// instance below is a 'live' object.
base::AutoLock lock(lock_);
// Find parent directory element within the cached file system snapshot.
GDataEntry* entry = GetGDataEntryByPath(directory_path);
if (!entry)
return base::PLATFORM_FILE_ERROR_FAILED;
// Check if parent is a directory since in theory since this is a callback
// something could in the meantime have nuked the parent dir and created a
// file with the exact same name.
GDataDirectory* parent_dir = entry->AsGDataDirectory();
if (!parent_dir)
return base::PLATFORM_FILE_ERROR_FAILED;
GDataEntry* new_entry = GDataEntry::FromDocumentEntry(parent_dir,
doc_entry.get(),
root_.get());
if (!new_entry)
return base::PLATFORM_FILE_ERROR_FAILED;
parent_dir->AddEntry(new_entry);
// |directory_path| is not necessary same as |entry->GetFilePath()|. It may be
// virtual path that references the entry (e.g. path under which content
// search result is shown).
// We want to dispatch directory changed with the actual entry's path.
NotifyDirectoryChanged(entry->GetFilePath());
return base::PLATFORM_FILE_OK;
}
GDataFileSystem::FindMissingDirectoryResult
GDataFileSystem::FindFirstMissingParentDirectory(
const FilePath& directory_path,
GURL* last_dir_content_url,
FilePath* first_missing_parent_path) {
// Let's find which how deep is the existing directory structure and
// get the first element that's missing.
std::vector<FilePath::StringType> path_parts;
directory_path.GetComponents(&path_parts);
FilePath current_path;
base::AutoLock lock(lock_);
for (std::vector<FilePath::StringType>::const_iterator iter =
path_parts.begin();
iter != path_parts.end(); ++iter) {
current_path = current_path.Append(*iter);
GDataEntry* entry = GetGDataEntryByPath(current_path);
if (entry) {
if (entry->file_info().is_directory) {
*last_dir_content_url = entry->content_url();
} else {
// Huh, the segment found is a file not a directory?
return FOUND_INVALID;
}
} else {
*first_missing_parent_path = current_path;
return FOUND_MISSING;
}
}
return DIRECTORY_ALREADY_PRESENT;
}
GURL GDataFileSystem::GetUploadUrlForDirectory(
const FilePath& destination_directory) {
// Find directory element within the cached file system snapshot.
base::AutoLock lock(lock_);
GDataEntry* entry = GetGDataEntryByPath(destination_directory);
GDataDirectory* dir = entry ? entry->AsGDataDirectory() : NULL;
return dir ? dir->upload_url() : GURL();
}
base::PlatformFileError GDataFileSystem::RemoveEntryFromGData(
const FilePath& file_path, std::string* resource_id) {
resource_id->clear();
// We need to lock here as well (despite FindEntryByPath lock) since
// directory instance below is a 'live' object.
base::AutoLock lock(lock_);
// Find directory element within the cached file system snapshot.
GDataEntry* entry = GetGDataEntryByPath(file_path);
if (!entry)
return base::PLATFORM_FILE_ERROR_NOT_FOUND;
// You can't remove root element.
if (!entry->parent())
return base::PLATFORM_FILE_ERROR_ACCESS_DENIED;
// If it's a file (only files have resource id), get its resource id so that
// we can remove it after releasing the auto lock.
if (entry->AsGDataFile())
*resource_id = entry->AsGDataFile()->resource_id();
GDataDirectory* parent_dir = entry->parent();
if (!parent_dir->RemoveEntry(entry))
return base::PLATFORM_FILE_ERROR_NOT_FOUND;
NotifyDirectoryChanged(parent_dir->GetFilePath());
return base::PLATFORM_FILE_OK;
}
void GDataFileSystem::AddUploadedFile(const FilePath& virtual_dir_path,
DocumentEntry* entry,
const FilePath& file_content_path,
FileOperationType cache_operation) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!entry) {
NOTREACHED();
return;
}
std::string resource_id;
std::string md5;
{
base::AutoLock lock(lock_);
GDataEntry* dir_entry = GetGDataEntryByPath(virtual_dir_path);
if (!dir_entry)
return;
GDataDirectory* parent_dir = dir_entry->AsGDataDirectory();
if (!parent_dir)
return;
scoped_ptr<GDataEntry> new_entry(
GDataEntry::FromDocumentEntry(parent_dir, entry, root_.get()));
if (!new_entry.get())
return;
GDataFile* file = new_entry->AsGDataFile();
DCHECK(file);
resource_id = file->resource_id();
md5 = file->file_md5();
parent_dir->AddEntry(new_entry.release());
}
NotifyDirectoryChanged(virtual_dir_path);
StoreToCache(resource_id, md5, file_content_path, cache_operation,
CacheOperationCallback());
}
void GDataFileSystem::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
if (type == chrome::NOTIFICATION_PREF_CHANGED) {
PrefService* pref_service = profile_->GetPrefs();
std::string* pref_name = content::Details<std::string>(details).ptr();
if (*pref_name == prefs::kDisableGDataHostedFiles) {
SetHideHostedDocuments(
pref_service->GetBoolean(prefs::kDisableGDataHostedFiles));
}
} else {
NOTREACHED();
}
}
bool GDataFileSystem::hide_hosted_documents() {
base::AutoLock lock(lock_);
return hide_hosted_docs_;
}
void GDataFileSystem::SetHideHostedDocuments(bool hide) {
FilePath root_path;
{
base::AutoLock lock(lock_);
if (hide == hide_hosted_docs_)
return;
hide_hosted_docs_ = hide;
root_path = root_->GetFilePath();
}
// Kick of directory refresh when this setting changes.
NotifyDirectoryChanged(root_path);
}
//===================== GDataFileSystem: Cache entry points ====================
bool GDataFileSystem::IsUnderGDataCacheDirectory(const FilePath& path) const {
return gdata_cache_path_ == path || gdata_cache_path_.IsParent(path);
}
FilePath GDataFileSystem::GetCacheDirectoryPath(
GDataRootDirectory::CacheSubDirectoryType sub_dir_type) const {
DCHECK_LE(0, sub_dir_type);
DCHECK_GT(GDataRootDirectory::NUM_CACHE_TYPES, sub_dir_type);
return cache_paths_[sub_dir_type];
}
FilePath GDataFileSystem::GetCacheFilePath(
const std::string& resource_id,
const std::string& md5,
GDataRootDirectory::CacheSubDirectoryType sub_dir_type,
CachedFileOrigin file_origin) const {
DCHECK(sub_dir_type != GDataRootDirectory::CACHE_TYPE_META);
// Runs on any thread.
// Filename is formatted as resource_id.md5, i.e. resource_id is the base
// name and md5 is the extension.
std::string base_name = util::EscapeCacheFileName(resource_id);
if (file_origin == CACHED_FILE_LOCALLY_MODIFIED) {
DCHECK(sub_dir_type == GDataRootDirectory::CACHE_TYPE_PERSISTENT);
base_name += FilePath::kExtensionSeparator;
base_name += kLocallyModifiedFileExtension;
} else if (!md5.empty()) {
base_name += FilePath::kExtensionSeparator;
base_name += util::EscapeCacheFileName(md5);
}
// For mounted archives the filename is formatted as resource_id.md5.mounted,
// i.e. resource_id.md5 is the base name and ".mounted" is the extension
if (file_origin == CACHED_FILE_MOUNTED) {
DCHECK(sub_dir_type == GDataRootDirectory::CACHE_TYPE_PERSISTENT);
base_name += FilePath::kExtensionSeparator;
base_name += kMountedArchiveFileExtension;
}
return GetCacheDirectoryPath(sub_dir_type).Append(base_name);
}
void GDataFileSystem::StoreToCache(const std::string& resource_id,
const std::string& md5,
const FilePath& source_path,
FileOperationType file_operation_type,
const CacheOperationCallback& callback) {
InitializeCacheIfNecessary();
base::PlatformFileError* error =
new base::PlatformFileError(base::PLATFORM_FILE_OK);
PostBlockingPoolSequencedTaskAndReply(
FROM_HERE,
base::Bind(&GDataFileSystem::StoreToCacheOnIOThreadPool,
base::Unretained(this),
resource_id,
md5,
source_path,
file_operation_type,
error),
base::Bind(&RunCacheOperationCallbackHelper,
callback,
base::Owned(error),
resource_id,
md5));
}
void GDataFileSystem::Pin(const std::string& resource_id,
const std::string& md5,
const CacheOperationCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
InitializeCacheIfNecessary();
base::PlatformFileError* error =
new base::PlatformFileError(base::PLATFORM_FILE_OK);
PostBlockingPoolSequencedTaskAndReply(
FROM_HERE,
base::Bind(&GDataFileSystem::PinOnIOThreadPool,
base::Unretained(this),
resource_id,
md5,
FILE_OPERATION_MOVE,
error),
base::Bind(&GDataFileSystem::OnFilePinned,
ui_weak_ptr_,
base::Owned(error),
resource_id,
md5,
callback));
}
void GDataFileSystem::Unpin(const std::string& resource_id,
const std::string& md5,
const CacheOperationCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
InitializeCacheIfNecessary();
base::PlatformFileError* error =
new base::PlatformFileError(base::PLATFORM_FILE_OK);
PostBlockingPoolSequencedTaskAndReply(
FROM_HERE,
base::Bind(&GDataFileSystem::UnpinOnIOThreadPool,
base::Unretained(this),
resource_id,
md5,
FILE_OPERATION_MOVE,
error),
base::Bind(&GDataFileSystem::OnFileUnpinned,
ui_weak_ptr_,
base::Owned(error),
resource_id,
md5,
callback));
}
void GDataFileSystem::MarkDirtyInCache(
const std::string& resource_id,
const std::string& md5,
const GetFileFromCacheCallback& callback) {
InitializeCacheIfNecessary();
base::PlatformFileError* error =
new base::PlatformFileError(base::PLATFORM_FILE_OK);
FilePath* cache_file_path = new FilePath;
PostBlockingPoolSequencedTaskAndReply(
FROM_HERE,
base::Bind(&GDataFileSystem::MarkDirtyInCacheOnIOThreadPool,
base::Unretained(this),
resource_id,
md5,
FILE_OPERATION_MOVE,
error,
cache_file_path),
base::Bind(&RunGetFileFromCacheCallbackHelper,
callback,
base::Owned(error),
resource_id,
md5,
base::Owned(cache_file_path)));
}
void GDataFileSystem::CommitDirtyInCache(
const std::string& resource_id,
const std::string& md5,
const CacheOperationCallback& callback) {
InitializeCacheIfNecessary();
base::PlatformFileError* error =
new base::PlatformFileError(base::PLATFORM_FILE_OK);
PostBlockingPoolSequencedTaskAndReply(
FROM_HERE,
base::Bind(&GDataFileSystem::CommitDirtyInCacheOnIOThreadPool,
base::Unretained(this),
resource_id,
md5,
FILE_OPERATION_MOVE,
error),
base::Bind(&RunCacheOperationCallbackHelper,
callback,
base::Owned(error),
resource_id,
md5));
}
void GDataFileSystem::ClearDirtyInCache(
const std::string& resource_id,
const std::string& md5,
const CacheOperationCallback& callback) {
InitializeCacheIfNecessary();
base::PlatformFileError* error =
new base::PlatformFileError(base::PLATFORM_FILE_OK);
PostBlockingPoolSequencedTaskAndReply(
FROM_HERE,
base::Bind(&GDataFileSystem::ClearDirtyInCacheOnIOThreadPool,
base::Unretained(this),
resource_id,
md5,
FILE_OPERATION_MOVE,
error),
base::Bind(&RunCacheOperationCallbackHelper,
callback,
base::Owned(error),
resource_id,
md5));
}
void GDataFileSystem::RemoveFromCache(const std::string& resource_id,
const CacheOperationCallback& callback) {
InitializeCacheIfNecessary();
base::PlatformFileError* error =
new base::PlatformFileError(base::PLATFORM_FILE_OK);
PostBlockingPoolSequencedTaskAndReply(
FROM_HERE,
base::Bind(&GDataFileSystem::RemoveFromCacheOnIOThreadPool,
base::Unretained(this),
resource_id,
error),
base::Bind(&RunCacheOperationCallbackHelper,
callback,
base::Owned(error),
resource_id,
"" /* md5 */));
}
void GDataFileSystem::InitializeCacheIfNecessary() {
// Lock to access cache_initialization_started_.
base::AutoLock lock(lock_);
// Cache initialization is either in progress or has completed.
if (cache_initialization_started_)
return;
// Need to initialize cache.
cache_initialization_started_ = true;
PostBlockingPoolSequencedTask(
FROM_HERE,
base::Bind(&GDataFileSystem::InitializeCacheOnIOThreadPool,
base::Unretained(this)));
}
//========= GDataFileSystem: Cache tasks that ran on io thread pool ============
void GDataFileSystem::InitializeCacheOnIOThreadPool() {
base::PlatformFileError error = CreateCacheDirectories(cache_paths_);
if (error != base::PLATFORM_FILE_OK)
return;
// Change permissions of cache persistent directory to u+rwx,og+x in order to
// allow archive files in that directory to be mounted by cros-disks.
error = ChangeFilePermissions(
GetCacheDirectoryPath(GDataRootDirectory::CACHE_TYPE_PERSISTENT),
S_IRWXU | S_IXGRP | S_IXOTH);
if (error != base::PLATFORM_FILE_OK)
return;
// Scan cache persistent and tmp directories to enumerate all files and create
// corresponding entries for cache map.
GDataRootDirectory::CacheMap cache_map;
ScanCacheDirectory(GDataRootDirectory::CACHE_TYPE_PERSISTENT, &cache_map);
ScanCacheDirectory(GDataRootDirectory::CACHE_TYPE_TMP, &cache_map);
// Then scan pinned and outgoing directories to update existing entries in
// cache map, or create new ones for pinned symlinks to /dev/null which target
// nothing.
// Pinned and outgoing directories should be scanned after the persistent
// directory as we'll add PINNED and DIRTY states respectively to the existing
// files in the persistent directory per the contents of the pinned and
// outgoing directories.
ScanCacheDirectory(GDataRootDirectory::CACHE_TYPE_PINNED, &cache_map);
ScanCacheDirectory(GDataRootDirectory::CACHE_TYPE_OUTGOING, &cache_map);
// Lock to update cache map.
base::AutoLock lock(lock_);
root_->SetCacheMap(cache_map);
NotifyCacheInitialized();
}
void GDataFileSystem::GetFileFromCacheOnIOThreadPool(
const std::string& resource_id,
const std::string& md5,
base::PlatformFileError* error,
FilePath* cache_file_path) {
DCHECK(error);
DCHECK(cache_file_path);
// Lock to access cache map.
base::AutoLock lock(lock_);
GDataRootDirectory::CacheEntry* entry = root_->GetCacheEntry(resource_id,
md5);
if (entry && entry->IsPresent()) {
CachedFileOrigin file_origin;
if (entry->IsMounted()) {
file_origin = CACHED_FILE_MOUNTED;
} else if (entry->IsDirty()) {
file_origin = CACHED_FILE_LOCALLY_MODIFIED;
} else {
file_origin = CACHED_FILE_FROM_SERVER;
}
*cache_file_path = GetCacheFilePath(
resource_id,
md5,
entry->sub_dir_type,
file_origin);
*error = base::PLATFORM_FILE_OK;
} else {
*error = base::PLATFORM_FILE_ERROR_NOT_FOUND;
}
}
void GDataFileSystem::GetCacheStateOnIOThreadPool(
const std::string& resource_id,
const std::string& md5,
base::PlatformFileError* error,
int* cache_state) {
DCHECK(error);
DCHECK(cache_state);
// Lock to access cache map.
base::AutoLock lock(lock_);
*error = base::PLATFORM_FILE_OK;
*cache_state = GDataFile::CACHE_STATE_NONE;
// Get file object for |resource_id|.
GDataEntry* entry = root_->GetEntryByResourceId(resource_id);
if (!entry || !entry->AsGDataFile()) {
*error = base::PLATFORM_FILE_ERROR_NOT_FOUND;
} else {
// Get cache state of file corresponding to |resource_id| and |md5|.
GDataRootDirectory::CacheEntry* entry = root_->GetCacheEntry(resource_id,
md5);
if (entry)
*cache_state = entry->cache_state;
}
}
void GDataFileSystem::StoreToCacheOnIOThreadPool(
const std::string& resource_id,
const std::string& md5,
const FilePath& source_path,
FileOperationType file_operation_type,
base::PlatformFileError* error) {
DCHECK(error);
// Lock to access cache map.
base::AutoLock lock(lock_);
FilePath dest_path;
FilePath symlink_path;
int cache_state = GDataFile::CACHE_STATE_PRESENT;
GDataRootDirectory::CacheSubDirectoryType sub_dir_type =
GDataRootDirectory::CACHE_TYPE_TMP;
GDataRootDirectory::CacheEntry* entry = root_->GetCacheEntry(
resource_id, md5);
// If file was previously pinned, store it in persistent dir and create
// symlink in pinned dir.
if (entry) { // File exists in cache.
// If file is dirty or mounted, return error.
if (entry->IsDirty() || entry->IsMounted()) {
LOG(WARNING) << "Can't store a file to replace a "
<< (entry->IsDirty() ? "dirty" : "mounted")
<< " file: res_id=" << resource_id
<< ", md5=" << md5;
*error = base::PLATFORM_FILE_ERROR_IN_USE;
return;
}
cache_state |= entry->cache_state;
// If file is pinned, determines destination path.
if (entry->IsPinned()) {
sub_dir_type = GDataRootDirectory::CACHE_TYPE_PERSISTENT;
dest_path = GetCacheFilePath(resource_id, md5, sub_dir_type,
CACHED_FILE_FROM_SERVER);
symlink_path = GetCacheFilePath(resource_id, std::string(),
GDataRootDirectory::CACHE_TYPE_PINNED,
CACHED_FILE_FROM_SERVER);
}
}
// File wasn't pinned or doesn't exist in cache, store in tmp dir.
if (dest_path.empty()) {
DCHECK_EQ(GDataRootDirectory::CACHE_TYPE_TMP, sub_dir_type);
dest_path = GetCacheFilePath(resource_id, md5, sub_dir_type,
CACHED_FILE_FROM_SERVER);
}
*error = ModifyCacheState(
source_path,
dest_path,
file_operation_type,
symlink_path,
!symlink_path.empty()); // create symlink
// Determine search pattern for stale filenames corrresponding to resource_id,
// either "<resource_id>*" or "<resource_id>.*".
FilePath stale_filenames_pattern;
if (md5.empty()) {
// No md5 means no extension, append '*' after base name, i.e.
// "<resource_id>*".
// Cannot call |dest_path|.ReplaceExtension when there's no md5 extension:
// if base name of |dest_path| (i.e. escaped resource_id) contains the
// extension separator '.', ReplaceExtension will remove it and everything
// after it. The result will be nothing like the escaped resource_id.
stale_filenames_pattern = FilePath(dest_path.value() + kWildCard);
} else {
// Replace md5 extension with '*' i.e. "<resource_id>.*".
// Note that ReplaceExtension automatically prefixes the extension with the
// extension separator '.'.
stale_filenames_pattern = dest_path.ReplaceExtension(kWildCard);
}
// Delete files that match |stale_filenames_pattern| except for |dest_path|.
DeleteFilesSelectively(stale_filenames_pattern, dest_path);
if (*error == base::PLATFORM_FILE_OK) {
// Now that file operations have completed, update cache map.
root_->UpdateCacheMap(resource_id, md5, sub_dir_type,
cache_state);
}
}
void GDataFileSystem::PinOnIOThreadPool(const std::string& resource_id,
const std::string& md5,
FileOperationType file_operation_type,
base::PlatformFileError* error) {
DCHECK(error);
// Lock to access cache map.
base::AutoLock lock(lock_);
FilePath source_path;
FilePath dest_path;
FilePath symlink_path;
bool create_symlink = true;
int cache_state = GDataFile::CACHE_STATE_PINNED;
GDataRootDirectory::CacheSubDirectoryType sub_dir_type =
GDataRootDirectory::CACHE_TYPE_PERSISTENT;
GDataRootDirectory::CacheEntry* entry = root_->GetCacheEntry(
resource_id, md5);
if (!entry) { // Entry does not exist in cache.
// Set both |dest_path| and |source_path| to /dev/null, so that:
// 1) ModifyCacheState won't move files when |source_path| and |dest_path|
// are the same.
// 2) symlinks to /dev/null will be picked up by GDataSyncClient to download
// pinned files that don't exist in cache.
dest_path = FilePath(kSymLinkToDevNull);
source_path = dest_path;
// Set sub_dir_type to PINNED to indicate that the file doesn't exist.
// When the file is finally downloaded and StoreToCache called, it will be
// moved to persistent directory.
sub_dir_type = GDataRootDirectory::CACHE_TYPE_PINNED;
} else { // File exists in cache, determines destination path.
cache_state |= entry->cache_state;
// Determine source and destination paths.
// If file is dirty or mounted, don't move it, so determine |dest_path| and
// set |source_path| the same, because ModifyCacheState only moves files if
// source and destination are different.
if (entry->IsDirty() || entry->IsMounted()) {
DCHECK_EQ(GDataRootDirectory::CACHE_TYPE_PERSISTENT, entry->sub_dir_type);
dest_path = GetCacheFilePath(resource_id,
md5,
entry->sub_dir_type,
CACHED_FILE_LOCALLY_MODIFIED);
source_path = dest_path;
} else {
// Gets the current path of the file in cache.
source_path = GetCacheFilePath(resource_id,
md5,
entry->sub_dir_type,
CACHED_FILE_FROM_SERVER);
// If file was pinned before but actual file blob doesn't exist in cache:
// - don't need to move the file, so set |dest_path| to |source_path|,
// because ModifyCacheState only moves files if source and destination
// are different
// - don't create symlink since it already exists.
if (entry->sub_dir_type == GDataRootDirectory::CACHE_TYPE_PINNED) {
dest_path = source_path;
create_symlink = false;
} else { // File exists, move it to persistent dir.
dest_path = GetCacheFilePath(resource_id,
md5,
GDataRootDirectory::CACHE_TYPE_PERSISTENT,
CACHED_FILE_FROM_SERVER);
}
}
}
// Create symlink in pinned dir.
if (create_symlink) {
symlink_path = GetCacheFilePath(resource_id,
std::string(),
GDataRootDirectory::CACHE_TYPE_PINNED,
CACHED_FILE_FROM_SERVER);
}
*error = ModifyCacheState(source_path,
dest_path,
file_operation_type,
symlink_path,
create_symlink);
if (*error == base::PLATFORM_FILE_OK) {
// Now that file operations have completed, update cache map.
root_->UpdateCacheMap(resource_id, md5, sub_dir_type,
cache_state);
}
}
void GDataFileSystem::UnpinOnIOThreadPool(const std::string& resource_id,
const std::string& md5,
FileOperationType file_operation_type,
base::PlatformFileError* error) {
DCHECK(error);
// Lock to access cache map.
base::AutoLock lock(lock_);
GDataRootDirectory::CacheEntry* entry = root_->GetCacheEntry(
resource_id, md5);
// Unpinning a file means its entry must exist in cache.
if (!entry) {
LOG(WARNING) << "Can't unpin a file that wasn't pinned or cached: res_id="
<< resource_id
<< ", md5=" << md5;
*error = base::PLATFORM_FILE_ERROR_NOT_FOUND;
return;
}
// Entry exists in cache, determines source and destination paths.
FilePath source_path;
FilePath dest_path;
GDataRootDirectory::CacheSubDirectoryType sub_dir_type =
GDataRootDirectory::CACHE_TYPE_TMP;
// If file is dirty or mounted, don't move it, so determine |dest_path| and
// set |source_path| the same, because ModifyCacheState moves files if source
// and destination are different.
if (entry->IsDirty() || entry->IsMounted()) {
sub_dir_type = GDataRootDirectory::CACHE_TYPE_PERSISTENT;
DCHECK_EQ(sub_dir_type, entry->sub_dir_type);
dest_path = GetCacheFilePath(resource_id,
md5,
entry->sub_dir_type,
CACHED_FILE_LOCALLY_MODIFIED);
source_path = dest_path;
} else {
// Gets the current path of the file in cache.
source_path = GetCacheFilePath(resource_id,
md5,
entry->sub_dir_type,
CACHED_FILE_FROM_SERVER);
// If file was pinned but actual file blob still doesn't exist in cache,
// don't need to move the file, so set |dest_path| to |source_path|, because
// ModifyCacheState only moves files if source and destination are
// different.
if (entry->sub_dir_type == GDataRootDirectory::CACHE_TYPE_PINNED) {
dest_path = source_path;
} else { // File exists, move it to tmp dir.
dest_path = GetCacheFilePath(resource_id, md5,
GDataRootDirectory::CACHE_TYPE_TMP,
CACHED_FILE_FROM_SERVER);
}
}
// If file was pinned, get absolute path of symlink in pinned dir so as to
// remove it.
FilePath symlink_path;
if (entry->IsPinned()) {
symlink_path = GetCacheFilePath(resource_id,
std::string(),
GDataRootDirectory::CACHE_TYPE_PINNED,
CACHED_FILE_FROM_SERVER);
}
*error = ModifyCacheState(
source_path,
dest_path,
file_operation_type,
symlink_path, // This will be deleted if it exists.
false /* don't create symlink*/);
if (*error == base::PLATFORM_FILE_OK) {
// Now that file operations have completed, update cache map.
int cache_state = GDataFile::ClearCachePinned(entry->cache_state);
root_->UpdateCacheMap(resource_id, md5, sub_dir_type,
cache_state);
}
}
void GDataFileSystem::MarkDirtyInCacheOnIOThreadPool(
const std::string& resource_id,
const std::string& md5,
FileOperationType file_operation_type,
base::PlatformFileError* error,
FilePath* cache_file_path) {
DCHECK(error);
DCHECK(cache_file_path);
// Lock to access cache map.
base::AutoLock lock(lock_);
// If file has already been marked dirty in previous instance of chrome, we
// would have lost the md5 info during cache initialization, because the file
// would have been renamed to .local extension.
// So, search for entry in cache without comparing md5.
GDataRootDirectory::CacheEntry* entry = root_->GetCacheEntry(
resource_id, std::string());
// Marking a file dirty means its entry and actual file blob must exist in
// cache.
if (!entry || entry->sub_dir_type == GDataRootDirectory::CACHE_TYPE_PINNED) {
LOG(WARNING) << "Can't mark dirty a file that wasn't cached: res_id="
<< resource_id
<< ", md5=" << md5;
*error = base::PLATFORM_FILE_ERROR_NOT_FOUND;
return;
}
// If a file is already dirty (i.e. MarkDirtyInCache was called before),
// delete outgoing symlink if it exists.
// TODO(benchan): We should only delete outgoing symlink if file is currently
// not being uploaded. However, for now, cache doesn't know if uploading of a
// file is in progress. Per zel, the upload process should be canceled before
// MarkDirtyInCache is called again.
if (entry->IsDirty()) {
// The file must be in persistent dir.
DCHECK_EQ(GDataRootDirectory::CACHE_TYPE_PERSISTENT, entry->sub_dir_type);
// Determine symlink path in outgoing dir, so as to remove it.
FilePath symlink_path = GetCacheFilePath(
resource_id,
std::string(),
GDataRootDirectory::CACHE_TYPE_OUTGOING,
CACHED_FILE_FROM_SERVER);
// We're not moving files here, so simply use empty FilePath for both
// |source_path| and |dest_path| because ModifyCacheState only move files
// if source and destination are different.
*error = ModifyCacheState(
FilePath(), // non-applicable source path
FilePath(), // non-applicable dest path
file_operation_type,
symlink_path,
false /* don't create symlink */);
// Determine current path of dirty file.
if (*error == base::PLATFORM_FILE_OK) {
*cache_file_path = GetCacheFilePath(
resource_id,
md5,
GDataRootDirectory::CACHE_TYPE_PERSISTENT,
CACHED_FILE_LOCALLY_MODIFIED);
}
return;
}
// Move file to persistent dir with new .local extension.
// Get the current path of the file in cache.
FilePath source_path = GetCacheFilePath(resource_id,
md5,
entry->sub_dir_type,
CACHED_FILE_FROM_SERVER);
// Determine destination path.
GDataRootDirectory::CacheSubDirectoryType sub_dir_type =
GDataRootDirectory::CACHE_TYPE_PERSISTENT;
*cache_file_path = GetCacheFilePath(resource_id,
md5,
sub_dir_type,
CACHED_FILE_LOCALLY_MODIFIED);
// If file is pinned, update symlink in pinned dir.
FilePath symlink_path;
if (entry->IsPinned()) {
symlink_path = GetCacheFilePath(resource_id,
std::string(),
GDataRootDirectory::CACHE_TYPE_PINNED,
CACHED_FILE_FROM_SERVER);
}
*error = ModifyCacheState(
source_path,
*cache_file_path,
file_operation_type,
symlink_path,
!symlink_path.empty() /* create symlink */);
if (*error == base::PLATFORM_FILE_OK) {
// Now that file operations have completed, update cache map.
int cache_state = GDataFile::SetCacheDirty(entry->cache_state);
root_->UpdateCacheMap(resource_id, md5, sub_dir_type,
cache_state);
}
}
void GDataFileSystem::CommitDirtyInCacheOnIOThreadPool(
const std::string& resource_id,
const std::string& md5,
FileOperationType file_operation_type,
base::PlatformFileError* error) {
DCHECK(error);
// Lock to access cache map.
base::AutoLock lock(lock_);
// If file has already been marked dirty in previous instance of chrome, we
// would have lost the md5 info during cache initialization, because the file
// would have been renamed to .local extension.
// So, search for entry in cache without comparing md5.
GDataRootDirectory::CacheEntry* entry = root_->GetCacheEntry(
resource_id, std::string());
// Committing a file dirty means its entry and actual file blob must exist in
// cache.
if (!entry || entry->sub_dir_type == GDataRootDirectory::CACHE_TYPE_PINNED) {
LOG(WARNING) << "Can't commit dirty a file that wasn't cached: res_id="
<< resource_id
<< ", md5=" << md5;
*error = base::PLATFORM_FILE_ERROR_NOT_FOUND;
return;
}
// If a file is not dirty (it should have been marked dirty via
// MarkDirtyInCache), commiting it dirty is an invalid operation.
if (!entry->IsDirty()) {
LOG(WARNING) << "Can't commit a non-dirty file: res_id="
<< resource_id
<< ", md5=" << md5;
*error = base::PLATFORM_FILE_ERROR_INVALID_OPERATION;
return;
}
// Dirty files must be in persistent dir.
DCHECK_EQ(GDataRootDirectory::CACHE_TYPE_PERSISTENT, entry->sub_dir_type);
// Create symlink in outgoing dir.
FilePath symlink_path = GetCacheFilePath(
resource_id,
std::string(),
GDataRootDirectory::CACHE_TYPE_OUTGOING,
CACHED_FILE_FROM_SERVER);
// Get target path of symlink i.e. current path of the file in cache.
FilePath target_path = GetCacheFilePath(resource_id,
md5,
entry->sub_dir_type,
CACHED_FILE_LOCALLY_MODIFIED);
// Since there's no need to move files, use |target_path| for both
// |source_path| and |dest_path|, because ModifyCacheState only moves files
// if source and destination are different.
*error = ModifyCacheState(target_path, // source
target_path, // destination
file_operation_type,
symlink_path,
true /* create symlink */);
}
void GDataFileSystem::ClearDirtyInCacheOnIOThreadPool(
const std::string& resource_id,
const std::string& md5,
FileOperationType file_operation_type,
base::PlatformFileError* error) {
DCHECK(error);
// Lock to access cache map.
base::AutoLock lock(lock_);
// |md5| is the new .<md5> extension to rename the file to.
// So, search for entry in cache without comparing md5.
GDataRootDirectory::CacheEntry* entry = root_->GetCacheEntry(
resource_id, std::string());
// Clearing a dirty file means its entry and actual file blob must exist in
// cache.
if (!entry || entry->sub_dir_type == GDataRootDirectory::CACHE_TYPE_PINNED) {
LOG(WARNING) << "Can't clear dirty state of a file that wasn't cached: "
<< "res_id=" << resource_id
<< ", md5=" << md5;
*error = base::PLATFORM_FILE_ERROR_NOT_FOUND;
return;
}
// If a file is not dirty (it should have been marked dirty via
// MarkDirtyInCache), clearing its dirty state is an invalid operation.
if (!entry->IsDirty()) {
LOG(WARNING) << "Can't clear dirty state of a non-dirty file: res_id="
<< resource_id
<< ", md5=" << md5;
*error = base::PLATFORM_FILE_ERROR_INVALID_OPERATION;
return;
}
// File must be dirty and hence in persistent dir.
DCHECK_EQ(GDataRootDirectory::CACHE_TYPE_PERSISTENT, entry->sub_dir_type);
// Get the current path of the file in cache.
FilePath source_path = GetCacheFilePath(resource_id,
md5,
entry->sub_dir_type,
CACHED_FILE_LOCALLY_MODIFIED);
// Determine destination path.
// If file is pinned, move it to persistent dir with .md5 extension;
// otherwise, move it to tmp dir with .md5 extension.
GDataRootDirectory::CacheSubDirectoryType sub_dir_type =
entry->IsPinned() ? GDataRootDirectory::CACHE_TYPE_PERSISTENT :
GDataRootDirectory::CACHE_TYPE_TMP;
FilePath dest_path = GetCacheFilePath(resource_id,
md5,
sub_dir_type,
CACHED_FILE_FROM_SERVER);
// Delete symlink in outgoing dir.
FilePath symlink_path = GetCacheFilePath(
resource_id,
std::string(),
GDataRootDirectory::CACHE_TYPE_OUTGOING,
CACHED_FILE_FROM_SERVER);
*error = ModifyCacheState(
source_path,
dest_path,
file_operation_type,
symlink_path,
false /* don't create symlink */);
// If file is pinned, update symlink in pinned dir.
if (*error == base::PLATFORM_FILE_OK && entry->IsPinned()) {
symlink_path = GetCacheFilePath(resource_id,
std::string(),
GDataRootDirectory::CACHE_TYPE_PINNED,
CACHED_FILE_FROM_SERVER);
// Since there's no moving of files here, use |dest_path| for both
// |source_path| and |dest_path|, because ModifyCacheState only moves files
// if source and destination are different.
*error = ModifyCacheState(dest_path, // source path
dest_path, // destination path
file_operation_type,
symlink_path,
true /* create symlink */);
}
if (*error == base::PLATFORM_FILE_OK) {
// Now that file operations have completed, update cache map.
int cache_state = GDataFile::ClearCacheDirty(entry->cache_state);
root_->UpdateCacheMap(resource_id, md5, sub_dir_type,
cache_state);
}
}
void GDataFileSystem::RemoveFromCacheOnIOThreadPool(
const std::string& resource_id,
base::PlatformFileError* error) {
DCHECK(error);
// Lock to access cache map.
base::AutoLock lock(lock_);
// MD5 is not passed into RemoveFromCache and hence
// RemoveFromCacheOnIOThreadPool, because we would delete all cache files
// corresponding to <resource_id> regardless of the md5.
// So, search for entry in cache without taking md5 into account.
GDataRootDirectory::CacheEntry* entry = root_->GetCacheEntry(
resource_id, std::string());
// If entry doesn't exist or is dirty or mounted in cache, nothing to do.
if (!entry || entry->IsDirty() || entry->IsMounted()) {
DVLOG(1) << "Entry is "
<< (entry ? (entry->IsDirty() ? "dirty" : "mounted") :
"non-existent")
<< " in cache, not removing";
*error = base::PLATFORM_FILE_OK;
return;
}
// Determine paths to delete all cache versions of |resource_id| in
// persistent, tmp and pinned directories.
std::vector<FilePath> paths_to_delete;
// For files in persistent and tmp dirs, delete files that match
// "<resource_id>.*".
paths_to_delete.push_back(GetCacheFilePath(
resource_id,
kWildCard,
GDataRootDirectory::CACHE_TYPE_PERSISTENT,
CACHED_FILE_FROM_SERVER));
paths_to_delete.push_back(GetCacheFilePath(
resource_id,
kWildCard,
GDataRootDirectory::CACHE_TYPE_TMP,
CACHED_FILE_FROM_SERVER));
// For pinned files, filename is "<resource_id>" with no extension, so delete
// "<resource_id>".
paths_to_delete.push_back(GetCacheFilePath(
resource_id,
std::string(),
GDataRootDirectory::CACHE_TYPE_PINNED,
CACHED_FILE_FROM_SERVER));
// Don't delete locally modified (i.e. dirty and possibly outgoing) files.
// Since we're not deleting outgoing symlinks, we don't need to append
// outgoing path to |paths_to_delete|.
FilePath path_to_keep = GetCacheFilePath(
resource_id,
std::string(),
GDataRootDirectory::CACHE_TYPE_PERSISTENT,
CACHED_FILE_LOCALLY_MODIFIED);
for (size_t i = 0; i < paths_to_delete.size(); ++i) {
DeleteFilesSelectively(paths_to_delete[i], path_to_keep);
}
// Now that all file operations have completed, remove from cache map.
root_->RemoveFromCacheMap(resource_id);
*error = base::PLATFORM_FILE_OK;
}
//=== GDataFileSystem: Cache callbacks for tasks that ran on io thread pool ====
void GDataFileSystem::OnFilePinned(base::PlatformFileError* error,
const std::string& resource_id,
const std::string& md5,
const CacheOperationCallback& callback) {
DCHECK(error);
if (!callback.is_null())
callback.Run(*error, resource_id, md5);
if (*error == base::PLATFORM_FILE_OK)
NotifyFilePinned(resource_id, md5);
}
void GDataFileSystem::OnFileUnpinned(base::PlatformFileError* error,
const std::string& resource_id,
const std::string& md5,
const CacheOperationCallback& callback) {
DCHECK(error);
if (!callback.is_null())
callback.Run(*error, resource_id, md5);
if (*error == base::PLATFORM_FILE_OK)
NotifyFileUnpinned(resource_id, md5);
// Now the file is moved from "persistent" to "tmp" directory.
// It's a chance to free up space if needed.
bool* has_enough_space = new bool(false);
PostBlockingPoolSequencedTask(
FROM_HERE,
base::Bind(&GDataFileSystem::FreeDiskSpaceIfNeeded,
base::Unretained(this),
base::Owned(has_enough_space)));
}
//============= GDataFileSystem: internal helper functions =====================
void GDataFileSystem::ScanCacheDirectory(
GDataRootDirectory::CacheSubDirectoryType sub_dir_type,
GDataRootDirectory::CacheMap* cache_map) {
file_util::FileEnumerator enumerator(
GetCacheDirectoryPath(sub_dir_type),
false, // not recursive
static_cast<file_util::FileEnumerator::FileType>(
file_util::FileEnumerator::FILES |
file_util::FileEnumerator::SHOW_SYM_LINKS),
kWildCard);
for (FilePath current = enumerator.Next(); !current.empty();
current = enumerator.Next()) {
// Extract resource_id and md5 from filename.
std::string resource_id;
std::string md5;
std::string extra_extension;
util::ParseCacheFilePath(current, &resource_id, &md5, &extra_extension);
// Determine cache state.
int cache_state = GDataFile::CACHE_STATE_NONE;
// If we're scanning pinned directory and if entry already exists, just
// update its pinned state.
if (sub_dir_type == GDataRootDirectory::CACHE_TYPE_PINNED) {
GDataRootDirectory::CacheMap::iterator iter =
cache_map->find(resource_id);
if (iter != cache_map->end()) { // Entry exists, update pinned state.
GDataRootDirectory::CacheEntry* entry = iter->second;
entry->cache_state = GDataFile::SetCachePinned(entry->cache_state);
continue;
}
// Entry doesn't exist, this is a special symlink that refers to
// /dev/null; follow through to create an entry with the PINNED but not
// PRESENT state.
cache_state = GDataFile::SetCachePinned(cache_state);
} else if (sub_dir_type == GDataRootDirectory::CACHE_TYPE_OUTGOING) {
// If we're scanning outgoing directory, entry must exist, update its
// dirty state.
// If entry doesn't exist, it's a logic error from previous execution,
// ignore this outgoing symlink and move on.
GDataRootDirectory::CacheMap::iterator iter =
cache_map->find(resource_id);
if (iter != cache_map->end()) { // Entry exists, update dirty state.
GDataRootDirectory::CacheEntry* entry = iter->second;
entry->cache_state = GDataFile::SetCacheDirty(entry->cache_state);
} else {
NOTREACHED() << "Dirty cache file MUST have actual file blob";
}
continue;
} else if (extra_extension == kMountedArchiveFileExtension) {
// Mounted archives in cache should be unmounted upon logout/shutdown.
// But if we encounter a mounted file at start, delete it and create an
// entry with not PRESENT state.
DCHECK(sub_dir_type == GDataRootDirectory::CACHE_TYPE_PERSISTENT);
file_util::Delete(current, false);
} else {
// Scanning other directories means that cache file is actually present.
cache_state = GDataFile::SetCachePresent(cache_state);
}
// Create and insert new entry into cache map.
GDataRootDirectory::CacheEntry* entry = new GDataRootDirectory::CacheEntry(
md5, sub_dir_type, cache_state);
cache_map->insert(std::make_pair(resource_id, entry));
}
}
void GDataFileSystem::GetFileFromCacheByResourceIdAndMd5(
const std::string& resource_id,
const std::string& md5,
const GetFileFromCacheCallback& callback) {
InitializeCacheIfNecessary();
base::PlatformFileError* error =
new base::PlatformFileError(base::PLATFORM_FILE_OK);
FilePath* cache_file_path = new FilePath;
PostBlockingPoolSequencedTaskAndReply(
FROM_HERE,
base::Bind(&GDataFileSystem::GetFileFromCacheOnIOThreadPool,
base::Unretained(this),
resource_id,
md5,
error,
cache_file_path),
base::Bind(&RunGetFileFromCacheCallbackHelper,
callback,
base::Owned(error),
resource_id,
md5,
base::Owned(cache_file_path)));
}
void GDataFileSystem::RunTaskOnIOThreadPool(const base::Closure& task) {
task.Run();
{
base::AutoLock lock(num_pending_tasks_lock_);
--num_pending_tasks_;
// Signal when the last task is completed.
if (num_pending_tasks_ == 0)
on_io_completed_->Signal();
}
}
void GDataFileSystem::PostBlockingPoolSequencedTask(
const tracked_objects::Location& from_here,
const base::Closure& task) {
PostBlockingPoolSequencedTaskAndReply(
from_here,
task,
base::Bind(&base::DoNothing));
}
void GDataFileSystem::PostBlockingPoolSequencedTaskAndReply(
const tracked_objects::Location& from_here,
const base::Closure& request_task,
const base::Closure& reply_task) {
{
// Note that we cannot use |lock_| as lock_ can be held before this
// function is called (i.e. InitializeCacheIfNecessary does).
base::AutoLock lock(num_pending_tasks_lock_);
// Initiate the sequenced task. We should Reset() here rather than on the
// blocking thread pool, as Reset() will cause a deadlock if it's called
// while Wait() is being called in the destructor.
//
// Signaling on_io_completed_ is closely coupled with number of pending
// tasks. We signal it when the number decreases to 0. Because of that, we
// should do the reset under |num_pending_tasks_lock_|. Otherwise, we could
// get in trouble if |num_pending_tasks_| gets decreased after the event is
// reset, but before we increase the number here.
on_io_completed_->Reset();
++num_pending_tasks_;
}
base::SequencedWorkerPool* pool = BrowserThread::GetBlockingPool();
const bool posted = pool->GetSequencedTaskRunner(sequence_token_)->
PostTaskAndReply(
from_here,
base::Bind(&GDataFileSystem::RunTaskOnIOThreadPool,
base::Unretained(this),
request_task),
reply_task);
DCHECK(posted);
}
void GDataFileSystem::InitializePreferenceObserver() {
pref_registrar_.reset(new PrefChangeRegistrar());
pref_registrar_->Init(profile_->GetPrefs());
pref_registrar_->Add(prefs::kDisableGDataHostedFiles, this);
}
void SetFreeDiskSpaceGetterForTesting(FreeDiskSpaceGetterInterface* getter) {
delete global_free_disk_getter_for_testing; // Safe to delete NULL;
global_free_disk_getter_for_testing = getter;
}
} // namespace gdata
|