File: gdrive.cpp

package info (click to toggle)
freefilesync 13.7-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 9,044 kB
  • sloc: cpp: 66,712; ansic: 447; makefile: 216
file content (4085 lines) | stat: -rw-r--r-- 194,756 bytes parent folder | download | duplicates (2)
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
// *****************************************************************************
// * This file is part of the FreeFileSync project. It is distributed under    *
// * GNU General Public License: https://www.gnu.org/licenses/gpl-3.0          *
// * Copyright (C) Zenju (zenju AT freefilesync DOT org) - All Rights Reserved *
// *****************************************************************************

#include "gdrive.h"
#include <variant>
#include <unordered_set> //needed by clang
#include <unordered_map> //
#include <libcurl/curl_wrap.h> //DON'T include <curl/curl.h> directly!
//#include <zen/basic_math.h>
#include <zen/base64.h>
//#include <zen/crc.h>
#include <zen/file_access.h>
#include <zen/file_io.h>
#include <zen/file_traverser.h>
#include <zen/guid.h>
#include <zen/http.h>
#include <zen/json.h>
#include <zen/resolve_path.h>
#include <zen/process_exec.h>
#include <zen/socket.h>
#include <zen/shutdown.h>
#include <zen/time.h>
#include <zen/zlib_wrap.h>
#include "abstract_impl.h"
#include "init_curl_libssh2.h"
    #include <poll.h>

using namespace zen;
using namespace fff;
using AFS = AbstractFileSystem;


namespace fff
{
struct GdrivePath
{
    GdriveLogin gdriveLogin;
    AfsPath itemPath; //path relative to drive root
};

struct GdriveRawPath
{
    std::string parentId; //Google Drive item IDs are *globally* unique!
    Zstring itemName;
};
inline
std::weak_ordering operator<=>(const GdriveRawPath& lhs, const GdriveRawPath& rhs)
{
    if (const std::strong_ordering cmp = lhs.parentId <=> rhs.parentId;
        cmp != std::strong_ordering::equal)
        return cmp;

    return compareNativePath(lhs.itemName, rhs.itemName);
}

constinit Global<PathAccessLocker<GdriveRawPath>> globalGdrivePathAccessLocker;
GLOBAL_RUN_ONCE(globalGdrivePathAccessLocker.set(std::make_unique<PathAccessLocker<GdriveRawPath>>()));

template <> std::shared_ptr<PathAccessLocker<GdriveRawPath>> PathAccessLocker<GdriveRawPath>::getGlobalInstance() { return globalGdrivePathAccessLocker.get(); }
template <> Zstring PathAccessLocker<GdriveRawPath>::getItemName(const GdriveRawPath& nativePath) { return nativePath.itemName; }

using PathAccessLock = PathAccessLocker<GdriveRawPath>::Lock; //throw SysError
using PathBlockType  = PathAccessLocker<GdriveRawPath>::BlockType;
}


namespace
{
//Google Drive REST API Overview:  https://developers.google.com/drive/api/v3/about-sdk
//Google Drive REST API Reference: https://developers.google.com/drive/api/v3/reference
const Zchar* GOOGLE_REST_API_SERVER = Zstr("www.googleapis.com");

constexpr std::chrono::seconds HTTP_SESSION_MAX_IDLE_TIME  (20);
constexpr std::chrono::seconds HTTP_SESSION_CLEANUP_INTERVAL(4);
constexpr std::chrono::seconds GDRIVE_SYNC_INTERVAL         (5);

const size_t GDRIVE_BLOCK_SIZE_DOWNLOAD =  64 * 1024; //libcurl returns blocks of only 16 kB as returned by recv() even if we request larger blocks via CURLOPT_BUFFERSIZE
const size_t GDRIVE_BLOCK_SIZE_UPLOAD   =  64 * 1024; //libcurl requests blocks of 64 kB. larger blocksizes set via CURLOPT_UPLOAD_BUFFERSIZE do not seem to make a difference
const size_t GDRIVE_STREAM_BUFFER_SIZE = 1024 * 1024; //unit: [byte]
//stream buffer should be big enough to facilitate prefetching during alternating read/write operations => e.g. see serialize.h::unbufferedStreamCopy()

constexpr ZstringView gdrivePrefix = Zstr("gdrive:");
const char gdriveFolderMimeType  [] = "application/vnd.google-apps.folder";
const char gdriveShortcutMimeType[] = "application/vnd.google-apps.shortcut"; //= symbolic link!

const char DB_FILE_DESCR[] = "FreeFileSync";
const int  DB_FILE_VERSION = 5; //2021-05-15

std::string getGdriveClientId    () { return ""; } // => replace with live credentials
std::string getGdriveClientSecret() { return ""; } //




struct HttpSessionId
{
    explicit HttpSessionId(const Zstring& serverName) :
        server(serverName) {}

    Zstring server;
};

inline
bool operator==(const HttpSessionId& lhs, const HttpSessionId& rhs) { return equalAsciiNoCase(lhs.server, rhs.server); }
}

//exactly the type of case insensitive comparison we need for server names!
//https://docs.microsoft.com/en-us/windows/win32/api/ws2tcpip/nf-ws2tcpip-getaddrinfow#IDNs
template<> struct std::hash<HttpSessionId> { size_t operator()(const HttpSessionId& sessionId) const { return StringHashAsciiNoCase()(sessionId.server); } };


namespace
{
Zstring concatenateGdriveFolderPathPhrase(const GdrivePath& gdrivePath); //noexcept


//e.g.: gdrive:/john@gmail.com:SharedDrive/folder/file.txt
std::wstring getGdriveDisplayPath(const GdrivePath& gdrivePath)
{
    Zstring displayPath = Zstring(gdrivePrefix) + FILE_NAME_SEPARATOR;

    displayPath += utfTo<Zstring>(gdrivePath.gdriveLogin.email);

    if (!gdrivePath.gdriveLogin.locationName.empty())
        displayPath += Zstr(':') + gdrivePath.gdriveLogin.locationName;

    if (!gdrivePath.itemPath.value.empty())
        displayPath += FILE_NAME_SEPARATOR + gdrivePath.itemPath.value;

    return utfTo<std::wstring>(displayPath);
}


std::wstring formatGdriveErrorRaw(std::string serverResponse)
{
    /* e.g.: {  "error": {  "errors": [{ "domain": "global",
                                         "reason": "invalidSharingRequest",
                                         "message": "Bad Request. User message: \"ACL change not allowed.\"" }],
                            "code":    400,
                            "message": "Bad Request" }}

    or: {  "error":             "invalid_client",
           "error_description": "Unauthorized" }

    or merely: { "error": "invalid_token" }                                    */
    trim(serverResponse);

    assert(!serverResponse.empty());
    if (serverResponse.empty())
        return L"<" + _("empty") + L">"; //at least give some indication

    try
    {
        const JsonValue jresponse = parseJson(serverResponse); //throw JsonParsingError

        if (const JsonValue* error = getChildFromJsonObject(jresponse, "error"))
        {
            if (error->type == JsonValue::Type::string)
                return utfTo<std::wstring>(error->primVal);
            //the inner message is generally more descriptive!
            else if (const JsonValue* errors = getChildFromJsonObject(*error, "errors"))
                if (errors->type == JsonValue::Type::array && !errors->arrayVal.empty())
                    if (const JsonValue* message = getChildFromJsonObject(errors->arrayVal[0], "message"))
                        if (message->type == JsonValue::Type::string)
                            return utfTo<std::wstring>(message->primVal);
        }
    }
    catch (JsonParsingError&) {} //not JSON?

    return utfTo<std::wstring>(serverResponse);
}


AFS::FingerPrint getGdriveFilePrint(const std::string& itemId)
{
    assert(!itemId.empty());
    //Google Drive item ID is persistent and globally unique! :)
    return hashString<AFS::FingerPrint>(itemId);
}

//----------------------------------------------------------------------------------------------------------------

constinit Global<UniSessionCounter> httpSessionCount;
GLOBAL_RUN_ONCE(httpSessionCount.set(createUniSessionCounter()));
UniInitializer globalInitHttp(*httpSessionCount.get());

//----------------------------------------------------------------------------------------------------------------

class HttpSessionManager //reuse (healthy) HTTP sessions globally
{
public:
    explicit HttpSessionManager(const Zstring& caCertFilePath) :
        caCertFilePath_(caCertFilePath),
        sessionCleaner_([this]
    {
        setCurrentThreadName(Zstr("Session Cleaner[HTTP]"));
        runGlobalSessionCleanUp(); //throw ThreadStopRequest
    }) {}

    void access(const HttpSessionId& sessionId, const std::function<void(HttpSession& session)>& useHttpSession /*throw X*/) //throw SysError, X
    {
        Protected<HttpSessionManager::HttpSessionCache>& sessionCache = getSessionCache(sessionId);

        std::unique_ptr<HttpInitSession> httpSession;

        sessionCache.access([&](HttpSessionManager::HttpSessionCache& sessions)
        {
            //assume "isHealthy()" to avoid hitting server connection limits: (clean up of !isHealthy() after use, idle sessions via worker thread)
            if (!sessions.empty())
            {
                httpSession = std::move(sessions.back    ());
                /**/                    sessions.pop_back();
            }
        });

        //create new HTTP session outside the lock: 1. don't block other threads 2. non-atomic regarding "sessionCache"! => one session too many is not a problem!
        if (!httpSession)
            httpSession = std::make_unique<HttpInitSession>(sessionId.server, caCertFilePath_); //throw SysError

        ZEN_ON_SCOPE_EXIT(
            if (isHealthy(httpSession->session)) //thread that created the "!isHealthy()" session is responsible for clean up (avoid hitting server connection limits!)
        sessionCache.access([&](HttpSessionManager::HttpSessionCache& sessions) { sessions.push_back(std::move(httpSession)); }); );

        useHttpSession(httpSession->session); //throw X
    }

private:
    HttpSessionManager           (const HttpSessionManager&) = delete;
    HttpSessionManager& operator=(const HttpSessionManager&) = delete;

    //associate session counting (for initialization/teardown)
    struct HttpInitSession
    {
        HttpInitSession(const Zstring& server, const Zstring& caCertFilePath) :
            session(server, true /*useTls*/, caCertFilePath) {}

        const std::shared_ptr<UniCounterCookie> cookie{getLibsshCurlUnifiedInitCookie(httpSessionCount)}; //throw SysError
        HttpSession session; //life time must be subset of UniCounterCookie
    };
    static bool isHealthy(const HttpSession& s) { return std::chrono::steady_clock::now() - s.getLastUseTime() <= HTTP_SESSION_MAX_IDLE_TIME; }

    using HttpSessionCache = std::vector<std::unique_ptr<HttpInitSession>>;

    Protected<HttpSessionCache>& getSessionCache(const HttpSessionId& sessionId)
    {
        //single global session store per sessionId; life-time bound to globalInstance => never remove a sessionCache!!!
        Protected<HttpSessionCache>* sessionCache = nullptr;

        globalSessionCache_.access([&](GlobalHttpSessions& sessionsById)
        {
            sessionCache = &sessionsById[sessionId]; //get or create
        });
        static_assert(std::is_same_v<GlobalHttpSessions, std::unordered_map<HttpSessionId, Protected<HttpSessionCache>>>, "require std::unordered_map so that the pointers we return remain stable");

        return *sessionCache;
    }

    //run a dedicated clean-up thread => it's unclear when the server let's a connection time out, so we do it preemptively
    //context of worker thread:
    void runGlobalSessionCleanUp() //throw ThreadStopRequest
    {
        std::chrono::steady_clock::time_point lastCleanupTime;
        for (;;)
        {
            const auto now = std::chrono::steady_clock::now();

            if (now < lastCleanupTime + HTTP_SESSION_CLEANUP_INTERVAL)
                interruptibleSleep(lastCleanupTime + HTTP_SESSION_CLEANUP_INTERVAL - now); //throw ThreadStopRequest

            lastCleanupTime = std::chrono::steady_clock::now();

            std::vector<Protected<HttpSessionCache>*> sessionCaches; //pointers remain stable, thanks to std::unordered_map<>

            globalSessionCache_.access([&](GlobalHttpSessions& sessionsByCfg)
            {
                for (auto& [sessionCfg, idleSession] : sessionsByCfg)
                    sessionCaches.push_back(&idleSession);
            });

            for (Protected<HttpSessionCache>* sessionCache : sessionCaches)
                for (;;)
                {
                    bool done = false;
                    sessionCache->access([&](HttpSessionCache& sessions)
                    {
                        for (std::unique_ptr<HttpInitSession>& sshSession : sessions)
                            if (!isHealthy(sshSession->session)) //!isHealthy() sessions are destroyed after use => in this context this means they have been idle for too long
                            {
                                sshSession.swap(sessions.back());
                                /**/            sessions.pop_back(); //run ~HttpSession *inside* the lock! => avoid hitting server limits!
                                return; //don't hold lock for too long: delete only one session at a time, then yield...
                            }
                        done = true;
                    });
                    if (done)
                        break;
                    std::this_thread::yield();
                }
        }
    }

    using GlobalHttpSessions = std::unordered_map<HttpSessionId, Protected<HttpSessionCache>>;

