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
use std::fs;
use std::io::Read;
use std::path::PathBuf;
use std::collections::HashMap;
use reqwest::{Url, Method, header};
use reqwest::blocking::{Client, multipart, RequestBuilder};
use crate::utils::upload::FileUploader;
use crate::{Credentials, Error, ErrorKind, objects, request_builder};
request_builder!(
/// A request builder to create a copy of a file and apply any requested
/// updates with patch semantics.
pub CopyRequest {
/// Whether to ignore the domain's default visibility settings for the
/// created file.
///
/// Domain administrators can choose to make all uploaded files visible
/// to the domain by default; this parameter bypasses that behavior for
/// the request. Permissions are still inherited from parent folders.
ignore_default_visibility: Option<bool>,
/// Whether to set the `keepForever` field in the new head revision.
///
/// This is only applicable to files with binary content in a Drive.
///
/// Only 200 revisions for the file can be kept forever, if the limit is
/// reached, try deleting pinned revisions.
keep_revision_forever: Option<bool>,
/// A language hint for OCR processing during image import
/// (ISO 639-1 code).
ocr_language: Option<String>,
/// Whether the requesting application supports both My Drives and
/// shared drives.
supports_all_drives: Option<bool>,
/// Specifies which additional view's permissions to include in the
/// response.
///
/// Only `published` is supported.
include_permissions_for_view: Option<String>,
/// A comma-separated list of IDs of labels to include in the
/// [`label_info`](objects::File::label_info) part of the response.
include_labels: Option<String>,
/// Sets the metadata that the copied file will have.
metadata: Option<objects::File>,
},
// HTTP Method
Method::POST,
// API endpoint
("https://www.googleapis.com/drive/v3/files/{file_id}/copy", file_id),
);
impl CopyRequest {
/// Executes this request.
///
/// # Errors:
///
/// - a [`UrlParsing`](ErrorKind::UrlParsing) error, if the creation of the
/// request's URL failed.
/// - a [`Request`](ErrorKind::Request) error, if unable to send the request
/// or get a body from the response.
/// - a [`Response`](ErrorKind::Response) error, if the request returned an
/// error response.
/// - a [`Json`](ErrorKind::Json) error, if unable to parse the response's
/// body to an [`File`](objects::File) object.
pub fn execute( &self ) -> Result<objects::File, Error> {
let metadata = self.metadata.clone().unwrap_or_default();
let body = serde_json::to_string(&metadata)?;
let content_length = body.as_bytes().len();
let request = self.build()?
.header( "Content-Length", content_length.to_string() )
.body(body);
let response = request.send()?;
if !response.status().is_success() {
return Err( response.into() );
}
Ok( serde_json::from_str( &response.text()? )? )
}
}
request_builder!(
/// A request builder to create a new file in a Drive.
pub CreateRequest {
/// The type of upload request to the /upload URI.
upload_type: Option<objects::UploadType>,
/// Whether to ignore the domain's default visibility settings for the
/// created file.
///
/// Domain administrators can choose to make all uploaded files visible
/// to the domain by default; this parameter bypasses that behavior for
/// the request. Permissions are still inherited from parent folders.
ignore_default_visibility: Option<bool>,
/// Whether to set the `keepForever` field in the new head revision.
///
/// This is only applicable to files with binary content in a Drive.
///
/// Only 200 revisions for the file can be kept forever, if the limit is
/// reached, try deleting pinned revisions.
keep_revision_forever: Option<bool>,
/// A language hint for OCR processing during image import
/// (ISO 639-1 code).
ocr_language: Option<String>,
/// Whether the requesting application supports both My Drives and
/// shared drives.
supports_all_drives: Option<bool>,
/// Whether to use the uploaded content as indexable text.
use_content_as_indexable_text: Option<bool>,
/// Specifies which additional view's permissions to include in the
/// response.
///
/// Only `published` is supported.
include_permissions_for_view: Option<String>,
/// A comma-separated list of IDs of labels to include in the
/// [`label_info`](objects::File::label_info) part of the response.
include_labels: Option<String>,
},
// HTTP Method
Method::POST,
// API endpoint
("https://www.googleapis.com/upload/drive/v3/files"),
// Other fields
/// Sets the metadata that the created file will have in Google Drive.
metadata: Option<objects::File>,
/// The path of the source file to be uploaded.
content_source: Option<PathBuf>,
/// Use this string as the content of the created file.
content_string: Option<String>,
// Function callbacks
(
/// A callback to receive updates on a resumable upload.
callback: Option<fn(usize, usize)>
),
);
impl CreateRequest {
/// Gets a media request.
fn get_media_request( &self ) -> Result<RequestBuilder, Error> {
let mut content_bytes = Vec::new();
if self.content_source.is_some() && self.content_string.is_some() {
return Err(Error {
kind: ErrorKind::Request,
message: "a create request can only use one of 'content_source'\
or 'content_string'".into()
})
}
if let Some(source) = &self.content_source {
let mut file = fs::File::open(source)?;
file.read_to_end(&mut content_bytes)?;
}
if let Some(string) = &self.content_string {
content_bytes = string.as_bytes().to_vec();
}
let mut request = self.build()?
.header( "Content-Length", content_bytes.len().to_string() )
.body(content_bytes);
let metadata = self.metadata.clone().unwrap_or_default();
if let Some(mime_type) = metadata.mime_type {
request = request.header("Content-Type", mime_type);
}
Ok(request)
}
fn get_metadata_form_part( &self ) -> Result<multipart::Part, Error> {
let metadata_string = serde_json::to_string(&self.metadata)?;
let mut metadata_headers = header::HeaderMap::new();
metadata_headers.insert(
header::CONTENT_TYPE, "application/json; charset=UTF-8".parse()?
);
metadata_headers.insert(
header::CONTENT_DISPOSITION, "form-data; name=\"metadata\"".parse()?
);
Ok( multipart::Part::text(metadata_string)
.headers(metadata_headers) )
}
fn get_file_form_part( &self ) -> Result<multipart::Part, Error> {
let metadata = self.metadata.clone().unwrap_or_default();
let content_mime_type = metadata.mime_type.unwrap_or( "*/*".into() );
let mut file_headers = reqwest::header::HeaderMap::new();
file_headers.insert(
header::CONTENT_TYPE, content_mime_type.parse()?
);
file_headers.insert(
header::CONTENT_DISPOSITION, "form-data; name=\"file\"".parse()?
);
let mut file_part = multipart::Part::text("");
if let Some(source) = &self.content_source {
file_part = multipart::Part::file(source)?;
}
if let Some(string) = &self.content_string {
file_part = multipart::Part::text(string.clone());
}
Ok( file_part.headers(file_headers) )
}
/// Gets a multipart request.
fn get_multipart_request( &self ) -> Result<RequestBuilder, Error> {
let metadata_part = self.get_metadata_form_part()?;
let file_part = self.get_file_form_part()?;
let form = multipart::Form::new()
.part("metadata", metadata_part)
.part("file", file_part);
Ok( self.build()?
.multipart(form) )
}
/// Performs a resumable upload.
fn perform_resumable_upload( &self ) -> Result<objects::File, Error> {
let metadata = self.metadata.clone().unwrap_or_default();
let metadata_string = serde_json::to_string(&metadata)?;
let metadata_size = metadata_string.as_bytes().len();
let content_mime_type = metadata.mime_type.unwrap_or( "*/*".into() );
if self.content_string.is_some() {
return Err(Error {
kind: ErrorKind::Request,
message: String::from("A resumable upload cannot be created\
from a string, it must be a file"),
})
}
let mut file = match &self.content_source {
Some(source) => fs::File::open(source)?,
None => {
return Err(Error {
kind: ErrorKind::Request,
message: String::from("A resumable request must include a\
source file"),
})
}
};
let file_size = file.metadata()?.len();
let request = self.build()?
.header( "X-Upload-Content-Type", &content_mime_type )
.header( "X-Upload-Content-Length", &file_size.to_string() )
.header( "Content-Type", "application/json; charset=UTF-8" )
.header( "Content-Length", &metadata_size.to_string() )
.body(metadata_string);
let response = request.send()?;
if !response.status().is_success() {
return Err( response.into() );
}
let upload_uri = match response.headers().get("location") {
Some(header) => header.to_str()?,
#[cfg(not(tarpaulin_include))]
None => {
return Err(Error {
kind: ErrorKind::Request,
message: String::from("unable to get the resumable upload\
location"),
})
}
};
let mut file_uploader = FileUploader::from_uri(upload_uri);
if let Some(callback) = self.callback {
file_uploader = file_uploader.with_callback(callback);
}
file_uploader.upload_file(&mut file)
}
/// Executes this request.
///
/// # Errors
///
/// - an [`IO`](crate::ErrorKind::IO) error, if the source file does not exist.
/// - a [`UrlParsing`](crate::ErrorKind::UrlParsing) error, if the creation of the request URL failed.
/// - a [`Json`](crate::ErrorKind::Json) error, if unable to parse the destination file to JSON.
/// - a [`Request`](crate::ErrorKind::Request) error, if unable to send the request or get a body from the response.
/// - a [`Response`](crate::ErrorKind::Response) error, if the request returned an error response.
pub fn execute( &self ) -> Result<objects::File, Error> {
let upload_type = self.upload_type.unwrap_or_default();
let request = match upload_type {
objects::UploadType::Media => self.get_media_request()?,
objects::UploadType::Multipart => self.get_multipart_request()?,
objects::UploadType::Resumable => {
return self.perform_resumable_upload()
},
};
let response = request.send()?;
if !response.status().is_success() {
return Err( response.into() );
}
Ok( serde_json::from_str( &response.text()? )? )
}
}
request_builder!(
/// A request builder to permanently delete a file without moving it into
/// the trash.
pub DeleteRequest {
/// Whether the requesting application supports both My Drives and
/// shared drives.
supports_all_drives: Option<bool>,
},
// HTTP Method
Method::DELETE,
// API endpoint
("https://www.googleapis.com/drive/v3/files/{file_id}", file_id),
);
impl DeleteRequest {
/// Executes this request.
///
/// # Errors
///
/// - a [`UrlParsing`](ErrorKind::UrlParsing) error, if the creation of the request URL failed.
/// - a [`Json`](ErrorKind::Json) error, if unable to parse the destination file to JSON.
/// - a [`Request`](ErrorKind::Request) error, if unable to send the request or get a body from the response.
/// - a [`Response`](ErrorKind::Response) error, if the request returned an error response.
pub fn execute( &self ) -> Result<(), Error> {
self.send()?;
Ok(())
}
}
request_builder!(
/// A request builder to permanently delete all of the user's trashed files.
pub EmptyTrashRequest {
/// If set, empties the trash of the provided shared drive.
drive_id: Option<String>,
},
// HTTP Method
Method::DELETE,
// API endpoint
("https://www.googleapis.com/drive/v3/files/trash"),
);
#[cfg(not(tarpaulin_include))] // Requires higher permissions
impl EmptyTrashRequest {
/// Executes this request.
///
/// # Errors
///
/// - a [`UrlParsing`](ErrorKind::UrlParsing) error, if the creation of the request URL failed.
/// - a [`Json`](ErrorKind::Json) error, if unable to parse the destination file to JSON.
/// - a [`Request`](ErrorKind::Request) error, if unable to send the request or get a body from the response.
/// - a [`Response`](ErrorKind::Response) error, if the request returned an error response.
pub fn execute( &self ) -> Result<(), Error> {
self.send()?;
Ok(())
}
}
request_builder!(
/// A request builder to export a Google Workspace document.
pub ExportRequest {
/// The MIME type of the format requested for this export.
mime_type: Option<String>,
},
// HTTP Method
Method::GET,
// API endpoint
("https://www.googleapis.com/drive/v3/files/{file_id}/export", file_id),
);
#[cfg(not(tarpaulin_include))] // Requires higher permissions
impl ExportRequest {
/// Executes this request.
///
/// # Errors
///
/// - a [`UrlParsing`](ErrorKind::UrlParsing) error, if the creation of the request URL failed.
/// - a [`Json`](ErrorKind::Json) error, if unable to parse the destination file to JSON.
/// - a [`Request`](ErrorKind::Request) error, if unable to send the request or get a body from the response.
/// - a [`Response`](ErrorKind::Response) error, if the request returned an error response.
pub fn execute( &self ) -> Result<Vec<u8>, Error> {
let response = self.send()?;
Ok( response.bytes()?.into() )
}
}
request_builder!(
/// A request builder to generate IDs.
pub GenerateIDsRequest {
/// The number of IDs to return.
count: Option<i64>,
/// The space in which the IDs can be used to create new files.
space: Option<objects::Space>,
/// The type of items which the IDs can be used for.
kind: Option<objects::IDKind>,
},
// HTTP Method
Method::GET,
// API endpoint
("https://www.googleapis.com/drive/v3/files/generateIds"),
);
impl GenerateIDsRequest {
/// Executes this request.
///
/// # Errors
///
/// - a [`UrlParsing`](ErrorKind::UrlParsing) error, if the creation of the request URL failed.
/// - a [`Json`](ErrorKind::Json) error, if unable to parse the destination file to JSON.
/// - a [`Request`](ErrorKind::Request) error, if unable to send the request or get a body from the response.
/// - a [`Response`](ErrorKind::Response) error, if the request returned an error response.
pub fn execute( &self ) -> Result<objects::GeneratedIDs, Error> {
let response = self.send()?;
Ok( serde_json::from_str( &response.text()? )? )
}
}
request_builder!(
/// A request builder to get a file’s metadata by ID.
pub GetRequest {
/// Whether the requesting application supports both My Drives and
/// shared drives.
supports_all_drives: Option<bool>,
/// Specifies which additional view's permissions to include in the
/// response.
///
/// Only `published` is supported.
include_permissions_for_view: Option<String>,
/// A comma-separated list of IDs of labels to include in the
/// [`label_info`](objects::File::label_info) part of the response.
include_labels: Option<String>,
},
// HTTP Method
Method::GET,
// API endpoint
("https://www.googleapis.com/drive/v3/files/{file_id}", file_id),
);
impl GetRequest {
/// Executes this request.
///
/// # Errors
///
/// - a [`UrlParsing`](ErrorKind::UrlParsing) error, if the creation of the request URL failed.
/// - a [`Json`](ErrorKind::Json) error, if unable to parse the destination file to JSON.
/// - a [`Request`](ErrorKind::Request) error, if unable to send the request or get a body from the response.
/// - a [`Response`](ErrorKind::Response) error, if the request returned an error response.
pub fn execute( &self ) -> Result<objects::File, Error> {
let response = self.send()?;
Ok( serde_json::from_str( &response.text()? )? )
}
}
request_builder!(
/// A request builder to get a file’s metadata by ID.
pub GetMediaRequest {
/// Whether the user is acknowledging the risk of downloading known
/// malware or other abusive files.
acknowledge_abuse: Option<bool>,
/// Whether the requesting application supports both My Drives and
/// shared drives.
supports_all_drives: Option<bool>,
/// Specifies which additional view's permissions to include in the
/// response.
///
/// Only `published` is supported.
include_permissions_for_view: Option<String>,
/// A comma-separated list of IDs of labels to include in the
/// [`label_info`](objects::File::label_info) part of the response.
include_labels: Option<String>,
},
// HTTP Method
Method::GET,
// API endpoint
("https://www.googleapis.com/drive/v3/files/{file_id}", file_id),
// Other fields
/// Path to save the contents to.
save_to: Option<PathBuf>
);
impl GetMediaRequest {
/// Executes this request.
///
/// # Errors
///
/// - a [`UrlParsing`](ErrorKind::UrlParsing) error, if the creation of the request URL failed.
/// - a [`Json`](ErrorKind::Json) error, if unable to parse the destination file to JSON.
/// - a [`Request`](ErrorKind::Request) error, if unable to send the request or get a body from the response.
/// - a [`Response`](ErrorKind::Response) error, if the request returned an error response.
pub fn execute( &self ) -> Result<Vec<u8>, Error> {
let mut parameters = self.get_parameters();
parameters.push(( "alt".into(), objects::Alt::Media.to_string() ));
let url = Url::parse_with_params(&self.url, parameters)?;
let request = Client::new()
.request( self.method.clone(), url )
.bearer_auth( self.credentials.get_access_token() );
let response = request.send()?;
if !response.status().is_success() {
return Err( response.into() );
}
let file_bytes: Vec<u8> = response.bytes()?.into();
if let Some(path) = &self.save_to {
use std::io::Write;
let mut file = fs::File::create(path)?;
file.write_all(&file_bytes)?;
}
Ok(file_bytes)
}
}
request_builder!(
/// A request builder to list the user's files.
pub ListRequest {
/// Bodies of items (files/documents) to which the query applies.
///
/// Supported bodies are `user`, `domain`, `drive`, and `allDrives`.
///
/// Prefer `user` or `drive` to `allDrives` for efficiency. By default,
/// corpora is set to `user`. However, this can change depending on the
/// filter set through the [`q`](ListRequest::q) parameter.
corpora: Option<String>,
/// ID of the shared drive to search.
drive_id: Option<String>,
/// Whether both My Drive and shared drive items should be included in
/// results.
include_items_from_all_drives: Option<bool>,
/// A comma-separated list of sort keys.
///
/// Valid keys are `createdTime`, `folder`, `modifiedByMeTime`,
/// `modifiedTime`, `name`, `name_natural`, `quotaBytesUsed`,
/// `recency`, `sharedWithMeTime`, `starred`, and `viewedByMeTime`.
///
/// Each key sorts ascending by default, but can be reversed by adding
/// the `desc` to the end of the key.
order_by: Option<String>,
/// The maximum number of files to return per page.
///
/// Partial or empty result pages are possible even before the end of
/// the files list has been reached.
page_size: Option<i64>,
/// The token for continuing a previous list request on the next page.
///
/// This should be set to the value of
/// [`nest_page_token`](objects::FileList::next_page_token) from the
/// previous response.
page_token: Option<String>,
/// A query for filtering the file results.
///
/// For more information, see Google's
/// [Search for files & folders](https://developers.google.com/drive/api/guides/search-files)
/// guide.
q: Option<String>,
/// A comma-separated list of spaces to query within the corpora.
///
/// Supported values are `drive` and `appDataFolder`.
spaces: Option<String>,
/// Whether the requesting application supports both My Drives and
/// shared drives.
supports_all_drives: Option<bool>,
/// Specifies which additional view's permissions to include in the
/// response.
///
/// Only `published` is supported.
include_permissions_for_view: Option<String>,
/// A comma-separated list of IDs of labels to include in the
/// [`label_info`](objects::File::label_info) part of the response.
include_labels: Option<String>,
},
// HTTP Method
Method::GET,
// API endpoint
("https://www.googleapis.com/drive/v3/files"),
);
impl ListRequest {
/// Executes this request.
///
/// # Errors
///
/// - a [`UrlParsing`](ErrorKind::UrlParsing) error, if the creation of the request URL failed.
/// - a [`Json`](ErrorKind::Json) error, if unable to parse the destination file to JSON.
/// - a [`Request`](ErrorKind::Request) error, if unable to send the request or get a body from the response.
/// - a [`Response`](ErrorKind::Response) error, if the request returned an error response.
pub fn execute( &self ) -> Result<objects::FileList, Error> {
let response = self.send()?;
Ok( serde_json::from_str( &response.text()? )? )
}
}
request_builder!(
/// A request builder to list the labels in a file.
pub ListLabelsRequest {
/// The maximum number of labels to return per page.
///
/// When not set, defaults to 100.
max_results: Option<i64>,
/// The token for continuing a previous list request on the next page.
///
/// This should be set to the value of
/// [`next_page_token`](objects::LabelList::next_page_token) from the
/// previous response.
page_token: Option<String>,
},
// HTTP Method
Method::GET,
// API endpoint
("https://www.googleapis.com/drive/v3/files/{file_id}/listLabels", file_id),
);
impl ListLabelsRequest {
/// Executes this request.
///
/// # Errors
///
/// - a [`UrlParsing`](ErrorKind::UrlParsing) error, if the creation of the request URL failed.
/// - a [`Json`](ErrorKind::Json) error, if unable to parse the destination file to JSON.
/// - a [`Request`](ErrorKind::Request) error, if unable to send the request or get a body from the response.
/// - a [`Response`](ErrorKind::Response) error, if the request returned an error response.
pub fn execute( &self ) -> Result<objects::LabelList, Error> {
let response = self.send()?;
Ok( serde_json::from_str( &response.text()? )? )
}
}
request_builder!(
/// A request builder to modify the labels in a file.
pub ModifyLabelsRequest {},
// HTTP Method
Method::POST,
// API endpoint
("https://www.googleapis.com/drive/v3/files/{file_id}/modifyLabels", file_id),
// Other fields
/// Sets the metadata that the updated file will have in Google Drive.
modifications: Option<Vec<objects::LabelModification>>
);
#[cfg(not(tarpaulin_include))] // Requires a business account
impl ModifyLabelsRequest {
/// Executes this request.
///
/// # Errors
///
/// - a [`UrlParsing`](ErrorKind::UrlParsing) error, if the creation of the
/// request URL failed.
/// - a [`Json`](ErrorKind::Json) error, if unable to parse the destination
/// file to JSON.
/// - a [`Request`](ErrorKind::Request) error, if unable to send the request
/// or get a body from the response.
/// - a [`Response`](ErrorKind::Response) error, if the request returned an
/// error response.
pub fn execute( &self ) -> Result<Vec<objects::Label>, Error> {
let mut modify_request = objects::ModifyLabelsRequest::new();
if let Some(modifications) = &self.modifications {
modify_request.label_modifications = Some( modifications.to_vec() );
}
let request = self.build()?
.body( serde_json::to_string(&modify_request)? );
let response = request.send()?;
if !response.status().is_success() {
return Err( response.into() )
}
let response_text = response.text()?;
let parsed_json = serde_json::from_str::<HashMap<&str, serde_json::Value>> (&response_text)?;
match parsed_json.get("modifiedLabels") {
Some(labels) => Ok( serde_json::from_value(labels.clone())? ),
None => Err( Error {
kind: ErrorKind::Json,
message: "the response did not contain the modified labels"
.to_string(),
} )
}
}
}
request_builder!(
/// A request builder to list the labels in a file.
pub UpdateRequest {
/// The type of upload request to the /upload URI.
upload_type: Option<objects::UploadType>,
/// A comma-separated list of parent IDs to add.
add_parents: Option<String>,
/// Whether to set the `keepForever` field in the new head revision.
///
/// This is only applicable to files with binary content in a Drive.
///
/// Only 200 revisions for the file can be kept forever, if the limit is
/// reached, try deleting pinned revisions.
keep_revision_forever: Option<bool>,
/// A language hint for OCR processing during image import
/// (ISO 639-1 code).
ocr_language: Option<String>,
/// Whether the requesting application supports both My Drives and
/// shared drives.
supports_all_drives: Option<bool>,
/// Whether to use the uploaded content as indexable text.
use_content_as_indexable_text: Option<bool>,
/// Specifies which additional view's permissions to include in the
/// response.
///
/// Only 'published' is supported.
include_permissions_for_view: Option<String>,
/// A comma-separated list of IDs of labels to include in the
/// [`label_info`](objects::File::label_info) part of the response.
include_labels: Option<String>,
},
// HTTP Method
Method::PATCH,
// API endpoint
("https://www.googleapis.com/upload/drive/v3/files/{file_id}", file_id),
// Other fields
/// Sets the metadata that the updated file will have in Google Drive.
metadata: Option<objects::File>,
/// The path of the source file to be uploaded.
content_source: Option<PathBuf>,
/// Use this string as the content of the created file.
content_string: Option<String>,
// Function callbacks
(
/// A callback to receive updates on a resumable upload.
callback: Option<fn(usize, usize)>
),
);
impl UpdateRequest {
/// Gets a media request.
fn get_media_request( &self ) -> Result<RequestBuilder, Error> {
let mut content_bytes = Vec::new();
if self.content_source.is_some() && self.content_string.is_some() {
return Err(Error {
kind: ErrorKind::Request,
message: "an update request can only use one of\
'content_source' or 'content_string'".into()
})
}
if let Some(source) = &self.content_source {
let mut file = fs::File::open(source)?;
file.read_to_end(&mut content_bytes)?;
}
if let Some(string) = &self.content_string {
content_bytes = string.as_bytes().to_vec();
}
let mut request = self.build()?
.header( "Content-Length", content_bytes.len().to_string() )
.body(content_bytes);
let metadata = self.metadata.clone().unwrap_or_default();
if let Some(mime_type) = metadata.mime_type {
request = request.header("Content-Type", mime_type);
}
Ok(request)
}
fn get_metadata_form_part( &self ) -> Result<multipart::Part, Error> {
let metadata_string = serde_json::to_string(&self.metadata)?;
let mut metadata_headers = header::HeaderMap::new();
metadata_headers.insert(
header::CONTENT_TYPE, "application/json; charset=UTF-8".parse()?
);
metadata_headers.insert(
header::CONTENT_DISPOSITION, "form-data; name=\"metadata\"".parse()?
);
Ok( multipart::Part::text(metadata_string)
.headers(metadata_headers) )
}
fn get_file_form_part( &self ) -> Result<multipart::Part, Error> {
let metadata = self.metadata.clone().unwrap_or_default();
let content_mime_type = metadata.mime_type.unwrap_or( "*/*".into() );
let mut file_headers = reqwest::header::HeaderMap::new();
file_headers.insert(
header::CONTENT_TYPE, content_mime_type.parse()?
);
file_headers.insert(
header::CONTENT_DISPOSITION, "form-data; name=\"file\"".parse()?
);
let mut file_part = multipart::Part::text("");
if let Some(source) = &self.content_source {
file_part = multipart::Part::file(source)?;
}
if let Some(string) = &self.content_string {
file_part = multipart::Part::text(string.clone());
}
Ok( file_part.headers(file_headers) )
}
/// Gets a multipart request.
fn get_multipart_request( &self ) -> Result<RequestBuilder, Error> {
let metadata_part = self.get_metadata_form_part()?;
let file_part = self.get_file_form_part()?;
let form = multipart::Form::new()
.part("metadata", metadata_part)
.part("file", file_part);
Ok( self.build()?
.multipart(form) )
}
/// Performs a resumable upload.
fn perform_resumable_upload( &self ) -> Result<objects::File, Error> {
let metadata = self.metadata.clone().unwrap_or_default();
let metadata_string = serde_json::to_string(&metadata)?;
let metadata_size = metadata_string.as_bytes().len();
let content_mime_type = metadata.mime_type.unwrap_or( "*/*".into() );
if self.content_string.is_some() {
return Err(Error {
kind: ErrorKind::Request,
message: String::from("A resumable upload cannot be created\
from a string, it must be a file"),
})
}
let mut file = match &self.content_source {
Some(source) => fs::File::open(source)?,
None => {
return Err(Error {
kind: ErrorKind::Request,
message: String::from("A resumable request must include a\
source file"),
})
}
};
let file_size = file.metadata()?.len();
let request = self.build()?
.header( "X-Upload-Content-Type", &content_mime_type )
.header( "X-Upload-Content-Length", &file_size.to_string() )
.header( "Content-Type", "application/json; charset=UTF-8" )
.header( "Content-Length", &metadata_size.to_string() )
.body(metadata_string);
let response = request.send()?;
if !response.status().is_success() {
return Err( response.into() );
}
let upload_uri = match response.headers().get("location") {
Some(header) => header.to_str()?,
#[cfg(not(tarpaulin_include))]
None => {
return Err(Error {
kind: ErrorKind::Request,
message: String::from("unable to get the resumable upload\
location"),
})
}
};
let mut file_uploader = FileUploader::from_uri(upload_uri);
if let Some(callback) = self.callback {
file_uploader = file_uploader.with_callback(callback);
}
file_uploader.upload_file(&mut file)
}
/// Executes this request.
///
/// # Errors
///
/// - an [`IO`](crate::ErrorKind::IO) error, if the source file does not exist.
/// - a [`UrlParsing`](crate::ErrorKind::UrlParsing) error, if the creation of the request URL failed.
/// - a [`Json`](crate::ErrorKind::Json) error, if unable to parse the destination file to JSON.
/// - a [`Request`](crate::ErrorKind::Request) error, if unable to send the request or get a body from the response.
/// - a [`Response`](crate::ErrorKind::Response) error, if the request returned an error response.
pub fn execute( &self ) -> Result<objects::File, Error> {
let upload_type = self.upload_type.unwrap_or_default();
let request = match upload_type {
objects::UploadType::Media => self.get_media_request()?,
objects::UploadType::Multipart => self.get_multipart_request()?,
objects::UploadType::Resumable => {
return self.perform_resumable_upload()
},
};
let response = request.send()?;
if !response.status().is_success() {
return Err( response.into() );
}
Ok( serde_json::from_str( &response.text()? )? )
}
}
request_builder!(
/// A request builder to modify the labels in a file.
pub WatchRequest {
/// Whether the requesting application supports both My Drives and
/// shared drives.
supports_all_drives: Option<bool>,
/// Whether the user is acknowledging the risk of downloading known
/// malware or other abusive files.
acknowledge_abuse: Option<bool>,
/// Specifies which additional view's permissions to include in the
/// response.
///
/// Only `published` is supported.
include_permissions_for_view: Option<String>,
/// A comma-separated list of IDs of labels to include in the
/// [`label_info`](objects::File::label_info) part of the response.
include_labels: Option<String>,
},
// HTTP Method
Method::POST,
// API endpoint
("https://www.googleapis.com/drive/v3/files/{file_id}/watch", file_id),
// Other fields
/// Sets the metadata that the channel will have.
channel: Option<objects::Channel>
);
impl WatchRequest {
/// Executes this request.
///
/// # Errors
///
/// - a [`UrlParsing`](ErrorKind::UrlParsing) error, if the creation of the
/// request URL failed.
/// - a [`Json`](ErrorKind::Json) error, if unable to parse the destination
/// file to JSON.
/// - a [`Request`](ErrorKind::Request) error, if unable to send the request
/// or get a body from the response.
/// - a [`Response`](ErrorKind::Response) error, if the request returned an
/// error response.
pub fn execute( &self ) -> Result<objects::Channel, Error> {
let channel_metadata = self.channel.clone().unwrap_or_default();
let request = self.build()?
.body( serde_json::to_string(&channel_metadata)? );
let response = request.send()?;
if !response.status().is_success() {
return Err( response.into() )
}
Ok( serde_json::from_str( &response.text()? )? )
}
}
/// Information related to a user's files.
///
/// # Examples:
///
/// List the files in a drive
///
/// ```no_run
/// # use drive_v3::Error;
/// use drive_v3::{Credentials, Drive};
///
/// let credentials_path = "my_credentials.json";
/// let scopes = ["https://www.googleapis.com/auth/drive.metadata.readonly"];
///
/// let credentials = Credentials::from_file(&credentials_path, &scopes)?;
/// let drive = Drive::new(&credentials);
///
/// let file_list = drive.files.list()
/// .fields("files(name, id, mimeType)") // Set what fields will be returned
/// .q("name = 'file_im_looking_for' and not trashed") // search for specific files
/// .execute()?;
///
/// if let Some(files) = file_list.files {
/// for file in &files {
/// println!("{}", file);
/// }
/// }
/// # Ok::<(), Error>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Files {
/// Credentials used to authenticate a user's access to this resource.
credentials: Credentials,
}
impl Files {
/// Creates a new [`Files`] resource with the given [`Credentials`].
pub fn new( credentials: &Credentials ) -> Self {
Self {
credentials: credentials.clone(),
}
}
/// Creates a copy of a file and applies any requested updates with patch
/// semantics.
///
/// See Google's
/// [documentation](https://developers.google.com/drive/api/reference/rest/v3/files/copy)
/// for more information.
///
/// # Requires one of the following OAuth scopes:
///
/// - `https://www.googleapis.com/auth/drive`
/// - `https://www.googleapis.com/auth/drive.appdata`
/// - `https://www.googleapis.com/auth/drive.file`
/// - `https://www.googleapis.com/auth/drive.photos.readonly`
///
/// # Examples:
///
/// ```no_run
/// use drive_v3::objects::File;
/// # use drive_v3::{Error, Credentials, Drive};
/// #
/// # let drive = Drive::new( &Credentials::from_file(
/// # ".secure-files/google_drive_credentials.json",
/// # &["https://www.googleapis.com/auth/drive.file"],
/// # )? );
///
/// // Set the metadata that the copied file will have
/// let metadata = File {
/// name: Some( "my-copy.txt".to_string() ),
/// description: Some( "I copied this using drive_v3!".to_string() ),
/// ..Default::default()
/// };
///
/// // Set the ID of the file you want to copy,
/// // you can get this using files.list()
/// let source_file_id = "some-file-id";
///
/// let copied_file = drive.files.copy(&source_file_id)
/// .metadata(&metadata)
/// .execute()?;
///
/// assert_eq!(copied_file.name, metadata.name);
/// assert_eq!(copied_file.description, metadata.description);
/// # Ok::<(), Error>(())
/// ```
pub fn copy<T: AsRef<str>> ( &self, file_id: T ) -> CopyRequest {
CopyRequest::new(&self.credentials, &file_id)
}
/// Creates a new file.
///
/// See Google's
/// [documentation](https://developers.google.com/drive/api/reference/rest/v3/files/create)
/// for more information.
///
/// # Note:
///
/// You can use any of the [`UploadTypes`](objects::UploadType), but for
/// most uploads I recommend using the
/// [`Resumable`](objects::UploadType::Resumable) type, which will allow you
/// to set a callback to monitor the upload progress.
///
/// # Requires one of the following OAuth scopes:
///
/// - `https://www.googleapis.com/auth/drive`
/// - `https://www.googleapis.com/auth/drive.appdata`
/// - `https://www.googleapis.com/auth/drive.file`
///
/// # Examples:
///
/// Perform a simple upload to create a small media file (5 MB or less)
/// without supplying metadata:
///
/// ```no_run
/// use drive_v3::objects::{File, UploadType};
/// # use drive_v3::{Error, Credentials, Drive};
/// #
/// # let drive = Drive::new( &Credentials::from_file(
/// # ".secure-files/google_drive_credentials.json",
/// # &["https://www.googleapis.com/auth/drive.file"],
/// # )? );
///
/// // A simple upload does not support metadata, however you can use it in
/// // this request to set the MIME type of your new file, any other fields
/// // you set will be ignored.
/// let metadata = File {
/// mime_type: Some( "text/plain".to_string() ),
/// ..Default::default()
/// };
///
/// let my_new_file = drive.files.create()
/// .upload_type(UploadType::Media)
/// .metadata(&metadata)
/// .content_string("This is the content of my new file!")
/// // .content_source("path/to/file.txt") // You can also load a file from the system
/// .execute()?;
///
/// assert_eq!(my_new_file.mime_type, metadata.mime_type);
/// # Ok::<(), Error>(())
/// ```
///
/// Perform a multipart upload to create a small media file (5 MB or less)
/// along with metadata that describes the file, in a single request:
///
/// ```no_run
/// use drive_v3::objects::{File, UploadType};
/// # use drive_v3::{Error, Credentials, Drive};
/// #
/// # let drive = Drive::new( &Credentials::from_file(
/// # ".secure-files/google_drive_credentials.json",
/// # &["https://www.googleapis.com/auth/drive.file"],
/// # )? );
///
/// // Set what information the uploaded file wil have
/// let metadata = File {
/// name: Some( "my-new-file.txt".to_string() ),
/// mime_type: Some( "text/plain".to_string() ),
/// ..Default::default()
/// };
///
/// let my_new_file = drive.files.create()
/// .upload_type(UploadType::Multipart)
/// .metadata(&metadata)
/// .content_source("path/to/file.txt")
/// // .content_string("This is the content of my new file!") // You can use a string
/// .execute()?;
///
/// assert_eq!(my_new_file.name, metadata.name);
/// assert_eq!(my_new_file.mime_type, metadata.mime_type);
/// # Ok::<(), Error>(())
/// ```
///
/// Perform a resumable upload to create a large file (greater than 5 MB):
///
/// ```no_run
/// use drive_v3::objects::{File, UploadType};
/// # use drive_v3::{Error, Credentials, Drive};
/// #
/// # let drive = Drive::new( &Credentials::from_file(
/// # ".secure-files/google_drive_credentials.json",
/// # &["https://www.googleapis.com/auth/drive.file"],
/// # )? );
///
/// // Set what information the uploaded file wil have
/// let metadata = File {
/// name: Some( "my-new-file.txt".to_string() ),
/// mime_type: Some( "text/plain".to_string() ),
/// ..Default::default()
/// };
///
/// // You can set a callback that will be called when a resumable upload
/// // progresses
/// fn progress_callback( total_bytes: usize, uploaded_bytes: usize ) {
/// println!("Uploaded {} bytes, out of a total of {}.", uploaded_bytes, total_bytes);
/// }
///
/// let my_new_file = drive.files.create()
/// .upload_type(UploadType::Resumable)
/// .callback(progress_callback)
/// .metadata(&metadata)
/// .content_source("path/to/file.txt")
/// .execute()?;
///
/// assert_eq!(my_new_file.name, metadata.name);
/// assert_eq!(my_new_file.mime_type, metadata.mime_type);
/// # Ok::<(), Error>(())
/// ```
pub fn create( &self ) -> CreateRequest {
CreateRequest::new(&self.credentials)
}
/// Permanently deletes a file owned by the user without moving it to the
/// trash.
///
/// If the file belongs to a shared drive, the user must be an organizer on
/// the parent folder. If the target is a folder, all descendants owned by
/// the user are also deleted.
///
/// # Requires one of the following OAuth scopes:
///
/// - `https://www.googleapis.com/auth/drive`
/// - `https://www.googleapis.com/auth/drive.appdata`
/// - `https://www.googleapis.com/auth/drive.file`
///
/// # Examples:
///
/// ```no_run
/// # use drive_v3::{Error, Credentials, Drive};
/// #
/// # let drive = Drive::new( &Credentials::from_file(
/// # ".secure-files/google_drive_credentials.json",
/// # &["https://www.googleapis.com/auth/drive.file"],
/// # )? );
/// #
/// let my_file_id = "example-id";
///
/// drive.files.delete(&my_file_id).execute()?;
///
/// # Ok::<(), Error>(())
/// ```
pub fn delete<T: AsRef<str>> ( &self, file_id: T ) -> DeleteRequest {
DeleteRequest::new(&self.credentials, &file_id)
}
/// Permanently deletes all of the user's trashed files.
///
/// # Note:
///
/// The emptying of the trash may take some time to be reflected in a user's
/// Drive.
///
/// # Requires the following OAuth scope:
///
/// - `https://www.googleapis.com/auth/drive`
///
/// # Examples:
///
/// ```no_run
/// # use drive_v3::{Error, Credentials, Drive};
/// #
/// # let drive = Drive::new( &Credentials::from_file(
/// # ".secure-files/google_drive_credentials.json",
/// # &["https://www.googleapis.com/auth/drive"],
/// # )? );
/// #
/// drive.files.empty_trash()
/// // .drive_id("my-drive-id") // You can specify which drive to empty the trash from
/// .execute()?;
///
/// # Ok::<(), Error>(())
/// ```
#[cfg(not(tarpaulin_include))] // Requires higher permissions
pub fn empty_trash( &self ) -> EmptyTrashRequest {
EmptyTrashRequest::new(&self.credentials)
}
/// Exports a Google Workspace document to the requested MIME type and
/// returns exported byte content (limited to 10MB).
///
/// For more information on the supported export MIME types, check Google's
/// [documentation](https://developers.google.com/drive/api/guides/ref-export-formats).
///
/// # Note:
///
/// This request requires you to set the
/// [`mime_type`](ExportRequest::mime_type) of the file to export.
///
/// # Requires one of the following OAuth scopes:
///
/// - `https://www.googleapis.com/auth/drive`
/// - `https://www.googleapis.com/auth/drive.file`
/// - `https://www.googleapis.com/auth/drive.readonly`
///
/// # Examples:
///
/// ```no_run
/// use std::fs;
/// use std::io::Write;
/// # use drive_v3::{Error, Credentials, Drive};
/// #
/// # let drive = Drive::new( &Credentials::from_file(
/// # ".secure-files/google_drive_credentials.json",
/// # &["https://www.googleapis.com/auth/drive.file"],
/// # )? );
/// #
/// let my_file_id = "file-id";
/// let my_exported_mime_type = "application/pdf";
///
/// let exported_bytes = drive.files.export(&my_file_id)
/// .mime_type(my_exported_mime_type)
/// .execute()?;
///
/// // Write the bytes to a file
/// let mut file = fs::File::create("exported-file.pdf")?;
/// file.write_all(&exported_bytes)?;
///
/// # Ok::<(), Error>(())
/// ```
#[cfg(not(tarpaulin_include))] // Requires higher permissions
pub fn export<T: AsRef<str>> ( &self, file_id: T ) -> ExportRequest {
ExportRequest::new(&self.credentials, &file_id)
}
/// Generates a set of file IDs which can be provided in create or copy
/// requests.
///
/// # Requires one of the following OAuth scopes:
///
/// - `https://www.googleapis.com/auth/drive`
/// - `https://www.googleapis.com/auth/drive.appdata`
/// - `https://www.googleapis.com/auth/drive.file`
///
/// # Examples:
///
/// ```no_run
/// use drive_v3::objects::{Space, IDKind};
/// # use drive_v3::{Error, Credentials, Drive};
/// #
/// # let drive = Drive::new( &Credentials::from_file(
/// # ".secure-files/google_drive_credentials.json",
/// # &["https://www.googleapis.com/auth/drive.file"],
/// # )? );
///
/// let my_generated_ids = drive.files.generate_ids()
/// .count(5) // How many IDs to generate
/// .space(Space::Drive) // Set the space in which the IDs can be used
/// .kind(IDKind::Files) // Set the type of the IDs
/// .execute()?;
///
/// for id in &my_generated_ids.ids {
/// println!("Generated this ID: {}", id);
/// }
/// # Ok::<(), Error>(())
/// ```
pub fn generate_ids( &self ) -> GenerateIDsRequest {
GenerateIDsRequest::new(&self.credentials)
}
/// Gets a file's metadata by ID.
///
/// # Note:
///
/// To get the content of a file you can use [`get_media`](Files::get_media)
/// (only works if the file is stored in Drive).
///
/// To download Google Docs, Sheets, and Slides use
/// [`export`](Files::export) instead.
///
/// # Requires one of the following OAuth scopes:
///
/// - `https://www.googleapis.com/auth/drive`
/// - `https://www.googleapis.com/auth/drive.appdata`
/// - `https://www.googleapis.com/auth/drive.file`
/// - `https://www.googleapis.com/auth/drive.metadata`
/// - `https://www.googleapis.com/auth/drive.metadata.readonly`
/// - `https://www.googleapis.com/auth/drive.photos.readonly`
/// - `https://www.googleapis.com/auth/drive.readonly`
///
/// # Examples:
///
/// ```no_run
/// # use drive_v3::{Error, Credentials, Drive};
/// #
/// # let drive = Drive::new( &Credentials::from_file(
/// # ".secure-files/google_drive_credentials.json",
/// # &["https://www.googleapis.com/auth/drive.file"],
/// # )? );
/// #
/// let my_file_id = "file-id";
///
/// let file_metadata = drive.files.get(&my_file_id).execute()?;
///
/// println!("Look at this metadata:\n{}", file_metadata);
/// # Ok::<(), Error>(())
/// ```
pub fn get<T: AsRef<str>> ( &self, file_id: T ) -> GetRequest {
GetRequest::new(&self.credentials, &file_id)
}
/// Gets a file's content by ID.
///
/// # Requires one of the following OAuth scopes:
///
/// - `https://www.googleapis.com/auth/drive`
/// - `https://www.googleapis.com/auth/drive.appdata`
/// - `https://www.googleapis.com/auth/drive.file`
/// - `https://www.googleapis.com/auth/drive.metadata`
/// - `https://www.googleapis.com/auth/drive.metadata.readonly`
/// - `https://www.googleapis.com/auth/drive.photos.readonly`
/// - `https://www.googleapis.com/auth/drive.readonly`
///
/// # Examples:
///
/// ```no_run
/// # use drive_v3::{Error, Credentials, Drive};
/// #
/// # let drive = Drive::new( &Credentials::from_file(
/// # ".secure-files/google_drive_credentials.json",
/// # &["https://www.googleapis.com/auth/drive.file"],
/// # )? );
/// #
/// let my_text_file_id = "file-id";
///
/// let file_bytes = drive.files.get_media(&my_text_file_id)
/// // .save_to("my_downloaded_file.txt") // Save the contents to a path
/// .execute()?;
///
/// let content = String::from_utf8_lossy(&file_bytes);
///
/// println!("content: {}", content);
/// # Ok::<(), Error>(())
/// ```
pub fn get_media<T: AsRef<str>> ( &self, file_id: T ) -> GetMediaRequest {
GetMediaRequest::new(&self.credentials, &file_id)
}
/// Lists the user's files.
///
/// This method accepts the [`q`](ListRequest::q) parameter, which is a
/// search query combining one or more search terms.
///
/// For more information, see Google's
/// [Search for files & folders](https://developers.google.com/drive/api/guides/search-files)
/// guide.
///
/// # Note
///
/// This method returns all files by default, including trashed files. If
/// you don't want trashed files to appear in the list, use the
/// `trashed=false` or `not trashed` in the [`q`](ListRequest::q) parameter
/// to remove trashed files from the results.
///
/// # Requires one of the following OAuth scopes:
///
/// - `https://www.googleapis.com/auth/drive`
/// - `https://www.googleapis.com/auth/drive.appdata`
/// - `https://www.googleapis.com/auth/drive.file`
/// - `https://www.googleapis.com/auth/drive.metadata`
/// - `https://www.googleapis.com/auth/drive.metadata.readonly`
/// - `https://www.googleapis.com/auth/drive.photos.readonly`
/// - `https://www.googleapis.com/auth/drive.readonly`
///
/// # Examples:
///
/// ```no_run
/// # use drive_v3::{Error, Credentials, Drive};
/// #
/// # let drive = Drive::new( &Credentials::from_file(
/// # ".secure-files/google_drive_credentials.json",
/// # &["https://www.googleapis.com/auth/drive.file"],
/// # )? );
/// #
/// let file_list = drive.files.list()
/// .fields("files(name, id, mimeType)") // Set what fields will be returned
/// .q("name = 'file_im_looking_for' and not trashed") // search for specific files
/// .execute()?;
///
/// if let Some(files) = file_list.files {
/// for file in &files {
/// println!("{}", file);
/// }
/// }
/// # Ok::<(), Error>(())
/// ```
pub fn list( &self ) -> ListRequest {
ListRequest::new(&self.credentials)
}
/// Lists the labels on a file.
///
/// # Requires one of the following OAuth scopes:
///
/// - `https://www.googleapis.com/auth/drive`
/// - `https://www.googleapis.com/auth/drive.file`
/// - `https://www.googleapis.com/auth/drive.metadata`
/// - `https://www.googleapis.com/auth/drive.metadata.readonly`
/// - `https://www.googleapis.com/auth/drive.readonly`
///
/// # Examples:
///
/// ```no_run
/// # use drive_v3::{Error, Credentials, Drive};
/// #
/// # let drive = Drive::new( &Credentials::from_file(
/// # ".secure-files/google_drive_credentials.json",
/// # &["https://www.googleapis.com/auth/drive.file"],
/// # )? );
/// #
/// let my_file_id = "file-id";
///
/// let label_list = drive.files.list_labels(&my_file_id)
/// .max_results(10)
/// .execute()?;
///
/// if let Some(labels) = label_list.labels {
/// for label in &labels {
/// println!("{}", label);
/// }
/// }
/// # Ok::<(), Error>(())
/// ```
pub fn list_labels<T: AsRef<str>> ( &self, file_id: T ) -> ListLabelsRequest {
ListLabelsRequest::new(&self.credentials, &file_id)
}
/// Modifies the set of labels applied to a file.
///
/// Returns a list of the labels that were added or modified.
///
/// # Note
///
/// As of now, labels on files are not supported on personal (free) Google
/// Drive accounts.
///
/// # Requires one of the following OAuth scopes:
///
/// - `https://www.googleapis.com/auth/drive`
/// - `https://www.googleapis.com/auth/drive.file`
/// - `https://www.googleapis.com/auth/drive.metadata`
///
/// # Examples:
///
/// ```no_run
/// use drive_v3::objects::{LabelModification, FieldModification};
/// # use drive_v3::{Error, Credentials, Drive};
/// #
/// # let drive = Drive::new( &Credentials::from_file(
/// # ".secure-files/google_drive_credentials.json",
/// # &["https://www.googleapis.com/auth/drive.file"],
/// # )? );
///
/// let label_modifications = vec![
/// LabelModification::from(
/// "label-id",
/// &vec![
/// FieldModification {
/// set_text_values: Some( vec!["text".into(), "other_text".into()] ),
/// ..Default::default()
/// }
/// ]
/// )
/// ];
///
/// let my_file_id = "file-id";
///
/// let modified_labels = drive.files.modify_labels(&my_file_id)
/// .modifications(label_modifications)
/// .execute()?;
///
/// for label in &modified_labels {
/// println!("this label was modified:\n{}", label);
/// }
/// # Ok::<(), Error>(())
/// ```
#[cfg(not(tarpaulin_include))] // Requires a business account
pub fn modify_labels<T: AsRef<str>> ( &self, file_id: T ) -> ModifyLabelsRequest {
ModifyLabelsRequest::new(&self.credentials, &file_id)
}
/// Updates a file's metadata and/or content.
///
/// When calling this method, only populate fields in the request that you
/// want to modify. When updating fields, some fields might be changed
/// automatically, such as [`modified_time`](objects::File::modified_time).
///
/// This method supports patch semantics.
///
/// # Requires one of the following OAuth scopes:
///
/// - `https://www.googleapis.com/auth/drive`
/// - `https://www.googleapis.com/auth/drive.appdata`
/// - `https://www.googleapis.com/auth/drive.file`
///
/// # Examples:
///
/// Perform a simple upload to create a small media file (5 MB or less)
/// without supplying metadata:
///
/// ```no_run
/// use drive_v3::objects::{File, UploadType};
/// # use drive_v3::{Error, Credentials, Drive};
/// #
/// # let drive = Drive::new( &Credentials::from_file(
/// # ".secure-files/google_drive_credentials.json",
/// # &["https://www.googleapis.com/auth/drive.file"],
/// # )? );
/// #
/// // A simple upload does not support metadata, however you can use it in
/// // this request to set the MIME type of your new file, any other fields
/// // you set will be ignored.
/// let metadata = File {
/// mime_type: Some( "text/plain".to_string() ),
/// ..Default::default()
/// };
///
/// let my_file_id = "file-id";
///
/// let my_new_file = drive.files.update(&my_file_id)
/// .upload_type(UploadType::Media)
/// .metadata(&metadata)
/// .content_string("This is the content of my new file!")
/// // .content_source("path/to/file.txt") // You can also load a file from the system
/// .execute()?;
///
/// # Ok::<(), Error>(())
/// ```
///
/// Perform a multipart upload to create a small media file (5 MB or less)
/// along with metadata that describes the file, in a single request:
///
/// ```no_run
/// use drive_v3::objects::{File, UploadType};
/// # use drive_v3::{Error, Credentials, Drive};
/// #
/// # let drive = Drive::new( &Credentials::from_file(
/// # ".secure-files/google_drive_credentials.json",
/// # &["https://www.googleapis.com/auth/drive.file"],
/// # )? );
/// #
/// // Set what information the uploaded file wil have
/// let metadata = File {
/// name: Some( "my-new-file.txt".to_string() ),
/// mime_type: Some( "text/plain".to_string() ),
/// ..Default::default()
/// };
///
/// let my_file_id = "file-id";
///
/// let my_new_file = drive.files.update(&my_file_id)
/// .upload_type(UploadType::Multipart)
/// .metadata(&metadata)
/// .content_source("path/to/file.txt")
/// // .content_string("This is the content of my new file!") // You can use a string
/// .execute()?;
///
/// # Ok::<(), Error>(())
/// ```
///
/// Perform a resumable upload to create a large file (greater than 5 MB):
///
/// ```no_run
/// use drive_v3::objects::{File, UploadType};
/// # use drive_v3::{Error, Credentials, Drive};
/// #
/// # let drive = Drive::new( &Credentials::from_file(
/// # ".secure-files/google_drive_credentials.json",
/// # &["https://www.googleapis.com/auth/drive.file"],
/// # )? );
/// #
/// // Set what information the uploaded file wil have
/// let metadata = File {
/// name: Some( "my-new-file.txt".to_string() ),
/// mime_type: Some( "text/plain".to_string() ),
/// ..Default::default()
/// };
///
/// // You can set a callback that will be called when a resumable upload
/// // progress, that way you can monitor and display how far along your
/// // file upload is
/// fn progress_callback( total_bytes: usize, uploaded_bytes: usize ) {
/// println!("Uploaded {} bytes, out of a total of {}.", uploaded_bytes, total_bytes);
/// }
///
/// let my_file_id = "file-id";
///
/// let my_new_file = drive.files.update(&my_file_id)
/// .upload_type(UploadType::Resumable)
/// .callback(progress_callback)
/// .metadata(&metadata)
/// .content_source("path/to/file.txt")
/// .execute()?;
///
/// # Ok::<(), Error>(())
/// ```
pub fn update<T: AsRef<str>> ( &self, file_id: T ) -> UpdateRequest {
UpdateRequest::new(&self.credentials, &file_id)
}
/// Subscribes to changes to a file.
///
/// # Note
///
/// In order to subscribe to a file's changes, you must provide a
/// [`Channel`](objects::Channel) with an `id` and an `address` which is the
/// one that will receive the notifications. This can be done by creating a
/// channel using [`from`](objects::Channel::from).
///
/// For more information on channels, see Google's
/// [documentation](https://developers.google.com/drive/api/guides/push).
///
/// # Requires one of the following OAuth scopes:
///
/// - `https://www.googleapis.com/auth/drive`
/// - `https://www.googleapis.com/auth/drive.appdata`
/// - `https://www.googleapis.com/auth/drive.file`
/// - `https://www.googleapis.com/auth/drive.metadata`
/// - `https://www.googleapis.com/auth/drive.metadata.readonly`
/// - `https://www.googleapis.com/auth/drive.photos.readonly`
/// - `https://www.googleapis.com/auth/drive.readonly`
///
/// # Examples:
///
/// ```no_run
/// use drive_v3::objects::Channel;
/// # use drive_v3::{Error, Credentials, Drive};
/// #
/// # let drive = Drive::new( &Credentials::from_file(
/// # ".secure-files/google_drive_credentials.json",
/// # &["https://www.googleapis.com/auth/drive.file"],
/// # )? );
///
/// let channel_id = "my-channel-id";
/// let channel_address = "https://mydomain.com/channel-notifications";
/// let channel = Channel::from(&channel_id, &channel_address);
///
/// let my_file_id = "file-id";
///
/// let created_channel = drive.files.watch(&my_file_id)
/// .channel(&channel)
/// .execute()?;
///
/// println!("this is the created channel:\n{}", created_channel);
/// # Ok::<(), Error>(())
/// ```
pub fn watch<T: AsRef<str>> ( &self, file_id: T ) -> WatchRequest {
WatchRequest::new(&self.credentials, &file_id)
}
}
#[cfg(test)]
mod tests {
use std::fs;
use super::Files;
use std::io::Write;
use std::path::PathBuf;
use crate::{objects, Error, ErrorKind};
use crate::utils::test::{INVALID_CREDENTIALS, LOCAL_STORAGE_IN_USE, VALID_CREDENTIALS};
fn get_resource() -> Files {
Files::new(&VALID_CREDENTIALS)
}
fn get_invalid_resource() -> Files {
Files::new(&INVALID_CREDENTIALS)
}
fn delete_file( file: &objects::File ) -> Result<(), Error> {
get_resource().delete( file.clone().id.unwrap() ).execute()
}
fn get_test_metadata() -> objects::File {
objects::File {
name: Some( "test.txt".to_string() ),
description: Some( "a test file".to_string() ),
mime_type: Some( "text/plain".to_string() ),
..Default::default()
}
}
fn get_test_file() -> (fs::File, PathBuf) {
let path = PathBuf::from("test-file.txt");
let mut test_file = fs::File::create(&path).unwrap();
test_file.write_all( "content".as_bytes() ).unwrap();
(test_file, path)
}
fn get_test_drive_file() -> Result<objects::File, Error> {
let metadata = get_test_metadata();
get_resource().create()
.upload_type(objects::UploadType::Multipart)
.metadata(&metadata)
.content_string("content")
.execute()
}
#[test]
fn new_test() {
let valid_resource = get_resource();
let invalid_resource = get_invalid_resource();
assert_eq!( valid_resource.credentials, VALID_CREDENTIALS.clone() );
assert_eq!( invalid_resource.credentials, INVALID_CREDENTIALS.clone() );
}
#[test]
fn copy_test() {
let metadata = get_test_metadata();
let test_drive_file = get_test_drive_file().unwrap();
let response = get_resource().copy( &test_drive_file.clone().id.unwrap() )
.fields("*")
.metadata(&metadata)
.execute().unwrap();
assert_eq!(response.name, metadata.name);
assert_eq!(response.description, metadata.description);
assert_eq!(response.mime_type, metadata.mime_type);
delete_file(&test_drive_file).expect("Failed to cleanup a created file");
delete_file(&response).expect("Failed to cleanup a created file");
}
#[test]
fn copy_invalid_response_test() {
let response = get_resource().copy("invalid-id")
.execute();
assert!( response.is_err() );
assert_eq!( response.unwrap_err().kind, ErrorKind::Response );
}
#[test]
fn create_media_test() {
// Only run if no other tests are using the local storage
let _unused = LOCAL_STORAGE_IN_USE.lock().unwrap();
let metadata = get_test_metadata();
let (_, test_file_path) = get_test_file();
let response = get_resource().create()
.upload_type(objects::UploadType::Media)
.metadata(&metadata)
.content_source(&test_file_path)
.execute()
.unwrap();
assert_eq!(response.mime_type, metadata.mime_type);
delete_file(&response).expect("Failed to cleanup a created file");
fs::remove_file(&test_file_path).expect("Failed to cleanup a created file");
}
#[test]
fn create_multipart_test() {
// Only run if no other tests are using the local storage
let _unused = LOCAL_STORAGE_IN_USE.lock().unwrap();
let metadata = get_test_metadata();
let (_, test_file_path) = get_test_file();
let response = get_resource().create()
.fields("*")
.upload_type(objects::UploadType::Multipart)
.metadata(&metadata)
.content_string("content")
.execute()
.unwrap();
assert_eq!(response.name, metadata.name);
assert_eq!(response.description, metadata.description);
assert_eq!(response.mime_type, metadata.mime_type);
delete_file(&response).expect("Failed to cleanup a created file");
let response = get_resource().create()
.fields("*")
.upload_type(objects::UploadType::Multipart)
.metadata(&metadata)
.content_source(&test_file_path)
.execute()
.unwrap();
assert_eq!(response.name, metadata.name);
assert_eq!(response.description, metadata.description);
assert_eq!(response.mime_type, metadata.mime_type);
delete_file(&response).expect("Failed to cleanup a created file");
fs::remove_file(&test_file_path).expect("Failed to cleanup a created file");
}
#[test]
fn create_resumable_test() {
// Only run if no other tests are using the local storage
let _unused = LOCAL_STORAGE_IN_USE.lock().unwrap();
fn callback( _: usize, _: usize ) {}
let metadata = get_test_metadata();
let (_, test_file_path) = get_test_file();
let response = get_resource().create()
.fields("*")
.upload_type(objects::UploadType::Resumable)
.metadata(&metadata)
.content_source(&test_file_path)
.callback(callback)
.execute()
.unwrap();
assert_eq!(response.name, metadata.name);
assert_eq!(response.description, metadata.description);
assert_eq!(response.mime_type, metadata.mime_type);
delete_file(&response).expect("Failed to cleanup a created file");
fs::remove_file(&test_file_path).expect("Failed to cleanup a created file");
}
#[test]
fn create_resumable_invalid_response_test() {
// Only run if no other tests are using the local storage
let _unused = LOCAL_STORAGE_IN_USE.lock().unwrap();
let (_, test_file_path) = get_test_file();
let response = get_invalid_resource().create()
.upload_type(objects::UploadType::Resumable)
.content_source(&test_file_path)
.execute();
assert!( response.is_err() );
assert_eq!( response.unwrap_err().kind, ErrorKind::Response );
fs::remove_file(&test_file_path).expect("Failed to cleanup a created file");
}
#[test]
fn create_multiple_sources_test() {
// Only run if no other tests are using the local storage
let _unused = LOCAL_STORAGE_IN_USE.lock().unwrap();
let (_, test_file_path) = get_test_file();
let response = get_resource().create()
.upload_type(objects::UploadType::Media)
.content_string("content")
.content_source(&test_file_path)
.execute();
assert!( response.is_err() );
assert_eq!( response.unwrap_err().kind, ErrorKind::Request );
fs::remove_file(&test_file_path).expect("Failed to cleanup a created file");
}
#[test]
fn create_invalid_resumable_test() {
let response = get_resource().create()
.upload_type(objects::UploadType::Resumable)
.content_string("content")
.execute();
assert!( response.is_err() );
assert_eq!( response.unwrap_err().kind, ErrorKind::Request );
}
#[test]
fn create_no_source_resumable_test() {
let response = get_resource().create()
.upload_type(objects::UploadType::Resumable)
.execute();
assert!( response.is_err() );
assert_eq!( response.unwrap_err().kind, ErrorKind::Request );
}
#[test]
fn create_invalid_response_test() {
let response = get_invalid_resource().create()
.content_string("content")
.execute();
assert!( response.is_err() );
assert_eq!( response.unwrap_err().kind, ErrorKind::Response );
}
#[test]
fn generate_ids_test() {
let response = get_resource().generate_ids()
.count(8)
.space(objects::Space::Drive)
.kind(objects::IDKind::Files)
.execute().unwrap();
assert_eq!( response.ids.len(), 8 );
assert_eq!( response.space, objects::Space::Drive );
}
#[test]
fn get_test() {
let metadata = get_test_metadata();
let test_drive_file = get_test_drive_file().unwrap();
let response = get_resource().get( test_drive_file.clone().id.unwrap() )
.fields("*")
.execute().unwrap();
assert_eq!(response.name, metadata.name);
assert_eq!(response.description, metadata.description);
assert_eq!(response.mime_type, metadata.mime_type);
delete_file(&test_drive_file).expect("Failed to cleanup a created file");
}
#[test]
fn get_media_test() {
// Only run if no other tests are using the local storage
let _unused = LOCAL_STORAGE_IN_USE.lock().unwrap();
let test_drive_file = get_test_drive_file().unwrap();
let save_path = PathBuf::from("saved.txt");
let response = get_resource().get_media( test_drive_file.clone().id.unwrap() )
.save_to(&save_path)
.execute().unwrap();
let content = String::from_utf8(response).unwrap();
let saved_content = fs::read_to_string(&save_path).unwrap();
assert_eq!(&content, "content");
assert_eq!(&saved_content, "content");
delete_file(&test_drive_file).expect("Failed to cleanup a created file");
fs::remove_file(&save_path).expect("Failed to cleanup a created file");
}
#[test]
fn get_media_invalid_response_test() {
let response = get_invalid_resource().get_media("invalid-id")
.execute();
assert!( response.is_err() );
assert_eq!( response.unwrap_err().kind, ErrorKind::Response );
}
#[test]
fn list_test() {
let response = get_resource().list()
.execute();
assert!( response.is_ok() );
}
#[test]
fn list_labels_test() {
let test_drive_file = get_test_drive_file().unwrap();
let response = get_resource().list_labels( test_drive_file.clone().id.unwrap() )
.execute();
assert!( response.is_ok() );
delete_file(&test_drive_file).expect("Failed to cleanup a created file");
}
#[test]
fn update_test() {
// Only run if no other tests are using the local storage
let _unused = LOCAL_STORAGE_IN_USE.lock().unwrap();
let metadata = get_test_metadata();
let test_drive_file = get_test_drive_file().unwrap();
let (_, test_file_path) = get_test_file();
let response = get_resource().update( test_drive_file.clone().id.unwrap() )
.upload_type(objects::UploadType::Media)
.metadata(&metadata)
.content_source(&test_file_path)
.execute()
.unwrap();
assert_eq!(response.id, test_drive_file.id);
assert_eq!(response.mime_type, metadata.mime_type);
delete_file(&test_drive_file).expect("Failed to cleanup a created file");
fs::remove_file(&test_file_path).expect("Failed to cleanup a created file");
}
#[test]
fn update_string_test() {
// Only run if no other tests are using the local storage
let _unused = LOCAL_STORAGE_IN_USE.lock().unwrap();
let metadata = get_test_metadata();
let test_drive_file = get_test_drive_file().unwrap();
let (_, test_file_path) = get_test_file();
let response = get_resource().update( test_drive_file.clone().id.unwrap() )
.upload_type(objects::UploadType::Media)
.metadata(&metadata)
.content_string("new content")
.execute()
.unwrap();
assert_eq!(response.id, test_drive_file.id);
assert_eq!(response.mime_type, metadata.mime_type);
delete_file(&test_drive_file).expect("Failed to cleanup a created file");
fs::remove_file(&test_file_path).expect("Failed to cleanup a created file");
}
#[test]
fn update_multipart_test() {
// Only run if no other tests are using the local storage
let _unused = LOCAL_STORAGE_IN_USE.lock().unwrap();
let metadata = get_test_metadata();
let test_drive_file = get_test_drive_file().unwrap();
let (_, test_file_path) = get_test_file();
let response = get_resource().update( test_drive_file.clone().id.unwrap() )
.fields("*")
.upload_type(objects::UploadType::Multipart)
.metadata(&metadata)
.content_string("content")
.execute()
.unwrap();
assert_eq!(response.id, test_drive_file.id);
assert_eq!(response.name, metadata.name);
assert_eq!(response.description, metadata.description);
assert_eq!(response.mime_type, metadata.mime_type);
let response = get_resource().update( test_drive_file.clone().id.unwrap() )
.fields("*")
.upload_type(objects::UploadType::Multipart)
.metadata(&metadata)
.content_source(&test_file_path)
.execute()
.unwrap();
assert_eq!(response.id, test_drive_file.id);
assert_eq!(response.name, metadata.name);
assert_eq!(response.description, metadata.description);
assert_eq!(response.mime_type, metadata.mime_type);
delete_file(&test_drive_file).expect("Failed to cleanup a created file");
fs::remove_file(&test_file_path).expect("Failed to cleanup a created file");
}
#[test]
fn update_resumable_test() {
// Only run if no other tests are using the local storage
let _unused = LOCAL_STORAGE_IN_USE.lock().unwrap();
fn callback( _: usize, _: usize ) {}
let metadata = get_test_metadata();
let test_drive_file = get_test_drive_file().unwrap();
let (_, test_file_path) = get_test_file();
let response = get_resource().update( test_drive_file.clone().id.unwrap() )
.fields("*")
.upload_type(objects::UploadType::Resumable)
.metadata(&metadata)
.content_source(&test_file_path)
.callback(callback)
.execute()
.unwrap();
assert_eq!(response.id, test_drive_file.id);
assert_eq!(response.name, metadata.name);
assert_eq!(response.description, metadata.description);
assert_eq!(response.mime_type, metadata.mime_type);
delete_file(&test_drive_file).expect("Failed to cleanup a created file");
fs::remove_file(&test_file_path).expect("Failed to cleanup a created file");
}
#[test]
fn update_invalid_id_test() {
let response = get_resource().update("invalid-id")
.execute();
assert!( response.is_err() );
assert_eq!( response.unwrap_err().kind, ErrorKind::Response );
}
#[test]
fn update_resumable_invalid_response_test() {
// Only run if no other tests are using the local storage
let _unused = LOCAL_STORAGE_IN_USE.lock().unwrap();
let (_, test_file_path) = get_test_file();
let response = get_invalid_resource().update("invalid-id")
.upload_type(objects::UploadType::Resumable)
.content_source(&test_file_path)
.execute();
assert!( response.is_err() );
assert_eq!( response.unwrap_err().kind, ErrorKind::Response );
fs::remove_file(&test_file_path).expect("Failed to cleanup a created file");
}
#[test]
fn update_invalid_response_test() {
let response = get_invalid_resource().update("invalid-id")
.content_string("content")
.execute();
assert!( response.is_err() );
assert_eq!( response.unwrap_err().kind, ErrorKind::Response );
}
#[test]
fn update_multiple_sources_test() {
// Only run if no other tests are using the local storage
let _unused = LOCAL_STORAGE_IN_USE.lock().unwrap();
let test_drive_file = get_test_drive_file().unwrap();
let (_, test_file_path) = get_test_file();
let response = get_resource().update( test_drive_file.clone().id.unwrap() )
.upload_type(objects::UploadType::Media)
.content_string("content")
.content_source(&test_file_path)
.execute();
assert!( response.is_err() );
assert_eq!( response.unwrap_err().kind, ErrorKind::Request );
delete_file(&test_drive_file).expect("Failed to cleanup a created file");
fs::remove_file(&test_file_path).expect("Failed to cleanup a created file");
}
#[test]
fn update_invalid_resumable_test() {
let test_drive_file = get_test_drive_file().unwrap();
let response = get_resource().update( test_drive_file.clone().id.unwrap() )
.upload_type(objects::UploadType::Resumable)
.content_string("content")
.execute();
assert!( response.is_err() );
assert_eq!( response.unwrap_err().kind, ErrorKind::Request );
delete_file(&test_drive_file).expect("Failed to cleanup a created file");
}
#[test]
fn update_no_source_resumable_test() {
let test_drive_file = get_test_drive_file().unwrap();
let response = get_resource().update( test_drive_file.clone().id.unwrap() )
.upload_type(objects::UploadType::Resumable)
.execute();
assert!( response.is_err() );
assert_eq!( response.unwrap_err().kind, ErrorKind::Request );
delete_file(&test_drive_file).expect("Failed to cleanup a created file");
}
#[test]
fn watch_test() {
let test_drive_file = get_test_drive_file().unwrap();
let channel_id = "channel_id".to_string();
let channel_address = "https://wwwgoogle.com".to_string();
let channel = objects::Channel::from(&channel_id, &channel_address);
let response = get_resource().watch( test_drive_file.clone().id.unwrap() )
.channel(&channel)
.execute();
assert!( response.is_ok() );
assert_eq!( response.unwrap().id, Some(channel_id) );
delete_file(&test_drive_file).expect("Failed to cleanup a created file");
}
#[test]
fn watch_invalid_response_test() {
let response = get_invalid_resource().watch("invalid-id")
.execute();
assert!( response.is_err() );
assert_eq!( response.unwrap_err().kind, ErrorKind::Response );
}
}