    Protected<GlobalHttpSessions> globalSessionCache_;
    const Zstring caCertFilePath_;
    InterruptibleThread sessionCleaner_;
};

//--------------------------------------------------------------------------------------
constinit Global<HttpSessionManager> globalHttpSessionManager; //caveat: life time must be subset of static UniInitializer!
//--------------------------------------------------------------------------------------

struct GdriveAccess
{
    std::string token;
    int timeoutSec = 0;
};

//===========================================================================================================================

HttpSession::Result googleHttpsRequest(const Zstring& serverName, const std::string& serverRelPath, //throw SysError, X
                                       const std::vector<std::string>& extraHeaders,
                                       std::vector<CurlOption> extraOptions,
                                       const std::function<void  (std::span<const char> buf)>& writeResponse /*throw X*/, //optional
                                       const std::function<size_t(std::span<      char> buf)>& readRequest   /*throw X*/, //optional; return "bytesToRead" bytes unless end of stream!
                                       const std::function<void(const std::string_view& header)>& receiveHeader /*throw X*/, //optional
                                       int timeoutSec)
{
    //https://developers.google.com/drive/api/v3/performance
    //"In order to receive a gzip-encoded response you must do two things: Set an Accept-Encoding header, ["gzip" automatically set by HttpSession]
    extraOptions.emplace_back(CURLOPT_USERAGENT, "FreeFileSync (gzip)"); //and modify your user agent to contain the string gzip."

    const std::shared_ptr<HttpSessionManager> mgr = globalHttpSessionManager.get();
    if (!mgr)
        throw SysError(formatSystemError("googleHttpsRequest", L"", L"Function call not allowed during init/shutdown."));

    HttpSession::Result httpResult;

    mgr->access(HttpSessionId(serverName), [&](HttpSession& session) //throw SysError
    {
        httpResult = session.perform(serverRelPath, extraHeaders, extraOptions, writeResponse, readRequest, receiveHeader, timeoutSec); //throw SysError, X
    });
    return httpResult;
}


//try to get a grip on this crazy REST API: - parameters are passed via query string, header, or body, using GET, POST, PUT, PATCH, DELETE, ... it's a dice roll
HttpSession::Result gdriveHttpsRequest(const std::string& serverRelPath, //throw SysError, X
                                       std::vector<std::string> extraHeaders,
                                       const std::vector<CurlOption>& extraOptions,
                                       const std::function<void  (std::span<const char> buf)>& writeResponse /*throw X*/, //optional
                                       const std::function<size_t(std::span<      char> buf)>& readRequest   /*throw X*/, //optional; return "bytesToRead" bytes unless end of stream!
                                       const std::function<void(const std::string_view& header)>& receiveHeader /*throw X*/, //optional
                                       const GdriveAccess& access)
{
    extraHeaders.push_back("Authorization: Bearer " + access.token);

    return googleHttpsRequest(GOOGLE_REST_API_SERVER, serverRelPath,
                              extraHeaders,
                              extraOptions,
                              writeResponse /*throw X*/,
                              readRequest /*throw X*/,
                              receiveHeader /*throw X*/, access.timeoutSec); //throw SysError, X
}

//========================================================================================================

struct GdriveUser
{
    std::wstring displayName;
    std::string email;
};
GdriveUser getGdriveUser(const GdriveAccess& access) //throw SysError
{
    //https://developers.google.com/drive/api/v3/reference/about
    const std::string& queryParams = xWwwFormUrlEncode(
    {
        {"fields", "user/displayName,user/emailAddress"},
    });
    std::string response;
    gdriveHttpsRequest("/drive/v3/about?" + queryParams, {} /*extraHeaders*/, {} /*extraOptions*/,
    [&](std::span<const char> buf) { response.append(buf.data(), buf.size()); }, nullptr /*readRequest*/, nullptr /*receiveHeader*/, access); //throw SysError

    JsonValue jresponse;
    try { jresponse = parseJson(response); }
    catch (JsonParsingError&) {}

    if (const JsonValue* user = getChildFromJsonObject(jresponse, "user"))
    {
        const std::optional<std::string> displayName = getPrimitiveFromJsonObject(*user, "displayName");
        const std::optional<std::string> email       = getPrimitiveFromJsonObject(*user, "emailAddress");
        if (displayName && email)
            return {utfTo<std::wstring>(*displayName), *email};
    }

    throw SysError(formatGdriveErrorRaw(response));
}


struct GdriveAuthCode
{
    std::string code;
    std::string redirectUrl;
    std::string codeChallenge;
};

struct GdriveAccessToken
{
    std::string value;
    time_t validUntil = 0; //remaining lifetime of the access token
};

struct GdriveAccessInfo
{
    GdriveAccessToken accessToken;
    std::string refreshToken;
    GdriveUser userInfo;
};

GdriveAccessInfo gdriveExchangeAuthCode(const GdriveAuthCode& authCode, int timeoutSec) //throw SysError
{
    //https://developers.google.com/identity/protocols/OAuth2InstalledApp#exchange-authorization-code
    const std::string postBuf = xWwwFormUrlEncode(
    {
        {"code",          authCode.code},
        {"client_id",     getGdriveClientId()},
        {"client_secret", getGdriveClientSecret()},
        {"redirect_uri",  authCode.redirectUrl},
        {"grant_type",    "authorization_code"},
        {"code_verifier", authCode.codeChallenge},
    });
    std::string response;
    googleHttpsRequest(Zstr("oauth2.googleapis.com"), "/token", {} /*extraHeaders*/, {{CURLOPT_POSTFIELDS, postBuf.c_str()}},
    [&](std::span<const char> buf) { response.append(buf.data(), buf.size()); },
    nullptr /*readRequest*/, nullptr /*receiveHeader*/, timeoutSec); //throw SysError

    JsonValue jresponse;
    try { jresponse = parseJson(response); }
    catch (JsonParsingError&) {}

    const std::optional<std::string> accessToken  = getPrimitiveFromJsonObject(jresponse, "access_token");
    const std::optional<std::string> refreshToken = getPrimitiveFromJsonObject(jresponse, "refresh_token");
    const std::optional<std::string> expiresIn    = getPrimitiveFromJsonObject(jresponse, "expires_in"); //e.g. 3600 seconds
    if (!accessToken || !refreshToken || !expiresIn)
        throw SysError(formatGdriveErrorRaw(response));

    const GdriveUser userInfo = getGdriveUser({*accessToken, timeoutSec}); //throw SysError

    return {{*accessToken, std::time(nullptr) + stringTo<time_t>(*expiresIn)}, *refreshToken, userInfo};
}


//Astyle fucks up because of the raw string literal!
//*INDENT-OFF*
GdriveAccessInfo gdriveAuthorizeAccess(const std::string& gdriveLoginHint, const std::function<void()>& updateGui /*throw X*/, int timeoutSec) //throw SysError, X
{
    //spin up a web server to wait for the HTTP GET after Google authentication
    const addrinfo hints 
    {
        .ai_flags =  
                    AI_ADDRCONFIG | //no such issue on Linux: https://bugs.chromium.org/p/chromium/issues/detail?id=5234
                    AI_PASSIVE, //the returned socket addresses will be suitable for bind(2)ing a socket that will accept(2) connections.
        .ai_family   = AF_INET, //make sure our server is reached by IPv4 127.0.0.1, not IPv6 [::1]
        .ai_socktype = SOCK_STREAM, //we *do* care about this one!
    };
    addrinfo* servinfo = nullptr;
    ZEN_ON_SCOPE_EXIT(if (servinfo) ::freeaddrinfo(servinfo));

    //ServiceName == "0": open the next best free port
    const int rcGai = ::getaddrinfo(nullptr,    //_In_opt_ PCSTR            pNodeName
                                    "0",        //_In_opt_ PCSTR            pServiceName
                                    &hints,     //_In_opt_ const ADDRINFOA* pHints
                                    &servinfo); //_Outptr_ PADDRINFOA*      ppResult
    if (rcGai != 0)
        THROW_LAST_SYS_ERROR_GAI(rcGai);
    if (!servinfo)
        throw SysError(L"getaddrinfo: empty server info");

    const auto getBoundSocket = [](const auto& /*::addrinfo*/ ai)
    {
        SocketType testSocket = ::socket(ai.ai_family,    //int socket_family
                                         SOCK_CLOEXEC |
                                         ai.ai_socktype,  //int socket_type
                                         ai.ai_protocol); //int protocol
        if (testSocket == invalidSocket)
            THROW_LAST_SYS_ERROR_WSA("socket");
        ZEN_ON_SCOPE_FAIL(closeSocket(testSocket));

        if (::bind(testSocket, ai.ai_addr, static_cast<int>(ai.ai_addrlen)) != 0)
            THROW_LAST_SYS_ERROR_WSA("bind");

        return testSocket;
    };


    SocketType socket = invalidSocket;

    std::optional<SysError> firstError;
    for (const auto* /*::addrinfo*/ si = servinfo; si; si = si->ai_next)
        try
        {
            socket = getBoundSocket(*si); //throw SysError; pass ownership
            break;
        }
        catch (const SysError& e) { if (!firstError) firstError = e; }

    if (socket == invalidSocket)
        throw* firstError; //list was not empty, so there must have been an error!

    ZEN_ON_SCOPE_EXIT(closeSocket(socket));


    sockaddr_storage addr = {}; //"sufficiently large to store address information for IPv4 (AF_INET) or IPv6 (AF_INET6)" => sockaddr_in and sockaddr_in6
    socklen_t addrLen = sizeof(addr);
    if (::getsockname(socket, reinterpret_cast<sockaddr*>(&addr), &addrLen) != 0)
        THROW_LAST_SYS_ERROR_WSA("getsockname");

    if (addr.ss_family != AF_INET)
        throw SysError(formatSystemError("getsockname", L"", L"Unexpected protocol family: " + numberTo<std::wstring>(addr.ss_family)));

    const int port = ntohs(reinterpret_cast<const sockaddr_in&>(addr).sin_port);
    //the socket is not bound to a specific local IP => inet_ntoa(reinterpret_cast<const sockaddr_in&>(addr).sin_addr) == "0.0.0.0"
    const std::string redirectUrl = "http://127.0.0.1:" + numberTo<std::string>(port);

    if (::listen(socket, SOMAXCONN) != 0)
        THROW_LAST_SYS_ERROR_WSA("listen");


    //"A code_verifier is a high-entropy cryptographic random string using the unreserved characters:"
    //[A-Z] / [a-z] / [0-9] / "-" / "." / "_" / "~", with a minimum length of 43 characters and a maximum length of 128 characters.
    std::string codeChallenge = stringEncodeBase64(generateGUID() + generateGUID());
    replace(codeChallenge, '+', '-'); //
    replace(codeChallenge, '/', '.'); //base64 is almost a perfect fit for code_verifier!
    replace(codeChallenge, '=', '_'); //
    assert(codeChallenge.size() == 44);

    //authenticate Google Drive via browser: https://developers.google.com/identity/protocols/OAuth2InstalledApp#step-2-send-a-request-to-googles-oauth-20-server
    const std::string oauthUrl = "https://accounts.google.com/o/oauth2/v2/auth?" + xWwwFormUrlEncode(
    {
        {"client_id",      getGdriveClientId()},
        {"redirect_uri",   redirectUrl},
        {"response_type",  "code"},
        {"scope",          "https://www.googleapis.com/auth/drive"},
        {"code_challenge", codeChallenge},
        {"code_challenge_method", "plain"},
        {"login_hint",     gdriveLoginHint},
    });
    try
    {
        openWithDefaultApp(utfTo<Zstring>(oauthUrl)); //throw FileError
    }
    catch (const FileError& e) { throw SysError(replaceCpy(e.toString(), L"\n\n", L'\n')); } //errors should be further enriched by context info => SysError

    //process incoming HTTP requests
    for (;;)
    {
        for (;;) //::accept() blocks forever if no client connects (e.g. user just closes the browser window!) => wait for incoming traffic with a time-out via ::select()
        {
            if (updateGui) updateGui(); //throw X

            const int waitTimeMs = 100;
            pollfd fds[] = {{socket, POLLIN}};

            const char* functionName = "poll";
            const int rv = ::poll(fds, std::size(fds), waitTimeMs); //int timeout
            if (rv < 0)
                THROW_LAST_SYS_ERROR_WSA(functionName);
            else if (rv != 0)
                break;
            //else: time-out!
        }
        //potential race! if the connection is gone right after ::select() and before ::accept(), latter will hang
        const int clientSocket = ::accept4(socket,        //int sockfd
                                           nullptr,       //sockaddr* addr
                                           nullptr,       //socklen_t* addrlen
                                           SOCK_CLOEXEC); //int flags
        if (clientSocket == invalidSocket)
            THROW_LAST_SYS_ERROR_WSA("accept");


        //receive first line of HTTP request
        std::string reqLine;
        for (;;)
        {
            const size_t blockSize = 64 * 1024;
            reqLine.resize(reqLine.size() + blockSize);
            const size_t bytesReceived = tryReadSocket(clientSocket, &*(reqLine.end() - blockSize), blockSize); //throw SysError
            reqLine.resize(reqLine.size() - (blockSize - bytesReceived)); //caveat: unsigned arithmetics

            if (contains(reqLine, "\r\n"))
            {
                reqLine = beforeFirst(reqLine, "\r\n", IfNotFoundReturn::none);
                break;
            }
            if (bytesReceived == 0 || reqLine.size() >= 100'000 /*bogus line length*/)
                break;
        }

        //get OAuth2.0 authorization result from Google, either:
        std::string code;
        std::string error;

        //parse header; e.g.: GET http://127.0.0.1:62054/?code=4/ZgBRsB9k68sFzc1Pz1q0__Kh17QK1oOmetySrGiSliXt6hZtTLUlYzm70uElNTH9vt1OqUMzJVeFfplMsYsn4uI HTTP/1.1
        const std::vector<std::string_view> statusItems = splitCpy<std::string_view>(reqLine, ' ', SplitOnEmpty::allow); //Method SP Request-URI SP HTTP-Version CRLF

        if (statusItems.size() == 3 && statusItems[0] == "GET" && startsWith(statusItems[2], "HTTP/"))
        {
            for (const auto& [name, value] : xWwwFormUrlDecode(afterFirst(statusItems[1], "?", IfNotFoundReturn::none)))
                if (name == "code")
                    code = value;
                else if (name == "error")
                    error = value; //e.g. "access_denied" => no more detailed error info available :(
        } //"add explicit braces to avoid dangling else [-Wdangling-else]"

        std::optional<std::variant<GdriveAccessInfo, SysError>> authResult;

        //send HTTP response; https://www.w3.org/Protocols/HTTP/1.0/spec.html#Request-Line
        std::string httpResponse;
        if (code.empty() && error.empty()) //parsing error or unrelated HTTP request
            httpResponse = "HTTP/1.0 400 Bad Request" "\r\n" "\r\n" "400 Bad Request\n" + reqLine;
        else
        {
            std::string htmlMsg = R"(<!DOCTYPE html>
            <html lang="en">
                <head>
                    <meta charset="utf-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <title>TITLE_PLACEHOLDER</title>
                    <style>
                        * {
                            font-family: -apple-system, 'Segoe UI', arial, Tahoma, Helvetica, sans-serif;
                            text-align: center;
                            background-color: #eee; }
                        h1 {
                            font-size:   45px;
                            font-weight: 300;
                            margin: 80px 0 20px 0; }
                        .descr {
                            font-size:   21px;
                            font-weight: 200; }
                    </style>
                </head>
                <body>
                    <h1><img src="https://freefilesync.org/images/FreeFileSync.png" style="vertical-align:middle; height:50px;" alt=""> TITLE_PLACEHOLDER</h1>
                    <div class="descr">MESSAGE_PLACEHOLDER</div>
                </body>
            </html>
            )";
            try
            {
                if (!error.empty())
                    throw SysError(replaceCpy(_("Error code %x"), L"%x",  + L"\"" + utfTo<std::wstring>(error) + L"\""));

                //do as many login-related tasks as possible while we have the browser as an error output device!
                //see AFS::connectNetworkFolder() => errors will be lost after time out in dir_exist_async.h!
                authResult = gdriveExchangeAuthCode({code, redirectUrl, codeChallenge}, timeoutSec); //throw SysError
                replace(htmlMsg, "TITLE_PLACEHOLDER",   utfTo<std::string>(_("Authentication completed.")));
                replace(htmlMsg, "MESSAGE_PLACEHOLDER", utfTo<std::string>(_("You may close this page now and continue with FreeFileSync.")));
            }
            catch (const SysError& e)
            {
                authResult = e;
                replace(htmlMsg, "TITLE_PLACEHOLDER",   utfTo<std::string>(_("Authentication failed.")));
                replace(htmlMsg, "MESSAGE_PLACEHOLDER", utfTo<std::string>(replaceCpy(_("Unable to connect to %x."), L"%x", L"Google Drive") + L"\n\n" + e.toString()));
            }
            httpResponse = "HTTP/1.0 200 OK"         "\r\n"
                           "Content-Type: text/html" "\r\n"
                           "Content-Length: " + numberTo<std::string>(strLength(htmlMsg)) + "\r\n"
                           "\r\n" + htmlMsg;
        }

        for (size_t bytesToSend = httpResponse.size(); bytesToSend > 0;)
            bytesToSend -= tryWriteSocket(clientSocket, &*(httpResponse.end() - bytesToSend), bytesToSend); //throw SysError

        shutdownSocketSend(clientSocket); //throw SysError
        //---------------------------------------------------------------

        if (authResult)
        {
            if (const SysError* e = std::get_if<SysError>(&*authResult))
                throw *e;
            return std::get<GdriveAccessInfo>(*authResult);
        }
    }
}
//*INDENT-ON*


GdriveAccessToken gdriveRefreshAccess(const std::string& refreshToken, int timeoutSec) //throw SysError
{
    //https://developers.google.com/identity/protocols/OAuth2InstalledApp#offline
    const std::string postBuf = xWwwFormUrlEncode(
    {
        {"refresh_token", refreshToken},
        {"client_id",     getGdriveClientId()},
        {"client_secret", getGdriveClientSecret()},
        {"grant_type",    "refresh_token"},
    });
    std::string response;
    googleHttpsRequest(Zstr("oauth2.googleapis.com"), "/token", {} /*extraHeaders*/, {{CURLOPT_POSTFIELDS, postBuf.c_str()}},
    [&](std::span<const char> buf) { response.append(buf.data(), buf.size()); },
    nullptr /*readRequest*/, nullptr /*receiveHeader*/, timeoutSec); //throw SysError

    JsonValue jresponse;
    try { jresponse = parseJson(response); }
    catch (JsonParsingError&) {}

    const std::optional<std::string> accessToken = getPrimitiveFromJsonObject(jresponse, "access_token");
    const std::optional<std::string> expiresIn   = getPrimitiveFromJsonObject(jresponse, "expires_in"); //e.g. 3600 seconds
    if (!accessToken || !expiresIn)
        throw SysError(formatGdriveErrorRaw(response));

    return {*accessToken, std::time(nullptr) + stringTo<time_t>(*expiresIn)};
}


void gdriveRevokeAccess(const GdriveAccess& access) //throw SysError
{
    //https://developers.google.com/identity/protocols/OAuth2InstalledApp#tokenrevoke
    std::string response;
    const HttpSession::Result httpResult = googleHttpsRequest(Zstr("oauth2.googleapis.com"), "/revoke?token=" + access.token,
    {"Content-Type: application/x-www-form-urlencoded"}, {{ CURLOPT_POSTFIELDS, ""}},
    [&](std::span<const char> buf) { response.append(buf.data(), buf.size()); },
    nullptr /*readRequest*/, nullptr /*receiveHeader*/, access.timeoutSec); //throw SysError

    if (httpResult.statusCode != 200)
        throw SysError(formatGdriveErrorRaw(response));
}


int64_t gdriveGetMyDriveFreeSpace(const GdriveAccess& access) //throw SysError
{
    //https://developers.google.com/drive/api/v3/reference/about
    std::string response;
    gdriveHttpsRequest("/drive/v3/about?fields=storageQuota", {} /*extraHeaders*/, {} /*extraOptions*/,
    [&](std::span<const char> buf) { response.append(buf.data(), buf.size()); },
    nullptr /*readRequest*/, nullptr /*receiveHeader*/, access); //throw SysError

    JsonValue jresponse;
    try { jresponse = parseJson(response); }
    catch (JsonParsingError&) {}

    if (const JsonValue* storageQuota = getChildFromJsonObject(jresponse, "storageQuota"))
    {
        const std::optional<std::string> usage = getPrimitiveFromJsonObject(*storageQuota, "usage");
        const std::optional<std::string> limit = getPrimitiveFromJsonObject(*storageQuota, "limit");
        if (usage)
        {
            if (!limit) //"will not be present if the user has unlimited storage."
                return std::numeric_limits<int64_t>::max();

            const auto bytesUsed  = stringTo<int64_t>(*usage);
            const auto bytesLimit = stringTo<int64_t>(*limit);

            if (0 <= bytesUsed && bytesUsed <= bytesLimit)
                return bytesLimit - bytesUsed;
        }
    }
    throw SysError(formatGdriveErrorRaw(response));
}


//instead of the "root" alias Google uses an actual ID in file metadata
std::string /*itemId*/ getMyDriveId(const GdriveAccess& access) //throw SysError
{
    //https://developers.google.com/drive/api/v3/reference/files/get
    const std::string& queryParams = xWwwFormUrlEncode(
    {
        {"supportsAllDrives", "true"},
        {"fields", "id"},
    });
    std::string response;
    gdriveHttpsRequest("/drive/v3/files/root?" + queryParams, {} /*extraHeaders*/, {} /*extraOptions*/,
    [&](std::span<const char> buf) { response.append(buf.data(), buf.size()); },
    nullptr /*readRequest*/, nullptr /*receiveHeader*/, access); //throw SysError

    JsonValue jresponse;
    try { jresponse = parseJson(response); }
    catch (JsonParsingError&) {}

    const std::optional<std::string> itemId = getPrimitiveFromJsonObject(jresponse, "id");
    if (!itemId)
        throw SysError(formatGdriveErrorRaw(response));

    return *itemId;
}


struct DriveDetails
{
    std::string driveId;
    Zstring driveName;
};
std::vector<DriveDetails> getSharedDrives(const GdriveAccess& access) //throw SysError
{
    //https://developers.google.com/drive/api/v3/reference/drives/list
    std::vector<DriveDetails> sharedDrives;
    {
        std::optional<std::string> nextPageToken;
        do
        {
            std::string queryParams = xWwwFormUrlEncode(
            {
                {"pageSize", "100"}, //"[1, 100] Default: 10"
                {"fields", "nextPageToken,drives(id,name)"},
            });
            if (nextPageToken)
                queryParams += '&' + xWwwFormUrlEncode({{"pageToken", *nextPageToken}});

            std::string response;
            gdriveHttpsRequest("/drive/v3/drives?" + queryParams, {} /*extraHeaders*/, {} /*extraOptions*/,
            [&](std::span<const char> buf) { response.append(buf.data(), buf.size()); },
            nullptr /*readRequest*/, nullptr /*receiveHeader*/, access); //throw SysError

            JsonValue jresponse;
            try { jresponse = parseJson(response); }
            catch (JsonParsingError&) {}

            /**/             nextPageToken = getPrimitiveFromJsonObject(jresponse, "nextPageToken");
            const JsonValue* drives        = getChildFromJsonObject    (jresponse, "drives");
            if (!drives || drives->type != JsonValue::Type::array)
                throw SysError(formatGdriveErrorRaw(response));

            for (const JsonValue& driveVal : drives->arrayVal)
            {
                std::optional<std::string> driveId   = getPrimitiveFromJsonObject(driveVal, "id");
                std::optional<std::string> driveName = getPrimitiveFromJsonObject(driveVal, "name");
                if (!driveId || !driveName || driveName->empty())
                    throw SysError(formatGdriveErrorRaw(serializeJson(driveVal)));

                sharedDrives.push_back({std::move(*driveId), utfTo<Zstring>(*driveName)});
            }
        }
        while (nextPageToken);
    }
    return sharedDrives;
}


struct StarredFolderDetails
{
    std::string folderId;
    Zstring folderName;
    std::string sharedDriveId; //empty if on "My Drive"
};
std::vector<StarredFolderDetails> getStarredFolders(const GdriveAccess& access) //throw SysError
{
    //https://developers.google.com/drive/api/v3/reference/files/list
    std::vector<StarredFolderDetails> starredFolders;
    {
        std::optional<std::string> nextPageToken;
        do
        {
            std::string queryParams = xWwwFormUrlEncode(
            {
                {"corpora", "allDrives"}, //"The 'user' corpus includes all files in "My Drive" and "Shared with me" https://developers.google.com/drive/api/v3/reference/files/list
                {"includeItemsFromAllDrives", "true"},
                {"pageSize", "1000"}, //"[1, 1000] Default: 100"
                {"q", std::string("not trashed and starred and mimeType = '") + gdriveFolderMimeType + "'"},
                {"spaces", "drive"},
                {"supportsAllDrives", "true"},
                {"fields", "nextPageToken,incompleteSearch,files(id,name,driveId)"}, //https://developers.google.com/drive/api/v3/reference/files
            });
            if (nextPageToken)
                queryParams += '&' + xWwwFormUrlEncode({{"pageToken", *nextPageToken}});

            std::string response;
            gdriveHttpsRequest("/drive/v3/files?" + queryParams, {} /*extraHeaders*/, {} /*extraOptions*/,
            [&](std::span<const char> buf) { response.append(buf.data(), buf.size()); },
            nullptr /*readRequest*/, nullptr /*receiveHeader*/, access); //throw SysError

            JsonValue jresponse;
            try { jresponse = parseJson(response); }
            catch (JsonParsingError&) {}

            /**/                             nextPageToken    = getPrimitiveFromJsonObject(jresponse, "nextPageToken");
            const std::optional<std::string> incompleteSearch = getPrimitiveFromJsonObject(jresponse, "incompleteSearch");
            const JsonValue*                 files            = getChildFromJsonObject    (jresponse, "files");
            if (!incompleteSearch || *incompleteSearch != "false" || !files || files->type != JsonValue::Type::array)
                throw SysError(formatGdriveErrorRaw(response));

            for (const JsonValue& childVal : files->arrayVal)
            {
                assert(childVal.type == JsonValue::Type::object);
                const std::optional<std::string> itemId   = getPrimitiveFromJsonObject(childVal, "id");
                const std::optional<std::string> itemName = getPrimitiveFromJsonObject(childVal, "name");
                const std::optional<std::string> driveId  = getPrimitiveFromJsonObject(childVal, "driveId");

                if (!itemId || itemId->empty() || !itemName || itemName->empty())
                    throw SysError(formatGdriveErrorRaw(serializeJson(childVal)));

                starredFolders.push_back({*itemId,
                                          utfTo<Zstring>(*itemName),
                                          driveId ? *driveId : ""});
            }
        }
        while (nextPageToken);
    }
    return starredFolders;
}


enum class GdriveItemType : unsigned char
{
    file,
    folder,
    shortcut,
};
enum class FileOwner : unsigned char
{
    none, //"ownedByMe" not populated for items in Shared Drives.
    me,
    other,
};
struct GdriveItemDetails
{
    Zstring itemName;
    uint64_t fileSize = 0;
    time_t modTime  = 0;
    //--- minimize padding ---
    GdriveItemType type = GdriveItemType::file;
    FileOwner owner = FileOwner::none;
    //------------------------
    std::string targetId; //for GdriveItemType::shortcut: https://developers.google.com/drive/api/v3/shortcuts
    std::vector<std::string> parentIds;

    bool operator==(const GdriveItemDetails&) const = default;
};


GdriveItemDetails extractItemDetails(const JsonValue& jvalue) //throw SysError
{
    assert(jvalue.type == JsonValue::Type::object);

    /**/  std::optional<std::string> itemName     = getPrimitiveFromJsonObject(jvalue, "name");
    const std::optional<std::string> mimeType     = getPrimitiveFromJsonObject(jvalue, "mimeType");
    const std::optional<std::string> ownedByMe    = getPrimitiveFromJsonObject(jvalue, "ownedByMe");
    const std::optional<std::string> size         = getPrimitiveFromJsonObject(jvalue, "size");
    const std::optional<std::string> modifiedTime = getPrimitiveFromJsonObject(jvalue, "modifiedTime");
    const JsonValue*                 parents      = getChildFromJsonObject    (jvalue, "parents");
    const JsonValue*                 shortcut     = getChildFromJsonObject    (jvalue, "shortcutDetails");

    if (!itemName || itemName->empty() || !mimeType || !modifiedTime)
        throw SysError(formatGdriveErrorRaw(serializeJson(jvalue)));

    const GdriveItemType type = *mimeType == gdriveFolderMimeType   ? GdriveItemType::folder :
                                *mimeType == gdriveShortcutMimeType ? GdriveItemType::shortcut :
                                GdriveItemType::file;

    const FileOwner owner = ownedByMe ? (*ownedByMe == "true" ? FileOwner::me : FileOwner::other) : FileOwner::none; //"Not populated for items in Shared Drives"
    const uint64_t fileSize = size ? stringTo<uint64_t>(*size) : 0; //not available for folders and shortcuts

    //RFC 3339 date-time: e.g. "2018-09-29T08:39:12.053Z"
    const TimeComp tc = parseTime("%Y-%m-%dT%H:%M:%S", beforeLast(*modifiedTime, '.', IfNotFoundReturn::all));
    if (tc == TimeComp() || !endsWith(*modifiedTime, 'Z')) //'Z' means "UTC" => it seems Google doesn't use the time-zone offset postfix
        throw SysError(L"Modification time is invalid. (" + utfTo<std::wstring>(*modifiedTime) + L')');

    const auto [modTime, timeValid] = utcToTimeT(tc);
    if (!timeValid)
        throw SysError(L"Modification time is invalid. (" + utfTo<std::wstring>(*modifiedTime) + L')');

    std::vector<std::string> parentIds;
    if (parents) //item without "parents" array is possible! e.g. 1. shared item located in "Shared with me", referenced via a Shortcut 2. root folder under "Computers"
        for (const JsonValue& parentVal : parents->arrayVal)
        {
            if (parentVal.type != JsonValue::Type::string)
                throw SysError(formatGdriveErrorRaw(serializeJson(jvalue)));
            parentIds.emplace_back(parentVal.primVal);
        }

    if (!!shortcut != (type == GdriveItemType::shortcut))
        throw SysError(formatGdriveErrorRaw(serializeJson(jvalue)));

    std::string targetId;
    if (shortcut)
    {
        std::optional<std::string> targetItemId = getPrimitiveFromJsonObject(*shortcut, "targetId");
        if (!targetItemId || targetItemId->empty())
            throw SysError(formatGdriveErrorRaw(serializeJson(jvalue)));

        targetId = std::move(*targetItemId);
        //evaluate "targetMimeType" ? don't bother: "The MIME type of a shortcut can become stale"!
    }

    return {utfTo<Zstring>(*itemName), fileSize, modTime, type, owner, std::move(targetId), std::move(parentIds)};
}


GdriveItemDetails getItemDetails(const std::string& itemId, const GdriveAccess& access) //throw SysError
{
    //https://developers.google.com/drive/api/v3/reference/files/get
    const std::string& queryParams = xWwwFormUrlEncode(
    {
        {"fields", "trashed,name,mimeType,ownedByMe,size,modifiedTime,parents,shortcutDetails(targetId)"},
        {"supportsAllDrives", "true"},
    });
    std::string response;
    gdriveHttpsRequest("/drive/v3/files/" + itemId + '?' + queryParams, {} /*extraHeaders*/, {} /*extraOptions*/,
    [&](std::span<const char> buf) { response.append(buf.data(), buf.size()); },
    nullptr /*readRequest*/, nullptr /*receiveHeader*/, access); //throw SysError
    try
    {
        const JsonValue jvalue = parseJson(response); //throw JsonParsingError

        //careful: do NOT return details about trashed items! they don't exist as far as FFS is concerned!!!
        const std::optional<std::string> trashed = getPrimitiveFromJsonObject(jvalue, "trashed");
        if (!trashed)
            throw SysError(formatGdriveErrorRaw(response));
        else if (*trashed == "true")
            throw SysError(L"Item has been trashed.");

        return extractItemDetails(jvalue); //throw SysError
    }
    catch (JsonParsingError&) { throw SysError(formatGdriveErrorRaw(response)); }
}


struct GdriveItem
{
    std::string itemId;
    GdriveItemDetails details;
};
std::vector<GdriveItem> readFolderContent(const std::string& folderId, const GdriveAccess& access) //throw SysError
{
    //https://developers.google.com/drive/api/v3/reference/files/list
    std::vector<GdriveItem> childItems;
    {
        std::optional<std::string> nextPageToken;
        do
        {
            std::string queryParams = xWwwFormUrlEncode(
            {
                {"corpora", "allDrives"}, //"The 'user' corpus includes all files in "My Drive" and "Shared with me" https://developers.google.com/drive/api/v3/reference/files/list
                {"includeItemsFromAllDrives", "true"},
                {"pageSize", "1000"}, //"[1, 1000] Default: 100"
                {"q", "not trashed and '" + folderId + "' in parents"},
                {"spaces", "drive"},
                {"supportsAllDrives", "true"},
                {"fields", "nextPageToken,incompleteSearch,files(id,name,mimeType,ownedByMe,size,modifiedTime,parents,shortcutDetails(targetId))"}, //https://developers.google.com/drive/api/v3/reference/files
            });
            if (nextPageToken)
                queryParams += '&' + xWwwFormUrlEncode({{"pageToken", *nextPageToken}});

            std::string response;
            gdriveHttpsRequest("/drive/v3/files?" + queryParams, {} /*extraHeaders*/, {} /*extraOptions*/,
            [&](std::span<const char> buf) { response.append(buf.data(), buf.size()); },
            nullptr /*readRequest*/, nullptr /*receiveHeader*/, access); //throw SysError

            JsonValue jresponse;
            try { jresponse = parseJson(response); }
            catch (JsonParsingError&) {}

            /**/                             nextPageToken    = getPrimitiveFromJsonObject(jresponse, "nextPageToken");
            const std::optional<std::string> incompleteSearch = getPrimitiveFromJsonObject(jresponse, "incompleteSearch");
            const JsonValue*                 files            = getChildFromJsonObject    (jresponse, "files");
            if (!incompleteSearch || *incompleteSearch != "false" || !files || files->type != JsonValue::Type::array)
                throw SysError(formatGdriveErrorRaw(response));

            for (const JsonValue& childVal : files->arrayVal)
            {
                std::optional<std::string> itemId = getPrimitiveFromJsonObject(childVal, "id");
                if (!itemId || itemId->empty())
                    throw SysError(formatGdriveErrorRaw(serializeJson(childVal)));

                GdriveItemDetails itemDetails(extractItemDetails(childVal)); //throw SysError
                assert(std::find(itemDetails.parentIds.begin(), itemDetails.parentIds.end(), folderId) != itemDetails.parentIds.end());

                childItems.push_back({std::move(*itemId), std::move(itemDetails)});
            }
        }
        while (nextPageToken);
    }
    return childItems;
}


struct FileChange
{
    std::string itemId;
    std::optional<GdriveItemDetails> details; //empty if item was deleted/trashed
};
struct DriveChange
{
    std::string driveId;
    Zstring driveName; //empty if shared drive was deleted
};
struct ChangesDelta
{
    std::string newStartPageToken;
    std::vector<FileChange> fileChanges;
    std::vector<DriveChange> driveChanges;
};
ChangesDelta getChangesDelta(const std::string& sharedDriveId /*empty for "My Drive"*/, const std::string& startPageToken, const GdriveAccess& access) //throw SysError
{
    //https://developers.google.com/drive/api/v3/reference/changes/list
    ChangesDelta delta;
    std::optional<std::string> nextPageToken = startPageToken;
    for (;;)
    {
        std::string queryParams = xWwwFormUrlEncode(
        {
            {"pageToken", *nextPageToken},
            {"fields", "kind,nextPageToken,newStartPageToken,changes(kind,changeType,removed,fileId,file(trashed,name,mimeType,ownedByMe,size,modifiedTime,parents,shortcutDetails(targetId)),driveId,drive(name))"},
            {"includeItemsFromAllDrives", "true"}, //semantics are a mess https://developers.google.com/drive/api/v3/enable-shareddrives https://freefilesync.org/forum/viewtopic.php?t=7827&start=30#p29712
            //in short: if driveId is set: required, but blatant lie; only drive-specific file changes returned
            //          if no driveId set: optional, but blatant lie; only changes to drive objects are returned, but not contained files (with a few exceptions)
            {"pageSize", "1000"}, //"[1, 1000] Default: 100"
            {"spaces", "drive"},
            {"supportsAllDrives", "true"},
            //do NOT "restrictToMyDrive": we're also interested in "Shared with me" items, which might be referenced by a shortcut in "My Drive"
        });
        if (!sharedDriveId.empty())
            queryParams += '&' + xWwwFormUrlEncode({{"driveId", sharedDriveId}}); //only allowed for shared drives!

        std::string response;
        gdriveHttpsRequest("/drive/v3/changes?" + queryParams, {} /*extraHeaders*/, {} /*extraOptions*/,
        [&](std::span<const char> buf) { response.append(buf.data(), buf.size()); },
        nullptr /*readRequest*/, nullptr /*receiveHeader*/, access); //throw SysError

        JsonValue jresponse;
        try { jresponse = parseJson(response); }
        catch (JsonParsingError&) {}

        /**/                             nextPageToken     = getPrimitiveFromJsonObject(jresponse, "nextPageToken");
        const std::optional<std::string> newStartPageToken = getPrimitiveFromJsonObject(jresponse, "newStartPageToken");
        const std::optional<std::string> listKind          = getPrimitiveFromJsonObject(jresponse, "kind");
        const JsonValue*                 changes           = getChildFromJsonObject    (jresponse, "changes");

        if (!!nextPageToken == !!newStartPageToken || //there can be only one
            !listKind || *listKind != "drive#changeList" ||
            !changes || changes->type != JsonValue::Type::array)
            throw SysError(formatGdriveErrorRaw(response));

        for (const JsonValue& childVal : changes->arrayVal)
        {
            const std::optional<std::string> kind       = getPrimitiveFromJsonObject(childVal, "kind");
            const std::optional<std::string> changeType = getPrimitiveFromJsonObject(childVal, "changeType");
            const std::optional<std::string> removed    = getPrimitiveFromJsonObject(childVal, "removed");
            if (!kind || *kind != "drive#change" || !changeType || !removed)
                throw SysError(formatGdriveErrorRaw(serializeJson(childVal)));

            if (*changeType == "file")
            {
                std::optional<std::string> fileId = getPrimitiveFromJsonObject(childVal, "fileId");
                if (!fileId || fileId->empty())
                    throw SysError(formatGdriveErrorRaw(serializeJson(childVal)));

                FileChange change;
                change.itemId = std::move(*fileId);
                if (*removed != "true")
                {
                    const JsonValue* file = getChildFromJsonObject(childVal, "file");
                    if (!file)
                        throw SysError(formatGdriveErrorRaw(serializeJson(childVal)));

                    const std::optional<std::string> trashed = getPrimitiveFromJsonObject(*file, "trashed");
                    if (!trashed)
                        throw SysError(formatGdriveErrorRaw(serializeJson(childVal)));

                    if (*trashed != "true")
                        change.details = extractItemDetails(*file); //throw SysError
                }
                delta.fileChanges.push_back(std::move(change));
            }
            else if (*changeType == "drive")
            {
                std::optional<std::string> driveId = getPrimitiveFromJsonObject(childVal, "driveId");
                if (!driveId || driveId->empty())
                    throw SysError(formatGdriveErrorRaw(serializeJson(childVal)));

                DriveChange change;
                change.driveId = std::move(*driveId);
                if (*removed != "true")
                {
                    const JsonValue* drive = getChildFromJsonObject(childVal, "drive");
                    if (!drive)
                        throw SysError(formatGdriveErrorRaw(serializeJson(childVal)));

                    const std::optional<std::string> name = getPrimitiveFromJsonObject(*drive, "name");
                    if (!name || name->empty())
                        throw SysError(formatGdriveErrorRaw(serializeJson(childVal)));

                    change.driveName = utfTo<Zstring>(*name);
                }
                delta.driveChanges.push_back(std::move(change));
            }
            else assert(false); //no other types (yet!)
        }

        if (!nextPageToken)
        {
            delta.newStartPageToken = *newStartPageToken;
            return delta;
        }
    }
}


std::string /*startPageToken*/ getChangesCurrentToken(const std::string& sharedDriveId /*empty for "My Drive"*/, const GdriveAccess& access) //throw SysError
{
    //https://developers.google.com/drive/api/v3/reference/changes/getStartPageToken
    std::string queryParams = xWwwFormUrlEncode(
    {
        {"supportsAllDrives", "true"},
    });
    if (!sharedDriveId.empty())
        queryParams += '&' + xWwwFormUrlEncode({{"driveId", sharedDriveId}}); //only allowed for shared drives!

    std::string response;
    gdriveHttpsRequest("/drive/v3/changes/startPageToken?" + queryParams, {} /*extraHeaders*/, {} /*extraOptions*/,
    [&](std::span<const char> buf) { response.append(buf.data(), buf.size()); },
    nullptr /*readRequest*/, nullptr /*receiveHeader*/, access); //throw SysError

    JsonValue jresponse;
    try { jresponse = parseJson(response); }
    catch (JsonParsingError&) {}

    const std::optional<std::string> startPageToken = getPrimitiveFromJsonObject(jresponse, "startPageToken");
    if (!startPageToken)
        throw SysError(formatGdriveErrorRaw(response));

    return *startPageToken;
}


//- if item is a folder: deletes recursively!!!
//- even deletes a hardlink with multiple parents => use gdriveUnlinkParent() first
void gdriveDeleteItem(const std::string& itemId, const GdriveAccess& access) //throw SysError
{
    //https://developers.google.com/drive/api/v3/reference/files/delete
    const std::string& queryParams = xWwwFormUrlEncode(
    {
        {"supportsAllDrives", "true"},
    });
    std::string response;
    const HttpSession::Result httpResult = gdriveHttpsRequest("/drive/v3/files/" + itemId + '?' + queryParams,
    {} /*extraHeaders*/, {{CURLOPT_CUSTOMREQUEST, "DELETE"}}, [&](std::span<const char> buf) { response.append(buf.data(), buf.size()); },
    nullptr /*readRequest*/, nullptr /*receiveHeader*/, access); //throw SysError

    if (response.empty() && httpResult.statusCode == 204)
        return; //"If successful, this method returns an empty response body"

    throw SysError(formatGdriveErrorRaw(response));
}


//item is NOT deleted when last parent is removed: it is just not accessible via the "My Drive" hierarchy but still adds to quota! => use for hard links only!
void gdriveUnlinkParent(const std::string& itemId, const std::string& parentId, const GdriveAccess& access) //throw SysError
{
    //https://developers.google.com/drive/api/v3/reference/files/update
    const std::string& queryParams = xWwwFormUrlEncode(
    {
        {"removeParents", parentId},
        {"supportsAllDrives", "true"},
        {"fields", "id,parents"}, //for test if operation was successful
    });
    std::string response;
    const HttpSession::Result httpResult = gdriveHttpsRequest("/drive/v3/files/" + itemId + '?' + queryParams,
    {"Content-Type: application/json; charset=UTF-8"}, {{CURLOPT_CUSTOMREQUEST, "PATCH"}, { CURLOPT_POSTFIELDS, "{}"}},
    [&](std::span<const char> buf) { response.append(buf.data(), buf.size()); }, nullptr /*readRequest*/, nullptr /*receiveHeader*/, access); //throw SysError

    if (response.empty() && httpResult.statusCode == 204)
        return; //removing last parent of item not owned by us returns "204 No Content" (instead of 200 + file body)

    JsonValue jresponse;
    try { jresponse = parseJson(response); /*throw JsonParsingError*/ }
    catch (const JsonParsingError&) {}

    const std::optional<std::string> id      = getPrimitiveFromJsonObject(jresponse, "id"); //id is returned on "success", unlike "parents", see below...
    const JsonValue*                 parents = getChildFromJsonObject(jresponse, "parents");
    if (!id || *id != itemId)
        throw SysError(formatGdriveErrorRaw(response));

    if (parents) //when last parent is removed, Google does NOT return the parents array (not even an empty one!)
        if (parents->type != JsonValue::Type::array ||
            std::any_of(parents->arrayVal.begin(), parents->arrayVal.end(),
        [&](const JsonValue& jval) { return jval.type == JsonValue::Type::string && jval.primVal == parentId; }))
    throw SysError(L"gdriveUnlinkParent: Google Drive internal failure"); //user should never see this...
}


//- if item is a folder: trashes recursively!!!
//- a hardlink with multiple parents will NOT be accessible anymore via any of its path aliases!
void gdriveMoveToTrash(const std::string& itemId, const GdriveAccess& access) //throw SysError
{
    //https://developers.google.com/drive/api/v3/reference/files/update
    const std::string& queryParams = xWwwFormUrlEncode(
    {
        {"supportsAllDrives", "true"},
        {"fields", "trashed"},
    });
    const std::string postBuf = R"({ "trashed": true })";

    std::string response;
    gdriveHttpsRequest("/drive/v3/files/" + itemId + '?' + queryParams,
    {"Content-Type: application/json; charset=UTF-8"}, {{CURLOPT_CUSTOMREQUEST, "PATCH"}, {CURLOPT_POSTFIELDS, postBuf.c_str()}},
    [&](std::span<const char> buf) { response.append(buf.data(), buf.size()); }, nullptr /*readRequest*/, nullptr /*receiveHeader*/, access); //throw SysError

    JsonValue jresponse;
    try { jresponse = parseJson(response); /*throw JsonParsingError*/ }
    catch (const JsonParsingError&) {}

    const std::optional<std::string> trashed = getPrimitiveFromJsonObject(jresponse, "trashed");
    if (!trashed || *trashed != "true")
        throw SysError(formatGdriveErrorRaw(response));
}


//folder name already existing? will (happily) create duplicate => caller must check!
std::string /*folderId*/ gdriveCreateFolderPlain(const Zstring& folderName, const std::string& parentId, const GdriveAccess& access) //throw SysError
{
    //https://developers.google.com/drive/api/v3/folder#creating_a_folder
    const std::string& queryParams = xWwwFormUrlEncode(
    {
        {"supportsAllDrives", "true"},
        {"fields", "id"},
    });
    JsonValue postParams(JsonValue::Type::object);
    postParams.objectVal.emplace("mimeType", gdriveFolderMimeType);
    postParams.objectVal.emplace("name", utfTo<std::string>(folderName));
    postParams.objectVal.emplace("parents", std::vector<JsonValue> {JsonValue(parentId)});
    const std::string& postBuf = serializeJson(postParams, "" /*lineBreak*/, "" /*indent*/);

    std::string response;
    gdriveHttpsRequest("/drive/v3/files?" + queryParams,
    {"Content-Type: application/json; charset=UTF-8"}, {{CURLOPT_POSTFIELDS, postBuf.c_str()}},
    [&](std::span<const char> buf) { response.append(buf.data(), buf.size()); }, nullptr /*readRequest*/, nullptr /*receiveHeader*/, access); //throw SysError

    JsonValue jresponse;
    try { jresponse = parseJson(response); }
    catch (JsonParsingError&) {}

    const std::optional<std::string> itemId = getPrimitiveFromJsonObject(jresponse, "id");
    if (!itemId)
        throw SysError(formatGdriveErrorRaw(response));
    return *itemId;
}


//shortcut name already existing? will (happily) create duplicate => caller must check!
std::string /*shortcutId*/ gdriveCreateShortcutPlain(const Zstring& shortcutName, const std::string& parentId,  const std::string& targetId, const GdriveAccess& access) //throw SysError
{
    /* https://developers.google.com/drive/api/v3/shortcuts
       - targetMimeType is determined automatically (ignored if passed)
       - creating shortcuts to shortcuts fails with "Internal Error"              */
    const std::string& queryParams = xWwwFormUrlEncode(
    {
        {"supportsAllDrives", "true"},
        {"fields", "id"},
    });
    JsonValue shortcutDetails(JsonValue::Type::object);
    shortcutDetails.objectVal.emplace("targetId", targetId);

    JsonValue postParams(JsonValue::Type::object);
    postParams.objectVal.emplace("mimeType", gdriveShortcutMimeType);
    postParams.objectVal.emplace("name", utfTo<std::string>(shortcutName));
    postParams.objectVal.emplace("parents", std::vector<JsonValue> {JsonValue(parentId)});
    postParams.objectVal.emplace("shortcutDetails", std::move(shortcutDetails));
    const std::string& postBuf = serializeJson(postParams, "" /*lineBreak*/, "" /*indent*/);

    std::string response;
    gdriveHttpsRequest("/drive/v3/files?" + queryParams, {"Content-Type: application/json; charset=UTF-8"},
    {{CURLOPT_POSTFIELDS, postBuf.c_str()}}, [&](std::span<const char> buf) { response.append(buf.data(), buf.size()); },
    nullptr /*readRequest*/, nullptr /*receiveHeader*/, access); //throw SysError

    JsonValue jresponse;
    try { jresponse = parseJson(response); }
    catch (JsonParsingError&) {}

    const std::optional<std::string> itemId = getPrimitiveFromJsonObject(jresponse, "id");
    if (!itemId)
        throw SysError(formatGdriveErrorRaw(response));
    return *itemId;
}


//target name already existing? will (happily) create duplicate items => caller must check!
//can copy files + shortcuts (but fails for folders) + Google-specific file types (.gdoc, .gsheet, .gslides)
std::string /*fileId*/ gdriveCopyFile(const std::string& fileId, const std::string& parentIdTo, const Zstring& newName, time_t newModTime, const GdriveAccess& access) //throw SysError
{
    //https://developers.google.com/drive/api/v3/reference/files/copy
    const std::string queryParams = xWwwFormUrlEncode(
    {
        {"supportsAllDrives", "true"},
        {"fields", "id"},
    });

    //more Google Drive peculiarities: changing the file name changes modifiedTime!!! => workaround:

    //RFC 3339 date-time: e.g. "2018-09-29T08:39:12.053Z"
    const std::string modTimeRfc = utfTo<std::string>(formatTime(Zstr("%Y-%m-%dT%H:%M:%S.000Z"), getUtcTime(newModTime))); //returns empty string on error
    if (modTimeRfc.empty())
        throw SysError(L"Invalid modification time (time_t: " + numberTo<std::wstring>(newModTime) + L')');

    JsonValue postParams(JsonValue::Type::object);
    postParams.objectVal.emplace("name", utfTo<std::string>(newName));
    postParams.objectVal.emplace("parents", std::vector<JsonValue> {JsonValue(parentIdTo)});
    postParams.objectVal.emplace("modifiedTime", modTimeRfc);
    const std::string& postBuf = serializeJson(postParams, "" /*lineBreak*/, "" /*indent*/);

    std::string response;
    gdriveHttpsRequest("/drive/v3/files/" + fileId + "/copy?" + queryParams,
    {"Content-Type: application/json; charset=UTF-8"}, {{CURLOPT_POSTFIELDS, postBuf.c_str()}},
    [&](std::span<const char> buf) { response.append(buf.data(), buf.size()); },
    nullptr /*readRequest*/, nullptr /*receiveHeader*/, access); //throw SysError

    JsonValue jresponse;
    try { jresponse = parseJson(response); /*throw JsonParsingError*/ }
    catch (const JsonParsingError&) {}

    const std::optional<std::string> itemId = getPrimitiveFromJsonObject(jresponse, "id");
    if (!itemId)
        throw SysError(formatGdriveErrorRaw(response));

    return *itemId;

}


//target name already existing? will (happily) create duplicate items => caller must check!
void gdriveMoveAndRenameItem(const std::string& itemId, const std::string& parentIdFrom, const std::string& parentIdTo,
                             const Zstring& newName, time_t newModTime, const GdriveAccess& access) //throw SysError
{
    //https://developers.google.com/drive/api/v3/folder#moving_files_between_folders
    std::string queryParams = xWwwFormUrlEncode(
    {
        {"supportsAllDrives", "true"},
        {"fields", "name,parents"}, //for test if operation was successful
    });

    if (parentIdFrom != parentIdTo)
        queryParams += '&' + xWwwFormUrlEncode(
    {
        {"removeParents", parentIdFrom},
        {"addParents",    parentIdTo},
    });

    //more Google Drive peculiarities: changing the file name changes modifiedTime!!! => workaround:

    //RFC 3339 date-time: e.g. "2018-09-29T08:39:12.053Z"
    const std::string modTimeRfc = utfTo<std::string>(formatTime(Zstr("%Y-%m-%dT%H:%M:%S.000Z"), getUtcTime(newModTime))); //returns empty string on error
    if (modTimeRfc.empty())
        throw SysError(L"Invalid modification time (time_t: " + numberTo<std::wstring>(newModTime) + L')');

    JsonValue postParams(JsonValue::Type::object);
    postParams.objectVal.emplace("name", utfTo<std::string>(newName));
    postParams.objectVal.emplace("modifiedTime", modTimeRfc);
    const std::string& postBuf = serializeJson(postParams, "" /*lineBreak*/, "" /*indent*/);

    std::string response;
    gdriveHttpsRequest("/drive/v3/files/" + itemId + '?' + queryParams,
    {"Content-Type: application/json; charset=UTF-8"}, {{CURLOPT_CUSTOMREQUEST, "PATCH"}, {CURLOPT_POSTFIELDS, postBuf.c_str()}},
    [&](std::span<const char> buf) { response.append(buf.data(), buf.size()); },
    nullptr /*readRequest*/, nullptr /*receiveHeader*/, access); //throw SysError

    JsonValue jresponse;
    try { jresponse = parseJson(response); /*throw JsonParsingError*/ }
    catch (const JsonParsingError&) {}

    const std::optional<std::string> name    = getPrimitiveFromJsonObject(jresponse, "name");
    const JsonValue*                 parents = getChildFromJsonObject(jresponse, "parents");
    if (!name || *name != utfTo<std::string>(newName) ||
        !parents || parents->type != JsonValue::Type::array)
        throw SysError(formatGdriveErrorRaw(response));

    if (!std::any_of(parents->arrayVal.begin(), parents->arrayVal.end(),
    [&](const JsonValue& jval) { return jval.type == JsonValue::Type::string && jval.primVal == parentIdTo; }))
    throw SysError(formatSystemError("gdriveMoveAndRenameItem", L"", L"Google Drive internal failure.")); //user should never see this...
}


#if 0
void setModTime(const std::string& itemId, time_t modTime, const GdriveAccess& access) //throw SysError
{
    //https://developers.google.com/drive/api/v3/reference/files/update
    //RFC 3339 date-time: e.g. "2018-09-29T08:39:12.053Z"
    const std::string& modTimeRfc = formatTime<std::string>("%Y-%m-%dT%H:%M:%S.000Z", getUtcTime2(modTime)); //returns empty string on error
    if (modTimeRfc.empty())
        throw SysError(L"Invalid modification time (time_t: " + numberTo<std::wstring>(modTime) + L')');

    const std::string& queryParams = xWwwFormUrlEncode(
    {
        {"supportsAllDrives", "true"},
        {"fields", "modifiedTime"},
    });
    const std::string postBuf = R"({ "modifiedTime": ")" + modTimeRfc + "\" }";

    std::string response;
    gdriveHttpsRequest("/drive/v3/files/" + itemId + '?' + queryParams,
    {"Content-Type: application/json; charset=UTF-8"}, {{CURLOPT_CUSTOMREQUEST, "PATCH"}, {CURLOPT_POSTFIELDS, postBuf.c_str()}},
    [&](std::span<const char> buf) { response.append(buf.data(), buf.size()); },
    nullptr /*readRequest*/, nullptr /*receiveHeader*/, access); //throw SysError

    JsonValue jresponse;
    try { jresponse = parseJson(response); /*throw JsonParsingError*/ }
    catch (const JsonParsingError&) {}

    const std::optional<std::string> modifiedTime = getPrimitiveFromJsonObject(jresponse, "modifiedTime");
    if (!modifiedTime || *modifiedTime != modTimeRfc)
        throw SysError(formatGdriveErrorRaw(response));
}
#endif


DEFINE_NEW_SYS_ERROR(SysErrorAbusiveFile)
void gdriveDownloadFileImpl(const std::string& fileId, const std::function<void(const void* buffer, size_t bytesToWrite)>& writeBlock /*throw X*/, //throw SysError, SysErrorAbusiveFile, X
                            bool acknowledgeAbuse, const GdriveAccess& access)
{
    /*  https://developers.google.com/drive/api/v3/manage-downloads
        doesn't work for Google-specific file types, but Google Backup & Sync still "downloads" them:
            - in some JSON-like file format:
                {"url": "https://docs.google.com/open?id=FILE_ID", "doc_id": "FILE_ID", "email": "ACCOUNT_EMAIL"}

            - adds artificial file extensions: .gdoc, .gsheet, .gslides, ...

            - 2022-10-10: In "Google Drive for Desktop" the file content now looks like:
                {"":"WARNING! DO NOT EDIT THIS FILE! ANY CHANGES MADE WILL BE LOST!","doc_id":"FILE_ID","resource_key":"","email":"ACCOUNT_EMAIL"}     */

    std::string queryParams = xWwwFormUrlEncode(
    {
        {"supportsAllDrives", "true"},
        {"alt", "media"},
    });
    if (acknowledgeAbuse) //apply on demand only! https://freefilesync.org/forum/viewtopic.php?t=7520")
        queryParams += '&' + xWwwFormUrlEncode({{"acknowledgeAbuse", "true"}});

    std::string headBytes;
    bool headBytesWritten = false;

    const HttpSession::Result httpResult = gdriveHttpsRequest("/drive/v3/files/" + fileId + '?' + queryParams, {} /*extraHeaders*/, {} /*extraOptions*/,
                                                              [&](std::span<const char> buf)
                                                              /*  libcurl feeds us a shitload of tiny kB-sized zlib-decompressed pieces of data!
                                                                  libcurl's zlib buffer is sized at ridiculous 16 kB!
                                                                  => if this ever becomes a perf issue: roll our own zlib decompression!   */
    {
        if (headBytes.size() < 16 * 1024) //don't access writeBlock() yet in case of error! (=> support acknowledgeAbuse retry handling)
            headBytes.append(buf.data(), buf.size());
        else
        {
            if (!headBytesWritten)
            {
                headBytesWritten = true;
                writeBlock(headBytes.c_str(), headBytes.size()); //throw X
            }

            writeBlock(buf.data(), buf.size()); //throw X
        }
    }, nullptr /*tryReadRequest*/, nullptr /*receiveHeader*/, access); //throw SysError, X

    if (httpResult.statusCode / 100 != 2)
    {
        /* https://freefilesync.org/forum/viewtopic.php?t=7463 => HTTP status code 403 + body:
            { "error": { "errors": [{ "domain": "global",
                                      "reason": "cannotDownloadAbusiveFile",
                                      "message": "This file has been identified as malware or spam and cannot be downloaded." }],
                         "code": 403,
                         "message": "This file has been identified as malware or spam and cannot be downloaded." }}       */
        if (!headBytesWritten && httpResult.statusCode == 403 && contains(headBytes, "\"cannotDownloadAbusiveFile\""))
            throw SysErrorAbusiveFile(formatGdriveErrorRaw(headBytes));

        throw SysError(formatGdriveErrorRaw(headBytes));
    }

    if (!headBytesWritten && !headBytes.empty())
        writeBlock(headBytes.c_str(), headBytes.size()); //throw X
}


void gdriveDownloadFile(const std::string& fileId, const std::function<void(const void* buffer, size_t bytesToWrite)>& writeBlock /*throw X*/, //throw SysError, X
                        const GdriveAccess& access)
{
    try
    {
        gdriveDownloadFileImpl(fileId, writeBlock /*throw X*/, false /*acknowledgeAbuse*/, access); //throw SysError, SysErrorAbusiveFile, X
    }
    catch (SysErrorAbusiveFile&)
    {
        gdriveDownloadFileImpl(fileId, writeBlock /*throw X*/, true /*acknowledgeAbuse*/, access); //throw SysError, (SysErrorAbusiveFile), X
    }
}


#if 0
//file name already existing? => duplicate file created!
//note: Google Drive upload is already transactional!
//upload "small files" (5 MB or less; enforced by Google?) in a single round-trip
std::string /*itemId*/ gdriveUploadSmallFile(const Zstring& fileName, const std::string& parentId, uint64_t streamSize, std::optional<time_t> modTime, //throw SysError, X
                                             const std::function<size_t(void* buffer, size_t bytesToRead)>& readBlock /*throw X; return "bytesToRead" bytes unless end of stream*/,
                                             const GdriveAccess& access)
{
    //https://developers.google.com/drive/api/v3/folder#inserting_a_file_in_a_folder
    //https://developers.google.com/drive/api/v3/manage-uploads#http_1

    JsonValue postParams(JsonValue::Type::object);
    postParams.objectVal.emplace("name", utfTo<std::string>(fileName));
    postParams.objectVal.emplace("parents", std::vector<JsonValue> {JsonValue(parentId)});
    if (modTime) //convert to RFC 3339 date-time: e.g. "2018-09-29T08:39:12.053Z"
    {
        const std::string& modTimeRfc = utfTo<std::string>(formatTime(Zstr("%Y-%m-%dT%H:%M:%S.000Z"), getUtcTime2(*modTime))); //returns empty string on error
        if (modTimeRfc.empty())
            throw SysError(L"Invalid modification time (time_t: " + numberTo<std::wstring>(*modTime) + L')');

        postParams.objectVal.emplace("modifiedTime", modTimeRfc);
    }
    const std::string& metaDataBuf = serializeJson(postParams, "" /*lineBreak*/, "" /*indent*/);

    //allowed chars for border: DIGIT ALPHA ' ( ) + _ , - . / : = ?
    const std::string boundaryString = stringEncodeBase64(generateGUID() + generateGUID());

    const std::string postBufHead = "--" + boundaryString +                         "\r\n"
                                    "Content-Type: application/json; charset=UTF-8" "\r\n"
                                    /**/                                            "\r\n" +
                                    metaDataBuf +                                   "\r\n"
                                    "--" + boundaryString +                         "\r\n"
                                    "Content-Type: application/octet-stream"        "\r\n"
                                    /**/                                            "\r\n";

    const std::string postBufTail = "\r\n--" + boundaryString + "--";

    auto readMultipartBlock = [&, headPos = size_t(0), eof = false, tailPos = size_t(0)](void* buffer, size_t bytesToRead) mutable -> size_t
    {
        const auto bufStart = buffer;

        if (headPos < postBufHead.size())
        {
            const size_t junkSize = std::min<ptrdiff_t>(postBufHead.size() - headPos, bytesToRead);
            std::memcpy(buffer, postBufHead.c_str() + headPos, junkSize);
            headPos += junkSize;
            buffer = static_cast<std::byte*>(buffer) + junkSize;
            bytesToRead -= junkSize;
        }
        if (bytesToRead > 0)
        {
            if (!eof) //don't assume readBlock() will return streamSize bytes as promised => exhaust and let Google Drive fail if there is a mismatch in Content-Length!
            {
                const size_t bytesRead = readBlock(buffer, bytesToRead); //throw X; return "bytesToRead" bytes unless end of stream
                buffer = static_cast<std::byte*>(buffer) + bytesRead;
                bytesToRead -= bytesRead;

                if (bytesToRead > 0)
                    eof = true;
            }
            if (bytesToRead > 0)
                if (tailPos < postBufTail.size())
                {
                    const size_t junkSize = std::min<ptrdiff_t>(postBufTail.size() - tailPos, bytesToRead);
                    std::memcpy(buffer, postBufTail.c_str() + tailPos, junkSize);
                    tailPos += junkSize;
                    buffer = static_cast<std::byte*>(buffer) + junkSize;
                    bytesToRead -= junkSize;
                }
        }
        return static_cast<std::byte*>(buffer) -
               static_cast<std::byte*>(bufStart);
    };

TODO:
    gzip-compress HTTP request body!

    const std::string& queryParams = xWwwFormUrlEncode(
    {
        {"supportsAllDrives", "true"},
        {"uploadType", "multipart"},
    });
    std::string response;
    const HttpSession::Result httpResult = gdriveHttpsRequest("/upload/drive/v3/files?" + queryParams,
    {
        "Content-Type: multipart/related; boundary=" + boundaryString,
        "Content-Length: " + numberTo<std::string>(postBufHead.size() + streamSize + postBufTail.size())
    },
    {{CURLOPT_POST, 1}}, //otherwise HttpSession::perform() will PUT
    [&](std::span<const char> buf) { response.append(buf.data(), buf.size()); },
    readMultipartBlock, nullptr /*receiveHeader*/, access); //throw SysError, X

    JsonValue jresponse;
    try { jresponse = parseJson(response); }
    catch (JsonParsingError&) {}

    const std::optional<std::string> itemId = getPrimitiveFromJsonObject(jresponse, "id");
    if (!itemId)
        throw SysError(formatGdriveErrorRaw(response));

    return *itemId;
}
#endif


//file name already existing? => duplicate file created!
//note: Google Drive upload is already transactional!
std::string /*itemId*/ gdriveUploadFile(const Zstring& fileName, const std::string& parentId, std::optional<time_t> modTime, //throw SysError, X
                                        const std::function<size_t(void* buffer, size_t bytesToRead)>& tryReadBlock /*throw X*/, //returning 0 signals EOF: Posix read() semantics
                                        const GdriveAccess& access)
{
    //https://developers.google.com/drive/api/v3/folder#inserting_a_file_in_a_folder
    //https://developers.google.com/drive/api/v3/manage-uploads#resumable

    //step 1: initiate resumable upload session
    std::string uploadUrlRelative;
    {
        const std::string& queryParams = xWwwFormUrlEncode(
        {
            {"supportsAllDrives", "true"},
            {"uploadType", "resumable"},
        });
        JsonValue postParams(JsonValue::Type::object);
        postParams.objectVal.emplace("name", utfTo<std::string>(fileName));
        postParams.objectVal.emplace("parents", std::vector<JsonValue> {JsonValue(parentId)});
        if (modTime) //convert to RFC 3339 date-time: e.g. "2018-09-29T08:39:12.053Z"
        {
            const std::string& modTimeRfc = utfTo<std::string>(formatTime(Zstr("%Y-%m-%dT%H:%M:%S.000Z"), getUtcTime(*modTime))); //returns empty string on error
            if (modTimeRfc.empty())
                throw SysError(L"Invalid modification time (time_t: " + numberTo<std::wstring>(*modTime) + L')');

            postParams.objectVal.emplace("modifiedTime", modTimeRfc);
        }
        const std::string& postBuf = serializeJson(postParams, "" /*lineBreak*/, "" /*indent*/);
        //---------------------------------------------------

        std::string uploadUrl;

        auto onHeaderData = [&](const std::string_view& header)
        {
            //"The callback will be called once for each header and only complete header lines are passed on to the callback" (including \r\n at the end)
            if (startsWithAsciiNoCase(header, "Location:"))
            {
                uploadUrl = header;
                uploadUrl = afterFirst(uploadUrl, ':', IfNotFoundReturn::none);
                trim(uploadUrl);
            }
        };

        std::string response;
        const HttpSession::Result httpResult = gdriveHttpsRequest("/upload/drive/v3/files?" + queryParams,
        {"Content-Type: application/json; charset=UTF-8"}, {{CURLOPT_POSTFIELDS, postBuf.c_str()}},
        [&](std::span<const char> buf) { response.append(buf.data(), buf.size()); },
        nullptr /*readRequest*/, onHeaderData, access); //throw SysError

        if (httpResult.statusCode != 200)
            throw SysError(formatGdriveErrorRaw(response));

        if (!startsWith(uploadUrl, "https://www.googleapis.com/"))
            throw SysError(L"Invalid upload URL: " + utfTo<std::wstring>(uploadUrl)); //user should never see this

        uploadUrlRelative = afterFirst(uploadUrl, "googleapis.com", IfNotFoundReturn::none);
    }
    //---------------------------------------------------
    //step 2: upload file content

    //not officially documented, but Google Drive supports compressed file upload when "Content-Encoding: gzip" is set! :)))
    InputStreamAsGzip gzipStream(tryReadBlock, GDRIVE_BLOCK_SIZE_UPLOAD); //throw SysError

    auto readRequest = [&](std::span<char> buf) { return gzipStream.read(buf.data(), buf.size()); }; //throw SysError, X

    std::string response; //don't need "Authorization: Bearer":
    googleHttpsRequest(GOOGLE_REST_API_SERVER, uploadUrlRelative, { "Content-Encoding: gzip" }, {} /*extraOptions*/,
    [&](std::span<const char> buf) { response.append(buf.data(), buf.size()); }, readRequest,
    nullptr /*receiveHeader*/, access.timeoutSec); //throw SysError, X

    JsonValue jresponse;
    try { jresponse = parseJson(response); }
    catch (JsonParsingError&) {}

    const std::optional<std::string> itemId = getPrimitiveFromJsonObject(jresponse, "id");
    if (!itemId)
        throw SysError(formatGdriveErrorRaw(response));

    return *itemId;
}


class GdriveAccessBuffer //per-user-session & drive! => serialize access (perf: amortized fully buffered!)
{
public:
    //GdriveDrivesBuffer constructor calls GdriveAccessBuffer::getAccessToken()
    explicit GdriveAccessBuffer(const GdriveAccessInfo& accessInfo) :
        accessInfo_(accessInfo) {}

    GdriveAccessBuffer(MemoryStreamIn& stream) //throw SysError
    {
        accessInfo_.accessToken.validUntil = readNumber<int64_t>(stream);                             //
        accessInfo_.accessToken.value      = readContainer<std::string>(stream);                      //
        accessInfo_.refreshToken           = readContainer<std::string>(stream);                      //SysErrorUnexpectedEos
        accessInfo_.userInfo.displayName   = utfTo<std::wstring>(readContainer<std::string>(stream)); //
        accessInfo_.userInfo.email         =                     readContainer<std::string>(stream);  //
    }

    void serialize(MemoryStreamOut& stream) const
    {
        writeNumber<int64_t>(stream, accessInfo_.accessToken.validUntil);
        static_assert(sizeof(accessInfo_.accessToken.validUntil) <= sizeof(int64_t)); //ensure cross-platform compatibility!
        writeContainer(stream, accessInfo_.accessToken.value);
        writeContainer(stream, accessInfo_.refreshToken);
        writeContainer(stream, utfTo<std::string>(accessInfo_.userInfo.displayName));
        writeContainer(stream,                    accessInfo_.userInfo.email);
    }

    //set *before* calling any of the subsequent functions; see GdrivePersistentSessions::accessUserSession()
    void setContextTimeout(const std::weak_ptr<int>& timeoutSec) { timeoutSec_ = timeoutSec; }

    GdriveAccess getAccessToken() //throw SysError
    {
        const int timeoutSec = getTimeoutSec();

        if (accessInfo_.accessToken.validUntil <= std::time(nullptr) + timeoutSec + 5 /*some leeway*/) //expired/will expire
        {
            GdriveAccessToken token = gdriveRefreshAccess(accessInfo_.refreshToken, timeoutSec); //throw SysError

            //"there are limits on the number of refresh tokens that will be issued"
            //Google Drive access token is usually valid for one hour => fail on pathologic user-defined time out:
            if (token.validUntil <= std::time(nullptr) + 2 * timeoutSec)
                throw SysError(_("Please set up a shorter time out for Google Drive.") + L" [" + _P("1 sec", "%x sec", timeoutSec) + L']');

            accessInfo_.accessToken = std::move(token);
        }

        return {accessInfo_.accessToken.value, timeoutSec};
    }

    const std::string& getUserEmail() const { return accessInfo_.userInfo.email; }

    void update(const GdriveAccessInfo& accessInfo)
    {
        if (!equalAsciiNoCase(accessInfo.userInfo.email, accessInfo_.userInfo.email))
            throw std::logic_error(std::string(__FILE__) + '[' + numberTo<std::string>(__LINE__) + "] Contract violation!");
        accessInfo_ = accessInfo;
    }

private:
    GdriveAccessBuffer           (const GdriveAccessBuffer&) = delete;
    GdriveAccessBuffer& operator=(const GdriveAccessBuffer&) = delete;

    int getTimeoutSec() const
    {
        const std::shared_ptr<int> timeoutSec = timeoutSec_.lock();
        assert(timeoutSec);
        if (!timeoutSec)
            throw std::runtime_error(std::string(__FILE__) + '[' + numberTo<std::string>(__LINE__) + "] GdriveAccessBuffer: Timeout duration was not set.");

        return *timeoutSec;
    }

    GdriveAccessInfo accessInfo_;
    std::weak_ptr<int> timeoutSec_;
};


class GdriveDrivesBuffer;


class GdriveFileState //per-user-session! => serialize access (perf: amortized fully buffered!)
{
public:
    GdriveFileState(const std::string& driveId, //ID of shared drive or "My Drive": never empty!
                    const Zstring& sharedDriveName, //*empty* for "My Drive"
                    GdriveAccessBuffer& accessBuf) : //throw SysError
        /* issue getChangesCurrentToken() as the very first Google Drive query! */
        lastSyncToken_(getChangesCurrentToken(sharedDriveName.empty() ? std::string() : driveId, accessBuf.getAccessToken())), //throw SysError
        driveId_(driveId),
        sharedDriveName_(sharedDriveName),
        accessBuf_(accessBuf) { assert(!driveId.empty() && sharedDriveName != Zstr("My Drive")); }

    GdriveFileState(MemoryStreamIn& stream, GdriveAccessBuffer& accessBuf) : //throw SysError
        accessBuf_(accessBuf)
    {
        lastSyncToken_   = readContainer<std::string>(stream); //
        driveId_         = readContainer<std::string>(stream); //SysErrorUnexpectedEos
        sharedDriveName_ = utfTo<Zstring>(readContainer<std::string>(stream)); //

        for (;;)
        {
            const std::string folderId = readContainer<std::string>(stream); //SysErrorUnexpectedEos
            if (folderId.empty())
                break;
            folderContents_[folderId].isKnownFolder = true;
        }

        for (;;)
        {
            const std::string itemId = readContainer<std::string>(stream); //SysErrorUnexpectedEos
            if (itemId.empty())
                break;

            GdriveItemDetails details = {}; //read in correct sequence!
            details.itemName = utfTo<Zstring>(readContainer<std::string>(stream)); //
            details.type     = readNumber<GdriveItemType>(stream); //
            details.owner    = readNumber     <FileOwner>(stream); //
            details.fileSize = readNumber      <uint64_t>(stream); //SysErrorUnexpectedEos
            details.modTime  = static_cast<time_t>(readNumber<int64_t>(stream)); //
            details.targetId = readContainer<std::string>(stream); //

            size_t parentsCount = readNumber<uint32_t>(stream); //SysErrorUnexpectedEos
            while (parentsCount-- != 0)
                details.parentIds.push_back(readContainer<std::string>(stream)); //SysErrorUnexpectedEos

            updateItemState(itemId, &details);
        }
    }

    void serialize(MemoryStreamOut& stream) const
    {
        writeContainer(stream, lastSyncToken_);
        writeContainer(stream, driveId_);
        writeContainer(stream, utfTo<std::string>(sharedDriveName_));

        for (const auto& [folderId, content] : folderContents_)
            if (folderId.empty())
                throw std::logic_error(std::string(__FILE__) + '[' + numberTo<std::string>(__LINE__) + "] Contract violation!");
            else if (content.isKnownFolder)
                writeContainer(stream, folderId);
        writeContainer(stream, std::string()); //sentinel

        auto serializeItem = [&](const std::string& itemId, const GdriveItemDetails& details)
        {
            writeContainer             (stream, itemId);
            writeContainer             (stream, utfTo<std::string>(details.itemName));
            writeNumber<GdriveItemType>(stream, details.type);
            writeNumber     <FileOwner>(stream, details.owner);
            writeNumber      <uint64_t>(stream, details.fileSize);
            writeNumber       <int64_t>(stream, details.modTime);
            static_assert(sizeof(details.modTime) <= sizeof(int64_t)); //ensure cross-platform compatibility!
            writeContainer(stream, details.targetId);

            writeNumber(stream, static_cast<uint32_t>(details.parentIds.size()));
            for (const std::string& parentId : details.parentIds)
                writeContainer(stream, parentId);
        };

        //serialize + clean up: only save items in "known folders" + items referenced by shortcuts
        for (const auto& [folderId, content] : folderContents_)
            if (content.isKnownFolder)
                for (const auto& itItem : content.childItems)
                {
                    const auto& [itemId, details] = *itItem;
                    if (itemId.empty())
                        throw std::logic_error(std::string(__FILE__) + '[' + numberTo<std::string>(__LINE__) + "] Contract violation!");
                    serializeItem(itemId, details);

                    if (details.type == GdriveItemType::shortcut)
                    {
                        if (details.targetId.empty())
                            throw std::logic_error(std::string(__FILE__) + '[' + numberTo<std::string>(__LINE__) + "] Contract violation!");

                        if (auto it = itemDetails_.find(details.targetId);
                            it != itemDetails_.end())
                            serializeItem(details.targetId, it->second);
                    }
                }
        writeContainer(stream, std::string()); //sentinel
    }

    std::string getDriveId() const { return driveId_; }

    Zstring getSharedDriveName() const { return sharedDriveName_; } //*empty* for "My Drive"

    void setSharedDriveName(const Zstring& sharedDriveName) { sharedDriveName_ = sharedDriveName; }

    struct PathStatus
    {
        std::string existingItemId;
        GdriveItemType existingType = GdriveItemType::file;
        AfsPath existingPath;         //input path =: existingPath + relPath
        std::vector<Zstring> relPath; //
    };
    PathStatus getPathStatus(const std::string& locationRootId, const AfsPath& itemPath, bool followLeafShortcut) //throw SysError
    {
        const std::vector<Zstring> relPath = splitCpy(itemPath.value, FILE_NAME_SEPARATOR, SplitOnEmpty::skip);
        if (relPath.empty())
            return {locationRootId, GdriveItemType::folder, AfsPath(), {}};
        else
            return getPathStatusSub(locationRootId, AfsPath(), relPath, followLeafShortcut); //throw SysError
    }

    std::string /*itemId*/ getItemId(const std::string& locationRootId, const AfsPath& itemPath, bool followLeafShortcut) //throw SysError
    {
        const GdriveFileState::PathStatus& ps = getPathStatus(locationRootId, itemPath, followLeafShortcut); //throw SysError
        if (ps.relPath.empty())
            return ps.existingItemId;

        throw SysError(replaceCpy(_("%x does not exist."), L"%x", fmtPath(ps.relPath.front())));
    }

    std::pair<std::string /*itemId*/, GdriveItemDetails> getFileAttributes(const std::string& locationRootId, const AfsPath& itemPath, bool followLeafShortcut) //throw SysError
    {
        if (itemPath.value.empty()) //location root not covered by itemDetails_
        {
            GdriveItemDetails rootDetails
            {
                .type = GdriveItemType::folder,
                //.itemName =... => better leave empty for a root item!
                .owner = sharedDriveName_.empty() ? FileOwner::me : FileOwner::none,
            };
            return {locationRootId, std::move(rootDetails)};
        }

        const std::string itemId = getItemId(locationRootId, itemPath, followLeafShortcut); //throw SysError
        if (auto it = itemDetails_.find(itemId);
            it != itemDetails_.end())
            return *it;

        //itemId was already found! => (must either be a location root) or buffered in itemDetails_
        throw std::logic_error(std::string(__FILE__) + '[' + numberTo<std::string>(__LINE__) + "] Contract violation!");
    }

    std::optional<GdriveItemDetails> tryGetBufferedItemDetails(const std::string& itemId) const
    {
        if (auto it = itemDetails_.find(itemId);
            it != itemDetails_.end())
            return it->second;
        return {};
    }

    std::optional<std::vector<GdriveItem>> tryGetBufferedFolderContent(const std::string& folderId) const
    {
        auto it = folderContents_.find(folderId);
        if (it == folderContents_.end() || !it->second.isKnownFolder)
            return std::nullopt;

        std::vector<GdriveItem> childItems;
        for (auto itChild : it->second.childItems)
        {
            const auto& [childId, childDetails] = *itChild;
            childItems.push_back({childId, childDetails});
        }
        return std::move(childItems); //[!] need std::move!
    }

    //-------------- notifications --------------
    using ItemIdDelta = std::unordered_set<std::string>;

    struct FileStateDelta //as long as instance exists, GdriveItem will log all changed items
    {
        FileStateDelta() {}
    private:
        FileStateDelta(const std::shared_ptr<const ItemIdDelta>& cids) : changedIds(cids) {}
        friend class GdriveFileState;
        std::shared_ptr<const ItemIdDelta> changedIds; //lifetime is managed by caller; access *only* by GdriveFileState!
    };

    void notifyFolderContent(const FileStateDelta& stateDelta, const std::string& folderId, const std::vector<GdriveItem>& childItems)
    {
        folderContents_[folderId].isKnownFolder = true;

        for (const GdriveItem& item : childItems)
            notifyItemUpdated(stateDelta, item.itemId, &item.details);

        //- should we remove parent links for items that are not children of folderId anymore (as of this update)?? => fringe case during first update! (still: maybe trigger sync?)
        //- what if there are multiple folder state updates incoming in wrong order!? => notifyItemUpdated() will sort it out!
    }

    void notifyItemCreated(const FileStateDelta& stateDelta, const GdriveItem& item)
    {
        notifyItemUpdated(stateDelta, item.itemId, &item.details);
    }

    void notifyItemUpdated(const FileStateDelta& stateDelta, const GdriveItem& item)
    {
        notifyItemUpdated(stateDelta, item.itemId, &item.details);
    }

    void notifyFolderCreated(const FileStateDelta& stateDelta, const std::string& folderId, const Zstring& folderName, const std::string& parentId)
    {
        GdriveItemDetails details
        {
            .itemName = folderName,
            .modTime = std::time(nullptr),
            .type = GdriveItemType::folder,
            .owner = FileOwner::me,
            .parentIds{parentId},
        };

        //avoid needless conflicts due to different Google Drive folder modTime!
        if (auto it = itemDetails_.find(folderId); it != itemDetails_.end())
            details.modTime = it->second.modTime;

        notifyItemUpdated(stateDelta, folderId, &details);
    }

    void notifyShortcutCreated(const FileStateDelta& stateDelta, const std::string& shortcutId, const Zstring& shortcutName, const std::string& parentId, const std::string& targetId)
    {
        GdriveItemDetails details
        {
            .itemName = shortcutName,
            .modTime = std::time(nullptr),
            .type = GdriveItemType::shortcut,
            .owner = FileOwner::me,
            .targetId = targetId,
            .parentIds{parentId},
        };

        //avoid needless conflicts due to different Google Drive folder modTime!
        if (auto it = itemDetails_.find(shortcutId); it != itemDetails_.end())
            details.modTime = it->second.modTime;

        notifyItemUpdated(stateDelta, shortcutId, &details);
    }


    void notifyItemDeleted(const FileStateDelta& stateDelta, const std::string& itemId)
    {
        notifyItemUpdated(stateDelta, itemId, nullptr);
    }

    void notifyParentRemoved(const FileStateDelta& stateDelta, const std::string& itemId, const std::string& parentIdOld)
    {
        if (auto it = itemDetails_.find(itemId); it != itemDetails_.end())
        {
            GdriveItemDetails detailsNew = it->second;
            std::erase(detailsNew.parentIds, parentIdOld);
            notifyItemUpdated(stateDelta, itemId, &detailsNew);
        }
        else //conflict!!!
            markSyncDue();
    }

    void notifyMoveAndRename(const FileStateDelta& stateDelta, const std::string& itemId, const std::string& parentIdFrom, const std::string& parentIdTo, const Zstring& newName)
    {
        if (auto it = itemDetails_.find(itemId); it != itemDetails_.end())
        {
            GdriveItemDetails detailsNew = it->second;
            detailsNew.itemName = newName;

            std::erase_if(detailsNew.parentIds, [&](const std::string& id) { return id == parentIdFrom || id == parentIdTo; }); //
            detailsNew.parentIds.push_back(parentIdTo); //not a duplicate

            notifyItemUpdated(stateDelta, itemId, &detailsNew);
        }
        else //conflict!!!
            markSyncDue();
    }

private:
    GdriveFileState           (const GdriveFileState&) = delete;
    GdriveFileState& operator=(const GdriveFileState&) = delete;

    friend class GdriveDrivesBuffer;

    void notifyItemUpdated(const FileStateDelta& stateDelta, const std::string& itemId, const GdriveItemDetails* details)
    {
        if (!stateDelta.changedIds->contains(itemId)) //no conflicting changes in the meantime?
            updateItemState(itemId, details);         //=> accept new state data
        else //conflict?
        {
            auto it = itemDetails_.find(itemId);
            if (!details == (it == itemDetails_.end()))
                if (!details || *details == it->second)
                    return; //notified changes match our current file state
            //else: conflict!!! unclear which has the more recent data!
            markSyncDue();
        }
    }

    FileStateDelta registerFileStateDelta()
    {
        auto deltaPtr = std::make_shared<ItemIdDelta>();
        changeLog_.push_back(deltaPtr);
        return FileStateDelta(deltaPtr);
    }

    bool syncIsDue() const { return std::chrono::steady_clock::now() >= lastSyncTime_ + GDRIVE_SYNC_INTERVAL; }

    void markSyncDue() { lastSyncTime_ = std::chrono::steady_clock::now() - GDRIVE_SYNC_INTERVAL; }

    void syncWithGoogle() //throw SysError
    {
        const ChangesDelta delta = getChangesDelta(sharedDriveName_.empty() ? std::string() : driveId_, lastSyncToken_, accessBuf_.getAccessToken()); //throw SysError

        for (const FileChange& change : delta.fileChanges)
            updateItemState(change.itemId, get(change.details));

        lastSyncToken_ = delta.newStartPageToken;
        lastSyncTime_ = std::chrono::steady_clock::now();

        //good to know: if item is created and deleted between polling for changes it is still reported as deleted by Google!
        //Same goes for any other change that is undone in between change notification syncs.
    }

    PathStatus getPathStatusSub(const std::string& folderId, const AfsPath& folderPath, const std::vector<Zstring>& relPath, bool followLeafShortcut) //throw SysError
    {
        assert(!relPath.empty());

        auto itKnown = folderContents_.find(folderId);
        if (itKnown == folderContents_.end() || !itKnown->second.isKnownFolder)
        {
            notifyFolderContent(registerFileStateDelta(), folderId, readFolderContent(folderId, accessBuf_.getAccessToken())); //throw SysError
            //perf: always buffered, except for direct, first-time folder access!
            itKnown = folderContents_.find(folderId);
            assert(itKnown != folderContents_.end());
            if (!itKnown->second.isKnownFolder)
                throw std::logic_error(std::string(__FILE__) + '[' + numberTo<std::string>(__LINE__) + "] Contract violation!");
        }

        auto itFound = itemDetails_.cend();
        for (const DetailsIterator& itChild : itKnown->second.childItems)
            //Since Google Drive has no concept of a file path, we have to roll our own "path to ID" mapping => let's use the platform-native style
            if (equalNativePath(itChild->second.itemName, relPath.front()))
            {
                if (itFound != itemDetails_.end())
                    throw SysError(replaceCpy(_("The name %x is used by more than one item in the folder."), L"%x", fmtPath(relPath.front())));

                itFound = itChild;
            }

        if (itFound == itemDetails_.end())
            return {folderId, GdriveItemType::folder, folderPath, relPath}; //always a folder, see check before recursion above
        else
        {
            auto getItemDetailsBuffered = [&](const std::string& itemId) -> const GdriveItemDetails&
            {
                auto it = itemDetails_.find(itemId);
                if (it == itemDetails_.end())
                {
                    notifyItemUpdated(registerFileStateDelta(), {itemId, getItemDetails(itemId, accessBuf_.getAccessToken())}); //throw SysError
                    //perf: always buffered, except for direct, first-time folder access!
                    it = itemDetails_.find(itemId);
                    assert(it != itemDetails_.end());
                }
                return it->second;
            };

            const auto& [childId, childDetails] = *itFound;
            const AfsPath              childItemPath(appendPath(folderPath.value, relPath.front()));
            const std::vector<Zstring> childRelPath(relPath.begin() + 1, relPath.end());

            if (childRelPath.empty())
            {
                if (childDetails.type == GdriveItemType::shortcut && followLeafShortcut)
                    return {childDetails.targetId, getItemDetailsBuffered(childDetails.targetId).type, childItemPath, childRelPath};
                else
                    return {childId, childDetails.type, childItemPath, childRelPath};
            }

            switch (childDetails.type)
            {
                case GdriveItemType::file: //parent/file/child-rel-path... => obscure, but possible
                    throw SysError(replaceCpy(_("The name %x is already used by another item."), L"%x", fmtPath(AFS::getItemName(childItemPath))));

                case GdriveItemType::folder:
                    return getPathStatusSub(childId, childItemPath, childRelPath, followLeafShortcut); //throw SysError

                case GdriveItemType::shortcut:
                    switch (getItemDetailsBuffered(childDetails.targetId).type)
                    {
                        case GdriveItemType::file: //parent/file-symlink/child-rel-path... => obscure, but possible
                            throw SysError(replaceCpy(_("The name %x is already used by another item."), L"%x", fmtPath(AFS::getItemName(childItemPath))));

                        case GdriveItemType::folder: //parent/folder-symlink/child-rel-path... => always follow
                            return getPathStatusSub(childDetails.targetId, childItemPath, childRelPath, followLeafShortcut); //throw SysError

                        case GdriveItemType::shortcut: //should never happen: creating shortcuts to shortcuts fails with "Internal Error"
                            throw SysError(replaceCpy<std::wstring>(L"Google Drive Shortcut %x is pointing to another Shortcut.", L"%x", fmtPath(AFS::getItemName(childItemPath))));
                    }
                    break;
            }
            throw std::logic_error(std::string(__FILE__) + '[' + numberTo<std::string>(__LINE__) + "] Contract violation!");
        }
    }

    void updateItemState(const std::string& itemId, const GdriveItemDetails* details)
    {
        auto it = itemDetails_.find(itemId);
        if (!details == (it == itemDetails_.end()))
            if (!details || *details == it->second) //notified changes match our current file state
                return; //=> avoid misleading changeLog_ entries after Google Drive sync!!!

        //update change logs (and clean up obsolete entries)
        std::erase_if(changeLog_, [&](std::weak_ptr<ItemIdDelta>& weakPtr)
        {
            if (std::shared_ptr<ItemIdDelta> iid = weakPtr.lock())
            {
                (*iid).insert(itemId);
                return false;
            }
            else
                return true;
        });

        //update file state
        if (details)
        {
            if (it != itemDetails_.end()) //update
            {
                if (it->second.type != details->type)
                    throw std::logic_error(std::string(__FILE__) + '[' + numberTo<std::string>(__LINE__) + "] Contract violation!"); //WTF!?

                std::vector<std::string> parentIdsNew     = details->parentIds;
                std::vector<std::string> parentIdsRemoved = it->second.parentIds;
                std::erase_if(parentIdsNew,     [&](const std::string& id) { return std::find(it->second.parentIds.begin(), it->second.parentIds.end(), id) != it->second.parentIds.end(); });
                std::erase_if(parentIdsRemoved, [&](const std::string& id) { return std::find(details->parentIds.begin(), details->parentIds.end(), id) != details->parentIds.end(); });

                for (const std::string& parentId : parentIdsNew)
                    folderContents_[parentId].childItems.push_back(it); //new insert => no need for duplicate check

                for (const std::string& parentId : parentIdsRemoved)
                    if (auto itP = folderContents_.find(parentId); itP != folderContents_.end())
                        std::erase(itP->second.childItems, it);
                //if all parents are removed, Google Drive will (recursively) delete the item => don't prematurely do this now: wait for change notifications!
                //OR: item without parents located in "Shared with me", but referenced via Shortcut => don't remove!!!

                it->second = *details;
            }
            else //create
            {
                auto itNew = itemDetails_.emplace(itemId, *details).first;

                for (const std::string& parentId : details->parentIds)
                    folderContents_[parentId].childItems.push_back(itNew); //new insert => no need for duplicate check
            }
        }
        else //delete
        {
            if (it != itemDetails_.end())
            {
                for (const std::string& parentId : it->second.parentIds) //1. delete from parent folders
                    if (auto itP = folderContents_.find(parentId); itP != folderContents_.end())
                        std::erase(itP->second.childItems, it);

                itemDetails_.erase(it);
            }

            if (auto itP = folderContents_.find(itemId); itP != folderContents_.end())
            {
                //2. delete as parent from child items (don't wait for change notifications of children)
                //  what if e.g. single change notification "folder removed", then folder reapears,
                //  and no notifications for child items: possible with Google drive!?
                //  => no problem: FolderContent::isKnownFolder will be false for this restored folder => only a rescan needed
                for (auto itChild : itP->second.childItems)
                    std::erase(itChild->second.parentIds, itemId);
                folderContents_.erase(itP);
            }
        }
    }

    using DetailsIterator = std::unordered_map<std::string, GdriveItemDetails>::iterator;

    struct FolderContent
    {
        bool isKnownFolder = false; //:= we've seen its full content at least once; further changes are calculated via change notifications
        std::vector<DetailsIterator> childItems;
    };
    std::unordered_map<std::string /*folderId*/, FolderContent> folderContents_;
    std::unordered_map<std::string /*itemId*/, GdriveItemDetails> itemDetails_; //contains ALL known, existing items!

    std::string lastSyncToken_; //drive-specific(!) marker corresponding to last sync with Google's change notifications
    std::chrono::steady_clock::time_point lastSyncTime_ = std::chrono::steady_clock::now() - GDRIVE_SYNC_INTERVAL; //... with Google Drive (default: sync is due)

    std::vector<std::weak_ptr<ItemIdDelta>> changeLog_; //track changed items since FileStateDelta was created (includes sync with Google + our own intermediate change notifications)

    std::string driveId_; //ID of shared drive or "My Drive": never empty!
    Zstring sharedDriveName_; //name of shared drive: empty for "My Drive"!

    GdriveAccessBuffer& accessBuf_;
};


class GdriveFileStateAtLocation
{
public:
    GdriveFileStateAtLocation(GdriveFileState& fileState, const std::string& locationRootId) : fileState_(fileState), locationRootId_(locationRootId) {}

    GdriveFileState::PathStatus getPathStatus(const AfsPath& itemPath, bool followLeafShortcut) //throw SysError
    {
        return fileState_.getPathStatus(locationRootId_, itemPath, followLeafShortcut); //throw SysError
    }

    std::string /*itemId*/ getItemId(const AfsPath& itemPath, bool followLeafShortcut) //throw SysError
    {
        return fileState_.getItemId(locationRootId_, itemPath, followLeafShortcut); //throw SysError
    }

    std::pair<std::string /*itemId*/, GdriveItemDetails> getFileAttributes(const AfsPath& itemPath, bool followLeafShortcut) //throw SysError
    {
        return fileState_.getFileAttributes(locationRootId_, itemPath, followLeafShortcut); //throw SysError
    }

    GdriveFileState& all() { return fileState_; }

private:
    GdriveFileState& fileState_;
    const std::string locationRootId_;
};


class GdriveDrivesBuffer
{
public:
    explicit GdriveDrivesBuffer(GdriveAccessBuffer& accessBuf) :
        accessBuf_(accessBuf),
        myDrive_(getMyDriveId(accessBuf.getAccessToken()), Zstring() /*sharedDriveName*/, accessBuf) {} //throw SysError

    GdriveDrivesBuffer(MemoryStreamIn& stream, GdriveAccessBuffer& accessBuf) : //throw SysError
        accessBuf_(accessBuf),
        myDrive_(stream, accessBuf) //throw SysError
    {
        size_t sharedDrivesCount = readNumber<uint32_t>(stream); //SysErrorUnexpectedEos
        while (sharedDrivesCount-- != 0)
        {
            auto fileState = makeSharedRef<GdriveFileState>(stream, accessBuf); //throw SysError
            sharedDrives_.emplace(fileState.ref().getDriveId(), fileState);
        }
    }

    void serialize(MemoryStreamOut& stream) const
    {
        myDrive_.serialize(stream);

        writeNumber(stream, static_cast<uint32_t>(sharedDrives_.size()));
        for (const auto& [driveId, fileState] : sharedDrives_)
            fileState.ref().serialize(stream);

        //starredFolders_? no, will be fully restored by syncWithGoogle()
    }

    std::vector<Zstring /*locationName*/> listLocations() //throw SysError
    {
        if (syncIsDue())
            syncWithGoogle(); //throw SysError

        std::vector<Zstring> locationNames;

        for (const auto& [driveId, fileState] : sharedDrives_)
            locationNames.push_back(fileState.ref().getSharedDriveName());

        for (const StarredFolderDetails& sfd : starredFolders_)
            locationNames.push_back(sfd.folderName);

        return locationNames;
    }

    std::pair<GdriveFileStateAtLocation, GdriveFileState::FileStateDelta> prepareAccess(const Zstring& locationName) //throw SysError
    {
        //checking for added/renamed/deleted shared drives *every* GDRIVE_SYNC_INTERVAL is needlessly excessive!
        //  => check 1. once per FFS run
        //           2. on drive access error
        if (lastSyncTime_ == std::chrono::steady_clock::time_point())
            syncWithGoogle(); //throw SysError

        GdriveFileStateAtLocation fileState = [&]
        {
            try
            {
                return getFileState(locationName); //throw SysError
            }
            catch (SysError&)
            {
                if (syncIsDue())
                    syncWithGoogle(); //throw SysError

                return getFileState(locationName); //throw SysError
            }
        }();

        //manage last sync time here so that "lastSyncToken" remains stable while accessing GdriveFileState in the callback
        if (fileState.all().syncIsDue())
            fileState.all().syncWithGoogle(); //throw SysError

        return {fileState, fileState.all().registerFileStateDelta()};
    }

private:
    bool syncIsDue() const { return std::chrono::steady_clock::now() >= lastSyncTime_ + GDRIVE_SYNC_INTERVAL; }

    void syncWithGoogle() //throw SysError
    {
        //run in parallel with getSharedDrives()
        auto ftStarredFolders = runAsync([access = accessBuf_.getAccessToken() /*throw SysError*/] { return getStarredFolders(access); /*throw SysError*/ });

        decltype(sharedDrives_) currentDrives;

        //getSharedDrives() should be fast enough to avoid the unjustified complexity of change notifications: https://freefilesync.org/forum/viewtopic.php?t=7827&start=30#p29712
        for (const auto& [driveId, driveName] : getSharedDrives(accessBuf_.getAccessToken())) //throw SysError
        {
            auto fileState = [&, &driveId /*clang bug*/= driveId, &driveName /*clang bug*/= driveName]
            {
                if (auto it = sharedDrives_.find(driveId);
                    it != sharedDrives_.end())
                {
                    it->second.ref().setSharedDriveName(driveName);
                    return it->second;
                }
                else
                    return makeSharedRef<GdriveFileState>(driveId, driveName, accessBuf_); //throw SysError
            }();
            currentDrives.emplace(driveId, fileState);
        }

        starredFolders_ = ftStarredFolders.get(); //throw SysError //
        sharedDrives_.swap(currentDrives);                         //transaction!
        lastSyncTime_ = std::chrono::steady_clock::now(); //...(uhm, mostly, except for setSharedDriveName())
    }

    GdriveFileStateAtLocation getFileState(const Zstring& locationName) //throw SysError
    {
        if (locationName.empty())
            return {myDrive_, myDrive_.getDriveId()};

        GdriveFileState* fileState = nullptr;
        std::string locationRootId;

        for (auto& [driveId, fileStateRef] : sharedDrives_)
            if (equalNativePath(fileStateRef.ref().getSharedDriveName(), locationName))
            {
                if (fileState)
                    throw SysError(replaceCpy(_("The name %x is used by more than one item in the folder."), L"%x", fmtPath(locationName)));

                fileState = &fileStateRef.ref();
                locationRootId = driveId;
            }

        for (const StarredFolderDetails& sfd : starredFolders_)
            if (equalNativePath(sfd.folderName, locationName))
            {
                if (fileState)
                    throw SysError(replaceCpy(_("The name %x is used by more than one item in the folder."), L"%x", fmtPath(locationName)));

                if (sfd.sharedDriveId.empty()) //=> My Drive
                    fileState = &myDrive_;
                else
                {
                    auto it = sharedDrives_.find(sfd.sharedDriveId);
                    if (it == sharedDrives_.end())
                        break;

                    fileState = &it->second.ref();
                }
                locationRootId = sfd.folderId;
            }

        if (!fileState)
            throw SysError(replaceCpy(_("%x does not exist."), L"%x", fmtPath(locationName)));

        return {*fileState, locationRootId};
    }

    GdriveAccessBuffer& accessBuf_;
    std::chrono::steady_clock::time_point lastSyncTime_; //... with Google Drive (default: sync is due)

    GdriveFileState myDrive_;
    std::unordered_map<std::string /*drive ID*/, SharedRef<GdriveFileState>> sharedDrives_;

    std::vector<StarredFolderDetails> starredFolders_;
};

//==========================================================================================
//==========================================================================================

class GdrivePersistentSessions
{
public:
    explicit GdrivePersistentSessions(const Zstring& configDirPath) : configDirPath_(configDirPath)
    {
        onSystemShutdownRegister(onBeforeSystemShutdownCookie_);
    }

    void saveActiveSessions() //throw FileError
    {
        std::vector<Protected<SessionHolder>*> protectedSessions; //pointers remain stable, thanks to std::unordered_map<>
        globalSessions_.access([&](GlobalSessions& sessions)
        {
            for (auto& [accountEmail, protectedSession] : sessions)
                protectedSessions.push_back(&protectedSession);
        });

        if (!protectedSessions.empty())
        {
            createDirectoryIfMissingRecursion(configDirPath_); //throw FileError

            std::exception_ptr firstError;

            //access each session outside the globalSessions_ lock!
            for (Protected<SessionHolder>* protectedSession : protectedSessions)
                protectedSession->access([&](SessionHolder& holder)
            {
                if (holder.session)
                    try
                    {
                        const Zstring dbFilePath = getDbFilePath(holder.session->accessBuf.ref().getUserEmail());
                        saveSession(dbFilePath, *holder.session); //throw FileError
                    }
                    catch (FileError&) { if (!firstError) firstError = std::current_exception(); }
            });

            if (firstError)
                std::rethrow_exception(firstError); //throw FileError
        }
    }

    std::string addUserSession(const std::string& gdriveLoginHint, const std::function<void()>& updateGui /*throw X*/, int timeoutSec) //throw SysError, X
    {
        const GdriveAccessInfo accessInfo = gdriveAuthorizeAccess(gdriveLoginHint, updateGui, timeoutSec); //throw SysError, X

        accessUserSession(accessInfo.userInfo.email, timeoutSec, [&](std::optional<UserSession>& userSession) //throw SysError
        {
            if (userSession)
                userSession->accessBuf.ref().update(accessInfo); //redundant?
            else
            {
                const std::shared_ptr<int> timeoutSec2 = std::make_shared<int>(timeoutSec); //context option: valid only for duration of this call!
                auto accessBuf = makeSharedRef<GdriveAccessBuffer>(accessInfo);
                accessBuf.ref().setContextTimeout(timeoutSec2); //[!] used by GdriveDrivesBuffer()!
                auto drivesBuf = makeSharedRef<GdriveDrivesBuffer>(accessBuf.ref()); //throw SysError
                userSession = {accessBuf, drivesBuf};
            }
        });

        return accessInfo.userInfo.email;
    }

    void removeUserSession(const std::string& accountEmail, int timeoutSec) //throw SysError
    {
        try
        {
            accessUserSession(accountEmail, timeoutSec, [&](std::optional<UserSession>& userSession) //throw SysError
            {
                if (userSession)
                    gdriveRevokeAccess(userSession->accessBuf.ref().getAccessToken()); //throw SysError
            });
        }
        catch (SysError&) { assert(false); } //best effort: try to invalidate the access token
        //=> expected to fail 1. if offline => not worse than removing FFS via "Uninstall Programs" 2. already revoked 3. if DB is corrupted

        try
        {
            //start with deleting the DB file (1. maybe it's corrupted? 2. skip unnecessary lazy-load)
            const Zstring dbFilePath = getDbFilePath(accountEmail);
            try
            {
                removeFilePlain(dbFilePath); //throw FileError
            }
            catch (FileError&)
            {
                if (itemExists(dbFilePath)) //throw FileError
                    throw;
            }
        }
        catch (const FileError& e) { throw SysError(replaceCpy(e.toString(), L"\n\n", L'\n')); } //file access errors should be further enriched by context info => SysError


        accessUserSession(accountEmail, timeoutSec, [&](std::optional<UserSession>& userSession) //throw SysError
        {
            userSession.reset();
        });
    }

    std::vector<std::string /*account email*/> listAccounts() //throw SysError
    {
        std::vector<std::string> emails;

        std::vector<Protected<SessionHolder>*> protectedSessions; //pointers remain stable, thanks to std::unordered_map<>
        globalSessions_.access([&](GlobalSessions& sessions)
        {
            for (auto& [accountEmail, protectedSession] : sessions)
                protectedSessions.push_back(&protectedSession);
        });

        //access each session outside the globalSessions_ lock!
        for (Protected<SessionHolder>* protectedSession : protectedSessions)
            protectedSession->access([&](SessionHolder& holder)
        {
            if (holder.session)
                emails.push_back(holder.session->accessBuf.ref().getUserEmail());
        });

        //also include available, but not-yet-loaded sessions
        try
        {
            traverseFolder(configDirPath_,
            [&](const    FileInfo& fi) { if (endsWith(fi.itemName, Zstr(".db"))) emails.push_back(utfTo<std::string>(beforeLast(fi.itemName, Zstr('.'), IfNotFoundReturn::none))); },
            [&](const  FolderInfo& fi) {},
            [&](const SymlinkInfo& si) {}); //throw FileError
        }
        catch (FileError&)
        {
            try
            {
                if (itemExists(configDirPath_)) //throw FileError
                    throw;
            }
            catch (const FileError& e) { throw SysError(replaceCpy(e.toString(), L"\n\n", L'\n')); } //file access errors should be further enriched by context info => SysError
        }

        removeDuplicates(emails, LessAsciiNoCase());
        return emails;
    }

    std::vector<Zstring /*locationName*/> listLocations(const std::string& accountEmail, int timeoutSec) //throw SysError
    {
        std::vector<Zstring> locationNames;

        accessUserSession(accountEmail, timeoutSec, [&](std::optional<UserSession>& userSession) //throw SysError
        {
            if (!userSession)
                throw SysError(replaceCpy(_("Please add a connection to user account %x first."), L"%x", utfTo<std::wstring>(accountEmail)));

            locationNames = userSession->drivesBuf.ref().listLocations(); //throw SysError
        });
        return locationNames;
    }

    struct AsyncAccessInfo
    {
        GdriveAccess access; //don't allow (long-running) web requests while holding the global session lock!
        GdriveFileState::FileStateDelta stateDelta;
    };
    //perf: amortized fully buffered!
    AsyncAccessInfo accessGlobalFileState(const GdriveLogin& login, const std::function<void(GdriveFileStateAtLocation& fileState)>& useFileState /*throw X*/) //throw SysError, X
    {
        GdriveAccess access;
        GdriveFileState::FileStateDelta stateDelta;

        accessUserSession(login.email, login.timeoutSec, [&](std::optional<UserSession>& userSession) //throw SysError
        {
            if (!userSession)
                throw SysError(replaceCpy(_("Please add a connection to user account %x first."), L"%x", utfTo<std::wstring>(login.email)));

            access                        = userSession->accessBuf.ref().getAccessToken(); //throw SysError
            auto [fileState, stateDelta2] = userSession->drivesBuf.ref().prepareAccess(login.locationName); //throw SysError
            stateDelta = std::move(stateDelta2);

            useFileState(fileState); //throw X
        });
        return {access, stateDelta};
    }

private:
    GdrivePersistentSessions           (const GdrivePersistentSessions&) = delete;
    GdrivePersistentSessions& operator=(const GdrivePersistentSessions&) = delete;

    struct UserSession;

    Zstring getDbFilePath(std::string accountEmail) const
    {
        for (char& c : accountEmail)
            c = asciiToLower(c);
        //return appendPath(configDirPath_, utfTo<Zstring>(formatAsHexString(getMd5(utfTo<std::string>(accountEmail)))) + Zstr(".db"));
        return appendPath(configDirPath_, utfTo<Zstring>(accountEmail) + Zstr(".db"));
    }

    void accessUserSession(const std::string& accountEmail, int timeoutSec, const std::function<void(std::optional<UserSession>& userSession)>& useSession /*throw X*/) //throw SysError, X
    {
        Protected<SessionHolder>* protectedSession = nullptr; //pointers remain stable, thanks to std::unordered_map<>
        globalSessions_.access([&](GlobalSessions& sessions) { protectedSession = &sessions[accountEmail]; });

        protectedSession->access([&](SessionHolder& holder)
        {
            if (!holder.dbWasLoaded) //let's NOT load the DB files under the globalSessions_ lock, but the session-specific one!
                try
                {
                    holder.session = loadSession(getDbFilePath(accountEmail), timeoutSec); //throw SysError
                }
                catch (const FileError& e) { throw SysError(replaceCpy(e.toString(), L"\n\n", L'\n')); } //GdrivePersistentSessions errors should be further enriched with context info => SysError
            holder.dbWasLoaded = true;

            const std::shared_ptr<int> timeoutSec2 = std::make_shared<int>(timeoutSec); //context option: valid only for duration of this call!
            if (holder.session)
                holder.session->accessBuf.ref().setContextTimeout(timeoutSec2);

            useSession(holder.session); //throw X
        });
    }

    static void saveSession(const Zstring& dbFilePath, const UserSession& userSession) //throw FileError
    {
        MemoryStreamOut streamOut;
        writeArray(streamOut, DB_FILE_DESCR, sizeof(DB_FILE_DESCR));
        writeNumber<int32_t>(streamOut, DB_FILE_VERSION);

        MemoryStreamOut streamOutBody;
        userSession.accessBuf.ref().serialize(streamOutBody);
        userSession.drivesBuf.ref().serialize(streamOutBody);

        try
        {
            streamOut.ref() += compress(streamOutBody.ref(), 3 /*best compression level: see db_file.cpp*/); //throw SysError
        }
        catch (const SysError& e) { throw FileError(replaceCpy(_("Cannot write file %x."), L"%x", fmtPath(dbFilePath)), e.toString()); }

        setFileContent(dbFilePath, streamOut.ref(), nullptr /*notifyUnbufferedIO*/); //throw FileError
    }

    static std::optional<UserSession> loadSession(const Zstring& dbFilePath, int timeoutSec) //throw FileError
    {
        std::string byteStream;
        try
        {
            byteStream = getFileContent(dbFilePath, nullptr /*notifyUnbufferedIO*/); //throw FileError
        }
        catch (FileError&)
        {
            if (itemExists(dbFilePath)) //throw FileError
                throw;

            return std::nullopt;
        }

        try
        {
            MemoryStreamIn streamIn(byteStream);
            //-------- file format header --------
            char tmp[sizeof(DB_FILE_DESCR)] = {};
            readArray(streamIn, &tmp, sizeof(tmp)); //throw SysErrorUnexpectedEos

            const std::shared_ptr<int> timeoutSec2 = std::make_shared<int>(timeoutSec); //context option: valid only for duration of this call!

            //TODO: remove migration code at some time! 2020-07-03
            if (!std::equal(std::begin(tmp), std::end(tmp), std::begin(DB_FILE_DESCR)))
            {
                const std::string& uncompressedStream = decompress(byteStream); //throw SysError
                MemoryStreamIn streamIn2(uncompressedStream);
                //-------- file format header --------
                const char DB_FILE_DESCR_OLD[] = "FreeFileSync: Google Drive Database";
                char tmp2[sizeof(DB_FILE_DESCR_OLD)] = {};
                readArray(streamIn2, &tmp2, sizeof(tmp2)); //throw SysErrorUnexpectedEos

                if (!std::equal(std::begin(tmp2), std::end(tmp2), std::begin(DB_FILE_DESCR_OLD)))
                    throw SysError(_("File content is corrupted.") + L" (invalid header)");

                const int version = readNumber<int32_t>(streamIn2); //throw SysErrorUnexpectedEos
                if (version != 1 && //TODO: remove migration code at some time! 2019-12-05
                    version != 2 && //TODO: remove migration code at some time! 2020-06-11
                    version != 3)   //TODO: remove migration code at some time! 2020-07-03
                    throw SysError(_("Unsupported data format.") + L' ' + replaceCpy(_("Version: %x"), L"%x", numberTo<std::wstring>(version)));

                //version 1 + 2: fully discard old state due to missing "ownedByMe" attribute + shortcut support
                //version 3:     fully discard old state due to revamped shared drive handling
                auto accessBuf = makeSharedRef<GdriveAccessBuffer>(streamIn2); //throw SysError
                accessBuf.ref().setContextTimeout(timeoutSec2); //not used by GdriveDrivesBuffer(), but let's be consistent
                auto drivesBuf = makeSharedRef<GdriveDrivesBuffer>(accessBuf.ref()); //throw SysError
                return UserSession{accessBuf, drivesBuf};
            }
            else
            {
                if (!std::equal(std::begin(tmp), std::end(tmp), std::begin(DB_FILE_DESCR)))
                    throw SysError(_("File content is corrupted.") + L" (invalid header)");

                const int version = readNumber<int32_t>(streamIn); //throw SysErrorUnexpectedEos
                if (version != 4 &&
                    version != DB_FILE_VERSION)
                    throw SysError(_("Unsupported data format.") + L' ' + replaceCpy(_("Version: %x"), L"%x", numberTo<std::wstring>(version)));

                const std::string& uncompressedStream = decompress(makeStringView(byteStream.begin() + streamIn.pos(), byteStream.end())); //throw SysError
                MemoryStreamIn streamInBody(uncompressedStream);

                auto accessBuf = makeSharedRef<GdriveAccessBuffer>(streamInBody); //throw SysError
                accessBuf.ref().setContextTimeout(timeoutSec2); //not used by GdriveDrivesBuffer(), but let's be consistent
                auto drivesBuf = [&]
                {
                    //TODO: remove migration code at some time! 2021-05-15
                    if (version <= 4) //fully discard old state due to revamped shared drive handling
                        return makeSharedRef<GdriveDrivesBuffer>(accessBuf.ref()); //throw SysError
                    else
                        return makeSharedRef<GdriveDrivesBuffer>(streamInBody, accessBuf.ref()); //throw SysError
                }();

                return UserSession{accessBuf, drivesBuf};
            }
        }
        catch (const SysError& e)
        {
            throw FileError(replaceCpy(_("Cannot read database file %x."), L"%x", fmtPath(dbFilePath)), e.toString());
        }
    }

    struct UserSession
    {
        SharedRef<GdriveAccessBuffer> accessBuf;
        SharedRef<GdriveDrivesBuffer> drivesBuf;
    };

    struct SessionHolder
    {
        bool dbWasLoaded = false;
        std::optional<UserSession> session;
    };
    using GlobalSessions = std::unordered_map<std::string /*Google account email*/, Protected<SessionHolder>, StringHashAsciiNoCase, StringEqualAsciiNoCase>;

    Protected<GlobalSessions> globalSessions_;
    const Zstring configDirPath_;

    const SharedRef<std::function<void()>> onBeforeSystemShutdownCookie_ = makeSharedRef<std::function<void()>>([this]
    {
        try //let's not lose Google Drive data due to unexpected system shutdown:
        { saveActiveSessions(); } //throw FileError
        catch (const FileError& e) { logExtraError(e.toString()); }
    });
};
//==========================================================================================
constinit Global<GdrivePersistentSessions> globalGdriveSessions;
//==========================================================================================

GdrivePersistentSessions::AsyncAccessInfo accessGlobalFileState(const GdriveLogin& login, const std::function<void(GdriveFileStateAtLocation& fileState)>& useFileState /*throw X*/) //throw SysError, X
{
    if (const std::shared_ptr<GdrivePersistentSessions> gps = globalGdriveSessions.get())
        return gps->accessGlobalFileState(login, useFileState); //throw SysError, X

    throw SysError(formatSystemError("accessGlobalFileState", L"", L"Function call not allowed during init/shutdown."));
}

//==========================================================================================
//==========================================================================================

struct GetDirDetails
{
    GetDirDetails(const GdrivePath& folderPath) : folderPath_(folderPath) {}

    struct Result
    {
        std::vector<GdriveItem> childItems;
        GdrivePath folderPath;
    };
    Result operator()() const
    {
        try
        {
            std::string folderId;
            std::optional<std::vector<GdriveItem>> childItemsBuf;
            const GdrivePersistentSessions::AsyncAccessInfo aai = accessGlobalFileState(folderPath_.gdriveLogin, [&](GdriveFileStateAtLocation& fileState) //throw SysError
            {
                const auto& [itemId, itemDetails] = fileState.getFileAttributes(folderPath_.itemPath, true /*followLeafShortcut*/); //throw SysError

                if (itemDetails.type != GdriveItemType::folder) //check(!) or readFolderContent() will return empty (without failing!)
                    throw SysError(replaceCpy<std::wstring>(L"%x is not a directory.", L"%x", fmtPath(utfTo<Zstring>(itemDetails.itemName))));

                folderId      = itemId;
                childItemsBuf = fileState.all().tryGetBufferedFolderContent(folderId);
            });

            if (!childItemsBuf)
            {
                childItemsBuf = readFolderContent(folderId, aai.access); //throw SysError

                //buffer new file state ASAP => make sure accessGlobalFileState() has amortized constant access (despite the occasional internal readFolderContent() on non-leaf folders)
                accessGlobalFileState(folderPath_.gdriveLogin, [&](GdriveFileStateAtLocation& fileState) //throw SysError
                {
                    fileState.all().notifyFolderContent(aai.stateDelta, folderId, *childItemsBuf);
                });
            }

            for (const GdriveItem& item : *childItemsBuf)
                if (item.details.itemName.empty())
                    throw SysError(L"Folder contains an item without name."); //mostly an issue for FFS's folder traversal, but NOT for globalGdriveSessions!

            return {std::move(*childItemsBuf), folderPath_};
        }
        catch (const SysError& e) { throw FileError(replaceCpy(_("Cannot read directory %x."), L"%x", fmtPath(getGdriveDisplayPath(folderPath_))), e.toString()); }
    }

private:
    GdrivePath folderPath_;
};


struct GetShortcutTargetDetails
{
    GetShortcutTargetDetails(const GdrivePath& shortcutPath, const GdriveItemDetails& shortcutDetails) : shortcutPath_(shortcutPath), shortcutDetails_(shortcutDetails) {}

    struct Result
    {
        GdriveItemDetails target;
        GdriveItemDetails shortcut;
        GdrivePath shortcutPath;
    };
    Result operator()() const
    {
        try
        {
            std::optional<GdriveItemDetails> targetDetailsBuf;
            const GdrivePersistentSessions::AsyncAccessInfo aai = accessGlobalFileState(shortcutPath_.gdriveLogin, [&](GdriveFileStateAtLocation& fileState) //throw SysError
            {
                targetDetailsBuf = fileState.all().tryGetBufferedItemDetails(shortcutDetails_.targetId);
            });
            if (!targetDetailsBuf)
            {
                targetDetailsBuf = getItemDetails(shortcutDetails_.targetId, aai.access); //throw SysError

                //buffer new file state ASAP
                accessGlobalFileState(shortcutPath_.gdriveLogin, [&](GdriveFileStateAtLocation& fileState) //throw SysError
                {
                    fileState.all().notifyItemUpdated(aai.stateDelta, {shortcutDetails_.targetId, *targetDetailsBuf});
                });
            }

            assert(targetDetailsBuf->targetId.empty());
            if (targetDetailsBuf->type == GdriveItemType::shortcut) //should never happen: creating shortcuts to shortcuts fails with "Internal Error"
                throw SysError(L"Google Drive Shortcut points to another Shortcut.");

            return {std::move(*targetDetailsBuf), shortcutDetails_, shortcutPath_};
        }
        catch (const SysError& e) { throw FileError(replaceCpy(_("Cannot resolve symbolic link %x."), L"%x", fmtPath(getGdriveDisplayPath(shortcutPath_))), e.toString()); }
    }

private:
    GdrivePath shortcutPath_;
    GdriveItemDetails shortcutDetails_;
};


class SingleFolderTraverser
{
public:
    SingleFolderTraverser(const GdriveLogin& gdriveLogin, const std::vector<std::pair<AfsPath, std::shared_ptr<AFS::TraverserCallback>>>& workload /*throw X*/) :
        gdriveLogin_(gdriveLogin), workload_(workload)
    {
        while (!workload_.empty())
        {
            auto wi = std::move(workload_.    back()); //yes, no strong exception guarantee (std::bad_alloc)
            /**/                workload_.pop_back();  //
            const auto& [folderPath, cb] = wi;

            tryReportingDirError([&] //throw X
            {
                traverseWithException(folderPath, *cb); //throw FileError, X
            }, *cb);
        }
    }

private:
    SingleFolderTraverser           (const SingleFolderTraverser&) = delete;
    SingleFolderTraverser& operator=(const SingleFolderTraverser&) = delete;

    void traverseWithException(const AfsPath& folderPath, AFS::TraverserCallback& cb) //throw FileError, X
    {
        const std::vector<GdriveItem>& childItems = GetDirDetails({gdriveLogin_, folderPath})().childItems; //throw FileError

        for (const GdriveItem& item : childItems)
        {
            const Zstring itemName = utfTo<Zstring>(item.details.itemName);

            switch (item.details.type)
            {
                case GdriveItemType::file:
                    cb.onFile({itemName, item.details.fileSize, item.details.modTime, getGdriveFilePrint(item.itemId), false /*isFollowedSymlink*/}); //throw X
                    break;

                case GdriveItemType::folder:
                    if (std::shared_ptr<AFS::TraverserCallback> cbSub = cb.onFolder({itemName, false /*isFollowedSymlink*/})) //throw X
                    {
                        const AfsPath afsItemPath(appendPath(folderPath.value, itemName));
                        workload_.push_back({afsItemPath, std::move(cbSub)});
                    }
                    break;

                case GdriveItemType::shortcut:
                    switch (cb.onSymlink({itemName, item.details.modTime})) //throw X
                    {
                        case AFS::TraverserCallback::HandleLink::follow:
                        {
                            const AfsPath afsItemPath(appendPath(folderPath.value, itemName));

                            GdriveItemDetails targetDetails = {};
                            if (!tryReportingItemError([&] //throw X
                        {
                            targetDetails = GetShortcutTargetDetails({gdriveLogin_, afsItemPath}, item.details)().target; //throw FileError
                            }, cb, itemName))
                            continue;

                            if (targetDetails.type == GdriveItemType::folder)
                            {
                                if (std::shared_ptr<AFS::TraverserCallback> cbSub = cb.onFolder({itemName, true /*isFollowedSymlink*/})) //throw X
                                    workload_.push_back({afsItemPath, std::move(cbSub)});
                            }
                            else //a file or named pipe, etc.
                                cb.onFile({itemName, targetDetails.fileSize, targetDetails.modTime, getGdriveFilePrint(item.details.targetId), true /*isFollowedSymlink*/}); //throw X
                        }
                        break;

                        case AFS::TraverserCallback::HandleLink::skip:
                            break;
                    }
                    break;
            }
        }
    }

    const GdriveLogin gdriveLogin_;
    std::vector<std::pair<AfsPath, std::shared_ptr<AFS::TraverserCallback>>> workload_;
};


void gdriveTraverseFolderRecursive(const GdriveLogin& gdriveLogin, const std::vector<std::pair<AfsPath, std::shared_ptr<AFS::TraverserCallback>>>& workload /*throw X*/, size_t) //throw X
{
    SingleFolderTraverser dummy(gdriveLogin, workload); //throw X
}
//==========================================================================================
//==========================================================================================

struct InputStreamGdrive : public AFS::InputStream
{
    explicit InputStreamGdrive(const GdrivePath& gdrivePath) :
        gdrivePath_(gdrivePath)
    {
        worker_ = InterruptibleThread([asyncStreamOut = this->asyncStreamIn_, gdrivePath]
        {
            setCurrentThreadName(Zstr("Istream ") + utfTo<Zstring>(getGdriveDisplayPath(gdrivePath)));
            try
            {
                GdriveAccess access;
                std::string fileId;
                try
                {
                    access = accessGlobalFileState(gdrivePath.gdriveLogin, [&](GdriveFileStateAtLocation& fileState) //throw SysError
                    {
                        fileId = fileState.getItemId(gdrivePath.itemPath, true /*followLeafShortcut*/); //throw SysError
                    }).access;
                }
                catch (const SysError& e) { throw FileError(replaceCpy(_("Cannot open file %x."), L"%x", fmtPath(getGdriveDisplayPath(gdrivePath))), e.toString()); }

                try
                {
                    auto writeBlock = [&](const void* buffer, size_t bytesToWrite)
                    {
                        asyncStreamOut->write(buffer, bytesToWrite); //throw ThreadStopRequest
                    };
                    gdriveDownloadFile(fileId, writeBlock, access); //throw SysError, ThreadStopRequest
                }
                catch (const SysError& e) { throw FileError(replaceCpy(_("Cannot read file %x."), L"%x", fmtPath(getGdriveDisplayPath(gdrivePath))), e.toString()); }

                asyncStreamOut->closeStream();
            }
            catch (FileError&) { asyncStreamOut->setWriteError(std::current_exception()); } //let ThreadStopRequest pass through!
        });
    }

    ~InputStreamGdrive()
    {
        asyncStreamIn_->setReadError(std::make_exception_ptr(ThreadStopRequest()));
    }

    size_t getBlockSize() override { return GDRIVE_BLOCK_SIZE_DOWNLOAD; } //throw (FileError)

    //may return short; only 0 means EOF! CONTRACT: bytesToRead > 0!
    size_t tryRead(void* buffer, size_t bytesToRead, const IoCallback& notifyUnbufferedIO /*throw X*/) override //throw FileError, (ErrorFileLocked), X
    {
        const size_t bytesRead = asyncStreamIn_->tryRead(buffer, bytesToRead); //throw FileError
        reportBytesProcessed(notifyUnbufferedIO); //throw X
        return bytesRead;
        //no need for asyncStreamIn_->checkWriteErrors(): once end of stream is reached, asyncStreamOut->closeStream() was called => no errors occured
    }

    std::optional<AFS::StreamAttributes> tryGetAttributesFast() override //throw FileError
    {
        AFS::StreamAttributes attr = {};
        try
        {
            accessGlobalFileState(gdrivePath_.gdriveLogin, [&](GdriveFileStateAtLocation& fileState) //throw SysError
            {
                const auto& [itemId, itemDetails] = fileState.getFileAttributes(gdrivePath_.itemPath, true /*followLeafShortcut*/); //throw SysError
                attr.modTime  = itemDetails.modTime;
                attr.fileSize = itemDetails.fileSize;
                attr.filePrint = getGdriveFilePrint(itemId);
            });
        }
        catch (const SysError& e) { throw FileError(replaceCpy(_("Cannot read file attributes of %x."), L"%x", fmtPath(getGdriveDisplayPath(gdrivePath_))), e.toString()); }
        return std::move(attr); //[!]
    }

private:
    void reportBytesProcessed(const IoCallback& notifyUnbufferedIO /*throw X*/) //throw X
    {
        const int64_t bytesDelta = makeSigned(asyncStreamIn_->getTotalBytesWritten()) - totalBytesReported_;
        totalBytesReported_ += bytesDelta;
        if (notifyUnbufferedIO) notifyUnbufferedIO(bytesDelta); //throw X
    }

    const GdrivePath gdrivePath_;
    int64_t totalBytesReported_ = 0;
    std::shared_ptr<AsyncStreamBuffer> asyncStreamIn_ = std::make_shared<AsyncStreamBuffer>(GDRIVE_STREAM_BUFFER_SIZE);
    InterruptibleThread worker_;
};

//==========================================================================================

//already existing: 1. fails or 2. creates duplicate
struct OutputStreamGdrive : public AFS::OutputStreamImpl
{
    OutputStreamGdrive(const GdrivePath& gdrivePath,
                       std::optional<uint64_t> /*streamSize*/,
                       std::optional<time_t> modTime,
                       std::unique_ptr<PathAccessLock>&& pal) //throw SysError
    {
        std::promise<AFS::FingerPrint> promFilePrint;
        futFilePrint_ = promFilePrint.get_future();

        //CAVEAT: if file is already existing, OutputStreamGdrive *constructor* must fail, not OutputStreamGdrive::write(),
        //        otherwise ~OutputStreamImpl() will delete the already existing file! => don't check asynchronously!
        const Zstring fileName = AFS::getItemName(gdrivePath.itemPath);
        std::string parentId;
        /*const*/ GdrivePersistentSessions::AsyncAccessInfo aai = accessGlobalFileState(gdrivePath.gdriveLogin, [&](GdriveFileStateAtLocation& fileState) //throw SysError
        {
            const GdriveFileState::PathStatus& ps = fileState.getPathStatus(gdrivePath.itemPath, false /*followLeafShortcut*/); //throw SysError
            if (ps.relPath.empty())
                throw SysError(replaceCpy(_("The name %x is already used by another item."), L"%x", fmtPath(fileName)));

            if (ps.relPath.size() > 1) //parent folder missing
                throw SysError(replaceCpy(_("%x does not exist."), L"%x", fmtPath(ps.relPath.front())));

            parentId = ps.existingItemId;
        });

        worker_ = InterruptibleThread([gdrivePath, modTime, fileName, asyncStreamIn = this->asyncStreamOut_,
                                                   pFilePrint = std::move(promFilePrint),
                                                   parentId   = std::move(parentId),
                                                   aai        = std::move(aai),
                                                   pal        = std::move(pal)]() mutable
        {
            assert(pal); //bind life time to worker thread!
            setCurrentThreadName(Zstr("Ostream ") + utfTo<Zstring>(getGdriveDisplayPath(gdrivePath)));
            try
            {
                auto tryReadBlock = [&](void* buffer, size_t bytesToRead) //may return short, only 0 means EOF!
                {
                    return asyncStreamIn->tryRead(buffer, bytesToRead); //throw ThreadStopRequest
                };
                //for whatever reason, gdriveUploadFile() is slightly faster than gdriveUploadSmallFile()! despite its two roundtrips! even when file sizes are 0!
                //=> 1. issue likely on Google's side => 2. persists even after having fixed "Expect: 100-continue"
                const std::string fileIdNew = //streamSize && *streamSize < 5 * 1024 * 1024 ?
                    //gdriveUploadSmallFile(fileName, parentId, *streamSize, modTime,    readBlock, aai.access) : //throw SysError, ThreadStopRequest
                    gdriveUploadFile       (fileName, parentId,              modTime, tryReadBlock, aai.access);  //throw SysError, ThreadStopRequest
                assert(asyncStreamIn->getTotalBytesRead() == asyncStreamIn->getTotalBytesWritten());
                //already existing: creates duplicate

                //buffer new file state ASAP (don't wait GDRIVE_SYNC_INTERVAL)
                GdriveItem newFileItem
                {
                    .itemId = fileIdNew,
                    .details{
                        .itemName = fileName,
                        .fileSize = asyncStreamIn->getTotalBytesRead(),
                        .type = GdriveItemType::file,
                        .owner = FileOwner::me,
                    }
                };
                if (modTime) //else: whatever modTime Google Drive selects will be notified after GDRIVE_SYNC_INTERVAL
                    newFileItem.details.modTime = *modTime;
                newFileItem.details.parentIds.push_back(parentId);

                accessGlobalFileState(gdrivePath.gdriveLogin, [&](GdriveFileStateAtLocation& fileState) //throw SysError
                {
                    fileState.all().notifyItemCreated(aai.stateDelta, newFileItem);
                });

                pFilePrint.set_value(getGdriveFilePrint(fileIdNew));
            }
            catch (const SysError& e)
            {
                FileError fe(replaceCpy(_("Cannot write file %x."), L"%x", fmtPath(getGdriveDisplayPath(gdrivePath))), e.toString());
                const std::exception_ptr exptr = std::make_exception_ptr(std::move(fe));
                asyncStreamIn->setReadError(exptr); //set both!
                pFilePrint.set_exception(exptr);    //
            }
            //let ThreadStopRequest pass through!
        });
    }

    ~OutputStreamGdrive()
    {
        if (asyncStreamOut_) //finalize() was not called (successfully)
            asyncStreamOut_->setWriteError(std::make_exception_ptr(ThreadStopRequest()));
    }

    size_t getBlockSize() override { return GDRIVE_BLOCK_SIZE_UPLOAD; } //throw (FileError)

    size_t tryWrite(const void* buffer, size_t bytesToWrite, const IoCallback& notifyUnbufferedIO /*throw X*/) override //throw FileError, X; may return short! CONTRACT: bytesToWrite > 0
    {
        const size_t bytesWritten = asyncStreamOut_->tryWrite(buffer, bytesToWrite); //throw FileError
        reportBytesProcessed(notifyUnbufferedIO); //throw X
        return bytesWritten;
    }

    AFS::FinalizeResult finalize(const IoCallback& notifyUnbufferedIO /*throw X*/) override //throw FileError, X
    {
        if (!asyncStreamOut_)
            throw std::logic_error(std::string(__FILE__) + '[' + numberTo<std::string>(__LINE__) + "] Contract violation!");

        asyncStreamOut_->closeStream();

        while (futFilePrint_.wait_for(std::chrono::milliseconds(50)) == std::future_status::timeout)
            reportBytesProcessed(notifyUnbufferedIO); //throw X
        reportBytesProcessed(notifyUnbufferedIO); //[!] once more, now that *all* bytes were written

        AFS::FinalizeResult result;
        assert(isReady(futFilePrint_));
        result.filePrint = futFilePrint_.get(); //throw FileError

        //asyncStreamOut_->checkReadErrors(); //throw FileError -> not needed after *successful* upload
        asyncStreamOut_.reset(); //do NOT reset on error, so that ~OutputStreamGdrive() will request worker thread to stop
        //--------------------------------------------------------------------

        //result.errorModTime -> already (successfully) set during file creation
        return result;
    }

private:
    void reportBytesProcessed(const IoCallback& notifyUnbufferedIO /*throw X*/) //throw X
    {
        const int64_t bytesDelta = makeSigned(asyncStreamOut_->getTotalBytesRead()) - totalBytesReported_;
        totalBytesReported_ += bytesDelta;
        if (notifyUnbufferedIO) notifyUnbufferedIO(bytesDelta); //throw X
    }

    int64_t totalBytesReported_ = 0;
    std::shared_ptr<AsyncStreamBuffer> asyncStreamOut_ = std::make_shared<AsyncStreamBuffer>(GDRIVE_STREAM_BUFFER_SIZE);
    InterruptibleThread worker_;
    std::future<AFS::FingerPrint> futFilePrint_;
};

//==========================================================================================

class GdriveFileSystem : public AbstractFileSystem
{
public:
    explicit GdriveFileSystem(const GdriveLogin& gdriveLogin) : gdriveLogin_(gdriveLogin) {}

    const GdriveLogin& getGdriveLogin() const { return gdriveLogin_; }

    Zstring getFolderUrl(const AfsPath& folderPath) const //throw FileError
    {
        try
        {
            GdriveFileState::PathStatus ps;
            accessGlobalFileState(gdriveLogin_, [&](GdriveFileStateAtLocation& fileState) //throw SysError
            {
                ps = fileState.getPathStatus(folderPath, true /*followLeafShortcut*/); //throw SysError
            });

            if (!ps.relPath.empty())
                throw SysError(replaceCpy(_("%x does not exist."), L"%x", fmtPath(ps.relPath.front())));

            if (ps.existingType != GdriveItemType::folder)
                throw SysError(replaceCpy<std::wstring>(L"%x is not a folder.", L"%x", fmtPath(getItemName(folderPath))));

            return Zstr("https://drive.google.com/drive/folders/") + utfTo<Zstring>(ps.existingItemId);
        }
        catch (const SysError& e) { throw FileError(replaceCpy(_("Cannot read directory %x."), L"%x", fmtPath(getDisplayPath(folderPath))), e.toString()); }
    }

private:
    GdrivePath getGdrivePath(const AfsPath& itemPath) const { return {gdriveLogin_, itemPath}; }

    GdriveRawPath getGdriveRawPath(const AfsPath& itemPath) const //throw SysError
    {
        const std::optional<AfsPath> parentPath = getParentPath(itemPath);
        if (!parentPath)
            throw SysError(L"Item is device root");

        std::string parentId;
        accessGlobalFileState(gdriveLogin_, [&](GdriveFileStateAtLocation& fileState) //throw SysError
        {
            parentId = fileState.getItemId(*parentPath, true /*followLeafShortcut*/); //throw SysError
        });
        return { std::move(parentId), getItemName(itemPath)};
    }

    Zstring getInitPathPhrase(const AfsPath& itemPath) const override { return concatenateGdriveFolderPathPhrase(getGdrivePath(itemPath)); }

    std::vector<Zstring> getPathPhraseAliases(const AfsPath& itemPath) const override { return {getInitPathPhrase(itemPath)}; }

    std::wstring getDisplayPath(const AfsPath& itemPath) const override { return getGdriveDisplayPath(getGdrivePath(itemPath)); }

    bool isNullFileSystem() const override { return gdriveLogin_.email.empty(); }

    std::weak_ordering compareDeviceSameAfsType(const AbstractFileSystem& afsRhs) const override
    {
        const GdriveLogin& lhs = gdriveLogin_;
        const GdriveLogin& rhs = static_cast<const GdriveFileSystem&>(afsRhs).gdriveLogin_;

        if (const std::weak_ordering cmp = compareAsciiNoCase(lhs.email, rhs.email);
            cmp != std::weak_ordering::equivalent)
            return cmp;

        return compareNativePath(lhs.locationName, rhs.locationName);
    }

    //----------------------------------------------------------------------------------------------------------------
    ItemType getItemType(const AfsPath& itemPath) const override //throw FileError
    {
        try
        {
            GdriveFileState::PathStatus ps;
            accessGlobalFileState(gdriveLogin_, [&](GdriveFileStateAtLocation& fileState) //throw SysError
            {
                ps = fileState.getPathStatus(itemPath, false /*followLeafShortcut*/); //throw SysError
            });
            if (ps.relPath.empty())
                switch (ps.existingType)
                {
                    //*INDENT-OFF*
                    case GdriveItemType::file:     return ItemType::file;
                    case GdriveItemType::folder:   return ItemType::folder;
                    case GdriveItemType::shortcut: return ItemType::symlink;
                    //*INDENT-ON*
                }

            throw SysError(replaceCpy(_("%x does not exist."), L"%x", fmtPath(Zstring(ps.relPath.front()))));
        }
        catch (const SysError& e) { throw FileError(replaceCpy(_("Cannot read file attributes of %x."), L"%x", fmtPath(getDisplayPath(itemPath))), e.toString()); }
    }

    std::optional<ItemType> getItemTypeIfExists(const AfsPath& itemPath) const override //throw FileError
    {
        try
        {
            GdriveFileState::PathStatus ps;
            accessGlobalFileState(gdriveLogin_, [&](GdriveFileStateAtLocation& fileState) //throw SysError
            {
                ps = fileState.getPathStatus(itemPath, false /*followLeafShortcut*/); //throw SysError
            });
            if (ps.relPath.empty())
                switch (ps.existingType)
                {
                    //*INDENT-OFF*
                    case GdriveItemType::file:     return ItemType::file;
                    case GdriveItemType::folder:   return ItemType::folder;
                    case GdriveItemType::shortcut: return ItemType::symlink;
                    //*INDENT-ON*
                }
            return std::nullopt;
        }
        catch (const SysError& e) { throw FileError(replaceCpy(_("Cannot read file attributes of %x."), L"%x", fmtPath(getDisplayPath(itemPath))), e.toString()); }
    }

    //----------------------------------------------------------------------------------------------------------------
    //already existing: 1. fails or 2. creates duplicate (unlikely)
    void createFolderPlain(const AfsPath& folderPath) const override //throw FileError
    {
        try
        {
            //avoid duplicate Google Drive item creation by multiple threads
            PathAccessLock pal(getGdriveRawPath(folderPath), PathBlockType::otherWait); //throw SysError

            const Zstring folderName = getItemName(folderPath);
            std::string parentId;
            const GdrivePersistentSessions::AsyncAccessInfo aai = accessGlobalFileState(gdriveLogin_, [&](GdriveFileStateAtLocation& fileState) //throw SysError
            {
                const GdriveFileState::PathStatus& ps = fileState.getPathStatus(folderPath, false /*followLeafShortcut*/); //throw SysError
                if (ps.relPath.empty())
                    throw SysError(replaceCpy(_("The name %x is already used by another item."), L"%x", fmtPath(folderName)));

                if (ps.relPath.size() > 1) //parent folder missing
                    throw SysError(replaceCpy(_("%x does not exist."), L"%x", fmtPath(ps.relPath.front())));

                parentId = ps.existingItemId;
            });

            //already existing: creates duplicate
            const std::string folderIdNew = gdriveCreateFolderPlain(folderName, parentId, aai.access); //throw SysError

            //buffer new file state ASAP (don't wait GDRIVE_SYNC_INTERVAL)
            accessGlobalFileState(gdriveLogin_, [&](GdriveFileStateAtLocation& fileState) //throw SysError
            {
                fileState.all().notifyFolderCreated(aai.stateDelta, folderIdNew, folderName, parentId);
            });
        }
        catch (const SysError& e) { throw FileError(replaceCpy(_("Cannot create directory %x."), L"%x", fmtPath(getDisplayPath(folderPath))), e.toString()); }
    }

    void removeItemPlainImpl(const AfsPath& itemPath, std::optional<GdriveItemType> expectedType, bool permanent /*...or move to trash*/, bool failIfNotExist) const //throw SysError
    {
        const std::optional<AfsPath> parentPath = getParentPath(itemPath);
        if (!parentPath) throw SysError(L"Item is device root");

        std::string itemId;
        std::optional<std::string> parentIdToUnlink;
        const GdrivePersistentSessions::AsyncAccessInfo aai = accessGlobalFileState(gdriveLogin_, [&](GdriveFileStateAtLocation& fileState) //throw SysError
        {
            const GdriveFileState::PathStatus ps = fileState.getPathStatus(itemPath, false /*followLeafShortcut*/); //throw SysError
            if (!ps.relPath.empty())
            {
                if (failIfNotExist)
                    throw SysError(replaceCpy(_("%x does not exist."), L"%x", fmtPath(ps.relPath.front())));
                else
                    return;
            }

            GdriveItemDetails itemDetails;
            std::tie(itemId, itemDetails) = fileState.getFileAttributes(itemPath, false /*followLeafShortcut*/); //throw SysError
            assert(std::find(itemDetails.parentIds.begin(), itemDetails.parentIds.end(), fileState.getItemId(*parentPath, true /*followLeafShortcut*/)) != itemDetails.parentIds.end());

            if (expectedType && itemDetails.type != *expectedType)
                switch (*expectedType)
                {
                    //*INDENT-OFF*
                    case GdriveItemType::file:     throw SysError(L"Item is not a file");
                    case GdriveItemType::folder:   throw SysError(L"Item is not a folder");
                    case GdriveItemType::shortcut: throw SysError(L"Item is not a shortcut");
                    //*INDENT-ON*
                }

            //hard-link handling applies to shared files as well: 1. it's the right thing (TM) 2. if we're not the owner: deleting would fail
            if (itemDetails.parentIds.size() > 1 || itemDetails.owner == FileOwner::other) //FileOwner::other behaves like a followed symlink! i.e. vanishes if owner deletes it!
                parentIdToUnlink = fileState.getItemId(*parentPath, true /*followLeafShortcut*/); //throw SysError
        });
        if (itemId.empty())
            return;

        if (parentIdToUnlink)
        {
            gdriveUnlinkParent(itemId, *parentIdToUnlink, aai.access); //throw SysError

            //buffer new file state ASAP (don't wait GDRIVE_SYNC_INTERVAL)
            accessGlobalFileState(gdriveLogin_, [&](GdriveFileStateAtLocation& fileState) //throw SysError
            {
                fileState.all().notifyParentRemoved(aai.stateDelta, itemId, *parentIdToUnlink);
            });
        }
        else
        {
            if (permanent)
                gdriveDeleteItem(itemId, aai.access); //throw SysError
            else
                gdriveMoveToTrash(itemId, aai.access); //throw SysError

            //buffer new file state ASAP (don't wait GDRIVE_SYNC_INTERVAL)
            accessGlobalFileState(gdriveLogin_, [&](GdriveFileStateAtLocation& fileState) //throw SysError
            {
                fileState.all().notifyItemDeleted(aai.stateDelta, itemId);
            });
        }
    }

    void removeFilePlain(const AfsPath& filePath) const override //throw FileError
    {
        try { removeItemPlainImpl(filePath, GdriveItemType::file, true /*permanent*/, false /*failIfNotExist*/); /*throw SysError*/ }
        catch (const SysError& e) { throw FileError(replaceCpy(_("Cannot delete file %x."), L"%x", fmtPath(getDisplayPath(filePath))), e.toString()); }
    }

    void removeSymlinkPlain(const AfsPath& linkPath) const override //throw FileError
    {
        try { removeItemPlainImpl(linkPath, GdriveItemType::shortcut, true /*permanent*/, false /*failIfNotExist*/); /*throw SysError*/ }
        catch (const SysError& e) { throw FileError(replaceCpy(_("Cannot delete symbolic link %x."), L"%x", fmtPath(getDisplayPath(linkPath))), e.toString()); }
    }

    void removeFolderPlain(const AfsPath& folderPath) const override //throw FileError
    {
        try { removeItemPlainImpl(folderPath, GdriveItemType::folder, true /*permanent*/, false /*failIfNotExist*/); /*throw SysError*/ }
        catch (const SysError& e) { throw FileError(replaceCpy(_("Cannot delete directory %x."), L"%x", fmtPath(getDisplayPath(folderPath))), e.toString()); }
    }

    void removeFolderIfExistsRecursion(const AfsPath& folderPath, //throw FileError
                                       const std::function<void(const std::wstring& displayPath)>& onBeforeFileDeletion   /*throw X*/,
                                       const std::function<void(const std::wstring& displayPath)>& onBeforeSymlinkDeletion/*throw X*/,
                                       const std::function<void(const std::wstring& displayPath)>& onBeforeFolderDeletion /*throw X*/) const override
    {
        if (onBeforeFolderDeletion) onBeforeFolderDeletion(getDisplayPath(folderPath)); //throw X

        try { removeItemPlainImpl(folderPath, GdriveItemType::folder, true /*permanent*/, false /*failIfNotExist*/); /*throw SysError*/ }
        catch (const SysError& e) { throw FileError(replaceCpy(_("Cannot delete directory %x."), L"%x", fmtPath(getDisplayPath(folderPath))), e.toString()); }
    }

    //----------------------------------------------------------------------------------------------------------------
    AbstractPath getSymlinkResolvedPath(const AfsPath& linkPath) const override //throw FileError
    {
        //this function doesn't make sense for Google Drive: Shortcuts do not refer by path, but ID!
        //even if it were possible to determine a path, doing anything with the target file (e.g. delete + recreate) would break other Shortcuts!
        throw FileError(replaceCpy(_("Cannot determine final path for %x."), L"%x", fmtPath(getDisplayPath(linkPath))), _("Operation not supported by device."));
    }

    bool equalSymlinkContentForSameAfsType(const AfsPath& linkPathL, const AbstractPath& linkPathR) const override //throw FileError
    {
        auto getTargetId = [](const GdriveFileSystem& gdriveFs, const AfsPath& linkPath)
        {
            try
            {
                std::string targetId;
                const GdrivePersistentSessions::AsyncAccessInfo aai = accessGlobalFileState(gdriveFs.gdriveLogin_, [&](GdriveFileStateAtLocation& fileState) //throw SysError
                {
                    const GdriveItemDetails& itemDetails = fileState.getFileAttributes(linkPath, false /*followLeafShortcut*/).second; //throw SysError
                    if (itemDetails.type != GdriveItemType::shortcut)
                        throw SysError(L"Not a Google Drive Shortcut.");

                    targetId = itemDetails.targetId;
                });
                return targetId;
            }
            catch (const SysError& e) { throw FileError(replaceCpy(_("Cannot resolve symbolic link %x."), L"%x", fmtPath(gdriveFs.getDisplayPath(linkPath))), e.toString()); }
        };

        return getTargetId(*this, linkPathL) == getTargetId(static_cast<const GdriveFileSystem&>(linkPathR.afsDevice.ref()), linkPathR.afsPath);
    }

    //----------------------------------------------------------------------------------------------------------------

    //return value always bound:
    std::unique_ptr<InputStream> getInputStream(const AfsPath& filePath) const override //throw FileError, (ErrorFileLocked)
    {
        return std::make_unique<InputStreamGdrive>(getGdrivePath(filePath));
    }

    //already existing: undefined behavior! (e.g. fail/overwrite/auto-rename)
    //=> actual behavior: 1. fails or 2. creates duplicate (unlikely)
    std::unique_ptr<OutputStreamImpl> getOutputStream(const AfsPath& filePath, //throw FileError
                                                      std::optional<uint64_t> streamSize,
                                                      std::optional<time_t> modTime) const override
    {
        try
        {
            //avoid duplicate item creation by multiple threads
            auto pal = std::make_unique<PathAccessLock>(getGdriveRawPath(filePath), PathBlockType::otherFail); //throw SysError
            //don't block during a potentially long-running file upload!

            //already existing: 1. fails or 2. creates duplicate
            return std::make_unique<OutputStreamGdrive>(getGdrivePath(filePath), streamSize, modTime, std::move(pal)); //throw SysError
        }
        catch (const SysError& e)
        {
            throw FileError(replaceCpy(_("Cannot write file %x."), L"%x", fmtPath(getDisplayPath(filePath))), e.toString());
        }
    }

    //----------------------------------------------------------------------------------------------------------------
    void traverseFolderRecursive(const TraverserWorkload& workload /*throw X*/, size_t parallelOps) const override
    {
        gdriveTraverseFolderRecursive(gdriveLogin_, workload, parallelOps); //throw X
    }
    //----------------------------------------------------------------------------------------------------------------

    //symlink handling: follow
    //already existing: undefined behavior! (e.g. fail/overwrite/auto-rename)
    //=> actual behavior: 1. fails or 2. creates duplicate (unlikely)
    FileCopyResult copyFileForSameAfsType(const AfsPath& sourcePath, const StreamAttributes& attrSource, //throw FileError, (ErrorFileLocked), (X)
                                          const AbstractPath& targetPath, bool copyFilePermissions, const IoCallback& notifyUnbufferedIO /*throw X*/) const override
    {
        //no native Google Drive file copy => use stream-based file copy:
        if (copyFilePermissions)
            throw FileError(replaceCpy(_("Cannot write permissions of %x."), L"%x", fmtPath(AFS::getDisplayPath(targetPath))), _("Operation not supported by device."));

        const GdriveFileSystem& fsTarget = static_cast<const GdriveFileSystem&>(targetPath.afsDevice.ref());

        if (!equalAsciiNoCase(gdriveLogin_.email, fsTarget.gdriveLogin_.email))
            //already existing: undefined behavior! (e.g. fail/overwrite/auto-rename)
            //=> actual behavior: 1. fails or 2. creates duplicate (unlikely)
            return copyFileAsStream(sourcePath, attrSource, targetPath, notifyUnbufferedIO); //throw FileError, (ErrorFileLocked), X
        //else: copying files within account works, e.g. between My Drive <-> shared drives

        try
        {
            //avoid duplicate Google Drive item creation by multiple threads (blocking is okay: gdriveCopyFile() should complete instantly!)
            PathAccessLock pal(fsTarget.getGdriveRawPath(targetPath.afsPath), PathBlockType::otherWait); //throw SysError

            const Zstring itemNameNew = getItemName(targetPath);
            std::string itemIdSrc;
            GdriveItemDetails itemDetailsSrc;
            /*const GdrivePersistentSessions::AsyncAccessInfo aaiSrc =*/ accessGlobalFileState(gdriveLogin_, [&](GdriveFileStateAtLocation& fileState) //throw SysError
            {
                std::tie(itemIdSrc, itemDetailsSrc) = fileState.getFileAttributes(sourcePath, true /*followLeafShortcut*/); //throw SysError

                assert(itemDetailsSrc.type == GdriveItemType::file); //Google Drive *should* fail trying to copy folder: "This file cannot be copied by the user."
                if (itemDetailsSrc.type != GdriveItemType::file)     //=> don't trust + improve error message
                    throw SysError(replaceCpy<std::wstring>(L"%x is not a file.", L"%x", fmtPath(getItemName(sourcePath))));
            });

            std::string parentIdTrg;
            const GdrivePersistentSessions::AsyncAccessInfo aaiTrg = accessGlobalFileState(fsTarget.gdriveLogin_, [&](GdriveFileStateAtLocation& fileState) //throw SysError
            {
                const GdriveFileState::PathStatus psTo = fileState.getPathStatus(targetPath.afsPath, false /*followLeafShortcut*/); //throw SysError
                if (psTo.relPath.empty())
                    throw SysError(replaceCpy(_("The name %x is already used by another item."), L"%x", fmtPath(itemNameNew)));

                if (psTo.relPath.size() > 1) //parent folder missing
                    throw SysError(replaceCpy(_("%x does not exist."), L"%x", fmtPath(psTo.relPath.front())));

                parentIdTrg = psTo.existingItemId;
            });

            //already existing: creates duplicate
            const std::string fileIdTrg = gdriveCopyFile(itemIdSrc, parentIdTrg, itemNameNew, itemDetailsSrc.modTime, aaiTrg.access); //throw SysError

            //buffer new file state ASAP (don't wait GDRIVE_SYNC_INTERVAL)
            accessGlobalFileState(fsTarget.gdriveLogin_, [&](GdriveFileStateAtLocation& fileState) //throw SysError
            {
                const GdriveItem newFileItem
                {
                    .itemId = fileIdTrg,
                    .details{
                        .itemName = itemNameNew,
                        .fileSize = itemDetailsSrc.fileSize,
                        .modTime = itemDetailsSrc.modTime,
                        .type = GdriveItemType::file,
                        .owner = fileState.all().getSharedDriveName().empty() ? FileOwner::me : FileOwner::none,
                        .parentIds{parentIdTrg},
                    }
                };
                fileState.all().notifyItemCreated(aaiTrg.stateDelta, newFileItem);
            });

            return
            {
                .fileSize = itemDetailsSrc.fileSize,
                .modTime  = itemDetailsSrc.modTime,
                .sourceFilePrint = getGdriveFilePrint(itemIdSrc),
                .targetFilePrint = getGdriveFilePrint(fileIdTrg),
                /*.errorModTime = */
            };
        }
        catch (const SysError& e)
        {
            throw FileError(replaceCpy(replaceCpy(_("Cannot copy file %x to %y."),
                                                  L"%x", L'\n' + fmtPath(getDisplayPath(sourcePath))),
                                       L"%y",  L'\n' + fmtPath(AFS::getDisplayPath(targetPath))), e.toString());
        }
    }

    //symlink handling: follow
    //already existing: fail
    void copyNewFolderForSameAfsType(const AfsPath& sourcePath, const AbstractPath& targetPath, bool copyFilePermissions) const override //throw FileError
    {
        //already existing: 1. fails or 2. creates duplicate (unlikely)
        AFS::createFolderPlain(targetPath); //throw FileError

        if (copyFilePermissions)
            throw FileError(replaceCpy(_("Cannot write permissions of %x."), L"%x", fmtPath(AFS::getDisplayPath(targetPath))), _("Operation not supported by device."));
    }

    //already existing: fail
    void copySymlinkForSameAfsType(const AfsPath& sourcePath, const AbstractPath& targetPath, bool copyFilePermissions) const override //throw FileError
    {
        try
        {
            std::string targetId;
            accessGlobalFileState(gdriveLogin_, [&](GdriveFileStateAtLocation& fileState) //throw SysError
            {
                const GdriveItemDetails& itemDetails = fileState.getFileAttributes(sourcePath, false /*followLeafShortcut*/).second; //throw SysError
                if (itemDetails.type != GdriveItemType::shortcut)
                    throw SysError(L"Not a Google Drive Shortcut.");

                targetId = itemDetails.targetId;
            });

            const GdriveFileSystem& fsTarget = static_cast<const GdriveFileSystem&>(targetPath.afsDevice.ref());

            //avoid duplicate Google Drive item creation by multiple threads
            PathAccessLock pal(fsTarget.getGdriveRawPath(targetPath.afsPath), PathBlockType::otherWait); //throw SysError

            const Zstring shortcutName = getItemName(targetPath.afsPath);
            std::string parentId;
            const GdrivePersistentSessions::AsyncAccessInfo aaiTrg = accessGlobalFileState(fsTarget.gdriveLogin_, [&](GdriveFileStateAtLocation& fileState) //throw SysError
            {
                const GdriveFileState::PathStatus& ps = fileState.getPathStatus(targetPath.afsPath, false /*followLeafShortcut*/); //throw SysError
                if (ps.relPath.empty())
                    throw SysError(replaceCpy(_("The name %x is already used by another item."), L"%x", fmtPath(shortcutName)));

                if (ps.relPath.size() > 1) //parent folder missing
                    throw SysError(replaceCpy(_("%x does not exist."), L"%x", fmtPath(ps.relPath.front())));

                parentId = ps.existingItemId;
            });

            //already existing: creates duplicate
            const std::string shortcutIdNew = gdriveCreateShortcutPlain(shortcutName, parentId, targetId, aaiTrg.access); //throw SysError

            //buffer new file state ASAP (don't wait GDRIVE_SYNC_INTERVAL)
            accessGlobalFileState(fsTarget.gdriveLogin_, [&](GdriveFileStateAtLocation& fileState) //throw SysError
            {
                fileState.all().notifyShortcutCreated(aaiTrg.stateDelta, shortcutIdNew, shortcutName, parentId, targetId);
            });
        }
        catch (const SysError& e)
        {
            throw FileError(replaceCpy(replaceCpy(_("Cannot copy symbolic link %x to %y."),
                                                  L"%x", L'\n' + fmtPath(getDisplayPath(sourcePath))),
                                       L"%y",  L'\n' + fmtPath(AFS::getDisplayPath(targetPath))), e.toString());
        }
    }

    //already existing: undefined behavior! (e.g. fail/overwrite)
    //=> actual behavior: 1. fails or 2. creates duplicate (unlikely)
    void moveAndRenameItemForSameAfsType(const AfsPath& pathFrom, const AbstractPath& pathTo) const override //throw FileError, ErrorMoveUnsupported
    {
        if (compareDeviceSameAfsType(pathTo.afsDevice.ref()) != std::weak_ordering::equivalent)
            throw ErrorMoveUnsupported(generateMoveErrorMsg(pathFrom, pathTo), _("Operation not supported between different devices."));
        //note: moving files within account works, e.g. between My Drive <-> shared drives
        //      BUT: not supported by our model with separate GdriveFileStates; e.g. how to handle complexity of a moved folder (tree)?
        try
        {
            const GdriveFileSystem& fsTarget = static_cast<const GdriveFileSystem&>(pathTo.afsDevice.ref());

            //avoid duplicate Google Drive item creation by multiple threads
            PathAccessLock pal(fsTarget.getGdriveRawPath(pathTo.afsPath), PathBlockType::otherWait); //throw SysError

            const Zstring itemNameOld = getItemName(pathFrom);
            const Zstring itemNameNew = getItemName(pathTo);
            const std::optional<AfsPath> parentPathFrom = getParentPath(pathFrom);
            const std::optional<AfsPath> parentPathTo   = getParentPath(pathTo.afsPath);
            if (!parentPathFrom) throw SysError(L"Source is device root");
            if (!parentPathTo  ) throw SysError(L"Target is device root");

            std::string itemId;
            GdriveItemDetails itemDetails;
            std::string parentIdFrom;
            std::string parentIdTo;
            const GdrivePersistentSessions::AsyncAccessInfo aai = accessGlobalFileState(gdriveLogin_, [&](GdriveFileStateAtLocation& fileState) //throw SysError
            {
                std::tie(itemId, itemDetails) = fileState.getFileAttributes(pathFrom, false /*followLeafShortcut*/); //throw SysError

                parentIdFrom = fileState.getItemId(*parentPathFrom, true /*followLeafShortcut*/); //throw SysError

                const GdriveFileState::PathStatus psTo = fileState.getPathStatus(pathTo.afsPath, false /*followLeafShortcut*/); //throw SysError

                //e.g. changing file name case only => this is not an "already exists" situation!
                //also: hardlink referenced by two different paths, the source one will be unlinked
                if (psTo.relPath.empty() && psTo.existingItemId == itemId)
                    parentIdTo = fileState.getItemId(*parentPathTo, true /*followLeafShortcut*/); //throw SysError
                else
                {
                    if (psTo.relPath.empty())
                        throw SysError(replaceCpy(_("The name %x is already used by another item."), L"%x", fmtPath(itemNameNew)));

                    if (psTo.relPath.size() > 1) //parent folder missing
                        throw SysError(replaceCpy(_("%x does not exist."), L"%x", fmtPath(psTo.relPath.front())));

                    parentIdTo = psTo.existingItemId;
                }
            });

            if (parentIdFrom == parentIdTo && itemNameOld == itemNameNew)
                return; //nothing to do

            //already existing: creates duplicate
            gdriveMoveAndRenameItem(itemId, parentIdFrom, parentIdTo, itemNameNew, itemDetails.modTime, aai.access); //throw SysError

            //buffer new file state ASAP (don't wait GDRIVE_SYNC_INTERVAL)
            accessGlobalFileState(gdriveLogin_, [&](GdriveFileStateAtLocation& fileState) //throw SysError
            {
                fileState.all().notifyMoveAndRename(aai.stateDelta, itemId, parentIdFrom, parentIdTo, itemNameNew);
            });
        }
        catch (const SysError& e) { throw FileError(generateMoveErrorMsg(pathFrom, pathTo), e.toString()); }
    }

    bool supportsPermissions(const AfsPath& folderPath) const override { return false; } //throw FileError

    //----------------------------------------------------------------------------------------------------------------
    FileIconHolder getFileIcon      (const AfsPath& filePath, int pixelSize) const override { return {}; } //throw FileError; optional return value
    ImageHolder    getThumbnailImage(const AfsPath& filePath, int pixelSize) const override { return {}; } //throw FileError; optional return value

    void authenticateAccess(const RequestPasswordFun& requestPassword /*throw X*/) const override //throw FileError, (X)
    {
        try
        {
            const std::shared_ptr<GdrivePersistentSessions> gps = globalGdriveSessions.get();
            if (!gps)
                throw SysError(formatSystemError("GdriveFileSystem::authenticateAccess", L"", L"Function call not allowed during init/shutdown."));

            for (const std::string& accountEmail : gps->listAccounts()) //throw SysError
                if (equalAsciiNoCase(accountEmail, gdriveLogin_.email))
                    return;

            const bool allowUserInteraction = static_cast<bool>(requestPassword);
            if (allowUserInteraction)
                gps->addUserSession(gdriveLogin_.email /*gdriveLoginHint*/, nullptr /*updateGui*/, gdriveLogin_.timeoutSec); //throw SysError
            //error messages will be lost if user cancels in dir_exist_async.h! However:
            //The most-likely-to-fail parts (web access) are reported by gdriveAuthorizeAccess() via the browser!
            else
                throw SysError(replaceCpy(_("Please add a connection to user account %x first."), L"%x", utfTo<std::wstring>(gdriveLogin_.email)));
        }
        catch (const SysError& e) { throw FileError(replaceCpy(_("Unable to connect to %x."), L"%x", fmtPath(getDisplayPath(AfsPath()))), e.toString()); }
    }

    bool hasNativeTransactionalCopy() const override { return true; }
    //----------------------------------------------------------------------------------------------------------------

    int64_t getFreeDiskSpace(const AfsPath& folderPath) const override //throw FileError, returns < 0 if not available
    {
        bool onMyDrive = false;
        try
        {
            const GdriveAccess& access = accessGlobalFileState(gdriveLogin_, [&](GdriveFileStateAtLocation& fileState)
            { onMyDrive = fileState.all().getSharedDriveName().empty(); }).access; //throw SysError

            if (onMyDrive)
                return gdriveGetMyDriveFreeSpace(access); //throw SysError
            else
                return -1;
        }
        catch (const SysError& e) { throw FileError(replaceCpy(_("Cannot determine free disk space for %x."), L"%x", fmtPath(getDisplayPath(folderPath))), e.toString()); }
    }

    std::unique_ptr<RecycleSession> createRecyclerSession(const AfsPath& folderPath) const override //throw FileError, (RecycleBinUnavailable)
    {
        struct RecycleSessionGdrive : public RecycleSession
        {
            //fails if item is not existing
            void moveToRecycleBin(const AbstractPath& itemPath, const Zstring& logicalRelPath) override { AFS::moveToRecycleBin(itemPath); } //throw FileError, (RecycleBinUnavailable)
            void tryCleanup(const std::function<void(const std::wstring& displayPath)>& notifyDeletionStatus) override {}; //throw FileError
        };

        return std::make_unique<RecycleSessionGdrive>();
    }

    //fails if item is not existing
    void moveToRecycleBin(const AfsPath& itemPath) const override //throw FileError, (RecycleBinUnavailable)
    {
        try
        {
            removeItemPlainImpl(itemPath, std::nullopt /*expectedType*/, false /*permanent*/, true /*failIfNotExist*/); //throw SysError
        }
        catch (const SysError& e) { throw FileError(replaceCpy(_("Unable to move %x to the recycle bin."), L"%x", fmtPath(getDisplayPath(itemPath))), e.toString()); }
    }

    const GdriveLogin gdriveLogin_;
};
//===========================================================================================================================

//expects "clean" input data
Zstring concatenateGdriveFolderPathPhrase(const GdrivePath& gdrivePath) //noexcept
{
    Zstring emailAndDrive = utfTo<Zstring>(gdrivePath.gdriveLogin.email);
    if (!gdrivePath.gdriveLogin.locationName.empty())
        emailAndDrive += Zstr(':') + gdrivePath.gdriveLogin.locationName;

    Zstring options;
    if (gdrivePath.gdriveLogin.timeoutSec != GdriveLogin().timeoutSec)
        options += Zstr("|timeout=") + numberTo<Zstring>(gdrivePath.gdriveLogin.timeoutSec);

    Zstring itemPath;
    if (!gdrivePath.itemPath.value.empty())
        itemPath += FILE_NAME_SEPARATOR + gdrivePath.itemPath.value;

    if (endsWith(itemPath, Zstr(' ')) && options.empty()) //path phrase concept must survive trimming!
        itemPath += FILE_NAME_SEPARATOR;

    return Zstring(gdrivePrefix) + FILE_NAME_SEPARATOR + emailAndDrive + itemPath + options;
}
}


void fff::gdriveInit(const Zstring& configDirPath, const Zstring& caCertFilePath)
{
    assert(!globalHttpSessionManager.get());
    globalHttpSessionManager.set(std::make_unique<HttpSessionManager>(caCertFilePath));

    assert(!globalGdriveSessions.get());
    globalGdriveSessions.set(std::make_unique<GdrivePersistentSessions>(configDirPath));
}


void fff::gdriveTeardown()
{
    try //don't use ~GdrivePersistentSessions() to save! Might never happen, e.g. detached thread waiting for Google Drive authentication; terminated on exit!
    {
        if (const std::shared_ptr<GdrivePersistentSessions> gps = globalGdriveSessions.get())
            gps->saveActiveSessions(); //throw FileError
    }
    catch (const FileError& e) { logExtraError(e.toString()); }

    assert(globalGdriveSessions.get());
    globalGdriveSessions.set(nullptr);

    assert(globalHttpSessionManager.get());
    globalHttpSessionManager.set(nullptr);
}


std::string fff::gdriveAddUser(const std::function<void()>& updateGui /*throw X*/, int timeoutSec) //throw FileError, X
{
    try
    {
        if (const std::shared_ptr<GdrivePersistentSessions> gps = globalGdriveSessions.get())
            return gps->addUserSession("" /*gdriveLoginHint*/, updateGui, timeoutSec); //throw SysError, X

        throw SysError(formatSystemError("gdriveAddUser", L"", L"Function call not allowed during init/shutdown."));
    }
    catch (const SysError& e) { throw FileError(replaceCpy(_("Unable to connect to %x."), L"%x", L"Google Drive"), e.toString()); }
}


void fff::gdriveRemoveUser(const std::string& accountEmail, int timeoutSec) //throw FileError
{
    try
    {
        if (const std::shared_ptr<GdrivePersistentSessions> gps = globalGdriveSessions.get())
            return gps->removeUserSession(accountEmail, timeoutSec); //throw SysError

        throw SysError(formatSystemError("gdriveRemoveUser", L"", L"Function call not allowed during init/shutdown."));
    }
    catch (const SysError& e) { throw FileError(replaceCpy(_("Unable to disconnect from %x."), L"%x", fmtPath(getGdriveDisplayPath({{accountEmail, Zstr("")}, AfsPath()}))), e.toString()); }
}


std::vector<std::string /*account email*/> fff::gdriveListAccounts() //throw FileError
{
    try
    {
        if (const std::shared_ptr<GdrivePersistentSessions> gps = globalGdriveSessions.get())
            return gps->listAccounts(); //throw SysError

        throw SysError(formatSystemError("gdriveListAccounts", L"", L"Function call not allowed during init/shutdown."));
    }
    catch (const SysError& e) { throw FileError(replaceCpy(_("Unable to connect to %x."), L"%x", L"Google Drive"), e.toString()); }
}


std::vector<Zstring /*locationName*/> fff::gdriveListLocations(const std::string& accountEmail, int timeoutSec) //throw FileError
{
    try
    {
        if (const std::shared_ptr<GdrivePersistentSessions> gps = globalGdriveSessions.get())
            return gps->listLocations(accountEmail, timeoutSec); //throw SysError

        throw SysError(formatSystemError("gdriveListLocations", L"", L"Function call not allowed during init/shutdown."));
    }
    catch (const SysError& e) { throw FileError(replaceCpy(_("Unable to connect to %x."), L"%x", fmtPath(getGdriveDisplayPath({{accountEmail, Zstr("")}, AfsPath()}))), e.toString()); }
}


AfsDevice fff::condenseToGdriveDevice(const GdriveLogin& login) //noexcept
{
    //clean up input:
    GdriveLogin loginTmp = login;
    trim(loginTmp.email);

    loginTmp.timeoutSec = std::max(1, loginTmp.timeoutSec);

    return makeSharedRef<GdriveFileSystem>(loginTmp);
}


GdriveLogin fff::extractGdriveLogin(const AfsDevice& afsDevice) //noexcept
{
    if (const auto gdriveDevice = dynamic_cast<const GdriveFileSystem*>(&afsDevice.ref()))
        return gdriveDevice ->getGdriveLogin();

    assert(false);
    return {};
}


Zstring fff::getGoogleDriveFolderUrl(const AbstractPath& folderPath) //throw FileError
{
    if (const auto gdriveDevice = dynamic_cast<const GdriveFileSystem*>(&folderPath.afsDevice.ref()))
        return gdriveDevice->getFolderUrl(folderPath.afsPath); //throw FileError
    //assert(false);
    return {};
}


bool fff::acceptsItemPathPhraseGdrive(const Zstring& itemPathPhrase) //noexcept
{
    Zstring path = expandMacros(itemPathPhrase); //expand before trimming!
    trim(path);
    return startsWithAsciiNoCase(path, gdrivePrefix);
}


/* syntax: gdrive:\<email>[:<shared drive>]\<relative-path>[|option_name=value]

    e.g.: gdrive:\john@gmail.com\folder\file.txt
          gdrive:\john@gmail.com:location\folder\file.txt|option_name=value        */
AbstractPath fff::createItemPathGdrive(const Zstring& itemPathPhrase) //noexcept
{
    Zstring pathPhrase = expandMacros(itemPathPhrase); //expand before trimming!
    trim(pathPhrase);

    if (startsWithAsciiNoCase(pathPhrase, gdrivePrefix))
        pathPhrase = pathPhrase.c_str() + strLength(gdrivePrefix);
    trim(pathPhrase, TrimSide::left, [](Zchar c) { return c == Zstr('/') || c == Zstr('\\'); });

    const ZstringView fullPath = beforeFirst<ZstringView>(pathPhrase, Zstr('|'), IfNotFoundReturn::all);
    const ZstringView options  =  afterFirst<ZstringView>(pathPhrase, Zstr('|'), IfNotFoundReturn::none);

    auto it = std::find_if(fullPath.begin(), fullPath.end(), [](Zchar c) { return c == '/' || c == '\\'; });
    const ZstringView emailAndDrive = makeStringView(fullPath.begin(), it);
    const AfsPath itemPath = sanitizeDeviceRelativePath({it, fullPath.end()});

    GdriveLogin login
    {
        .email        = utfTo<std::string>(beforeFirst(emailAndDrive, Zstr(':'), IfNotFoundReturn::all)),
        .locationName =            Zstring(afterFirst (emailAndDrive, Zstr(':'), IfNotFoundReturn::none)),
    };

    split(options, Zstr('|'), [&](ZstringView optPhrase)
    {
        optPhrase = trimCpy(optPhrase);
        if (!optPhrase.empty())
        {
            if (startsWith(optPhrase, Zstr("timeout=")))
                login.timeoutSec = stringTo<int>(afterFirst(optPhrase, Zstr('='), IfNotFoundReturn::none));
            else
                assert(false);
        }
    });
    return AbstractPath(makeSharedRef<GdriveFileSystem>(login), itemPath);
}