Compare commits
1291
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
544757a33b | ||
|
|
bfcf6baf93 | ||
|
|
b2b5b7598c | ||
|
|
5f943aabc8 | ||
|
|
84c785bc36 | ||
|
|
993146375e | ||
|
|
bbe791a886 | ||
|
|
1545ace8f2 | ||
|
|
bcac8fdc83 | ||
|
|
15e1a6bee7 | ||
|
|
9710ded60f | ||
|
|
5f3672102c | ||
|
|
644cc69108 | ||
|
|
1415666074 | ||
|
|
bae550c71e | ||
|
|
beff081abb | ||
|
|
7f5ee5d81f | ||
|
|
8b41dfa50a | ||
|
|
0d8bcc08da | ||
|
|
d3b7f14b66 | ||
|
|
f66928a846 | ||
|
|
3b1122c888 | ||
|
|
463a18aa07 | ||
|
|
0a932dc1f2 | ||
|
|
8856e0e559 | ||
|
|
3b6df71838 | ||
|
|
31de631b22 | ||
|
|
189ef5f257 | ||
|
|
2f67681e3b | ||
|
|
41127965b0 | ||
|
|
8171671d82 | ||
|
|
75617c0c3b | ||
|
|
8b9d23916b | ||
|
|
e43b79e33d | ||
|
|
459cc70a50 | ||
|
|
20578f3f89 | ||
|
|
15da53696e | ||
|
|
2bddba118e | ||
|
|
c7e5976e11 | ||
|
|
f0bf9cfda1 | ||
|
|
671dd047f7 | ||
|
|
6272ca74bc | ||
|
|
f5af761466 | ||
|
|
06f1c0c61c | ||
|
|
e6a9f005d6 | ||
|
|
8f6f4b053c | ||
|
|
fe15a2eeeb | ||
|
|
019667170f | ||
|
|
7a496752f3 | ||
|
|
b569dc11a0 | ||
|
|
df4e6079f1 | ||
|
|
6156f90601 | ||
|
|
cdaea62932 | ||
|
|
78afe01d15 | ||
|
|
4eac88babf | ||
|
|
b4217fabd3 | ||
|
|
92b9dabf3c | ||
|
|
4323ff8a63 | ||
|
|
3e188495f5 | ||
|
|
acb9e17eb3 | ||
|
|
c8ab4f1d02 | ||
|
|
e776a1b122 | ||
|
|
c57af26de9 | ||
|
|
7d89912666 | ||
|
|
cd075f1703 | ||
|
|
35b2ca642c | ||
|
|
127f48e8ad | ||
|
|
3e986cdf54 | ||
|
|
b80d498304 | ||
|
|
757e696a6b | ||
|
|
e3979131f2 | ||
|
|
a774f6bfdb | ||
|
|
d7cd35e2ca | ||
|
|
38e70f1797 | ||
|
|
3b49440c25 | ||
|
|
7c0287b824 | ||
|
|
f97c2c85bd | ||
|
|
14c0d8a93e | ||
|
|
768ad4de2a | ||
|
|
817987dfc4 | ||
|
|
eb090d3544 | ||
|
|
4daf8b7083 | ||
|
|
0be69018b8 | ||
|
|
9b9ab5f3e8 | ||
|
|
072464cbdb | ||
|
|
b0491dec88 | ||
|
|
ccfefedb47 | ||
|
|
2fffcf9e7f | ||
|
|
a39a5d261c | ||
|
|
45b57822d5 | ||
|
|
d8984cd37f | ||
|
|
80e63af470 | ||
|
|
db2c38b21b | ||
|
|
cef51d58ac | ||
|
|
e0b5a13a13 | ||
|
|
de21356154 | ||
|
|
35a4de2030 | ||
|
|
847625822f | ||
|
|
3877df4e62 | ||
|
|
ec73d2fb9a | ||
|
|
a7689d7023 | ||
|
|
847a44e7ad | ||
|
|
b3710c962e | ||
|
|
35ccfe1721 | ||
|
|
ef2bfb9718 | ||
|
|
a97effa27c | ||
|
|
01adee7554 | ||
|
|
78a76b0d29 | ||
|
|
e775328523 | ||
|
|
50344e7792 | ||
|
|
d58fdb10db | ||
|
|
feaacfd226 | ||
|
|
e3c238ac95 | ||
|
|
752997c5e8 | ||
|
|
71edc75ca6 | ||
|
|
768e4c4735 | ||
|
|
c553ad5158 | ||
|
|
c66b901320 | ||
|
|
dd67a3d5f5 | ||
|
|
e972f2c98a | ||
|
|
acbcb1ea9d | ||
|
|
d4444375ac | ||
|
|
00bf40a8ef | ||
|
|
5d1f947f32 | ||
|
|
b594cb9430 | ||
|
|
add7a35e55 | ||
|
|
2af7b61fc3 | ||
|
|
cb97c2b0d3 | ||
|
|
35da38e93f | ||
|
|
963c0f28b9 | ||
|
|
b3815dc0c2 | ||
|
|
8053fc4e16 | ||
|
|
66c3f2f31f | ||
|
|
62c9074132 | ||
|
|
a854cb9617 | ||
|
|
fbf9942fe7 | ||
|
|
f425950a52 | ||
|
|
1d40bc1901 | ||
|
|
ba51409c3c | ||
|
|
a64fc05385 | ||
|
|
4d54454900 | ||
|
|
5601652d65 | ||
|
|
b218bc5bed | ||
|
|
65eee674b9 | ||
|
|
72eb74e94a | ||
|
|
6bfec25165 | ||
|
|
1c61d51448 | ||
|
|
f7fe1d766b | ||
|
|
55aec19389 | ||
|
|
9db51117dc | ||
|
|
a9c9467210 | ||
|
|
f50e15c77c | ||
|
|
e3191d096f | ||
|
|
07c40780b3 | ||
|
|
67b82b4a28 | ||
|
|
5f47e1e034 | ||
|
|
e92cb9e8f8 | ||
|
|
9ea990d5a2 | ||
|
|
08b9ede217 | ||
|
|
6342499c47 | ||
|
|
f347a198f7 | ||
|
|
060642ad14 | ||
|
|
629c0d0f65 | ||
|
|
f7404f52e7 | ||
|
|
74a321e156 | ||
|
|
fce885c0cd | ||
|
|
4028a245b0 | ||
|
|
c5b07a6714 | ||
|
|
b0965bf34f | ||
|
|
1eaca9fb45 | ||
|
|
d833e49db9 | ||
|
|
3aee544cee | ||
|
|
9e87f5090f | ||
|
|
c8cfa43ccc | ||
|
|
ed7af3f370 | ||
|
|
be19d6a403 | ||
|
|
46858ee6fe | ||
|
|
a94e4d803b | ||
|
|
dcbe62ab0a | ||
|
|
121b981b49 | ||
|
|
73bb9322f5 | ||
|
|
bdc2278a30 | ||
|
|
ea8d13d841 | ||
|
|
e45716cac2 | ||
|
|
c98dd8755c | ||
|
|
5ae5e1dd56 | ||
|
|
4f8ee736b1 | ||
|
|
816e68a274 | ||
|
|
6ab6c8eefa | ||
|
|
cb16f42075 | ||
|
|
7ae84a3c91 | ||
|
|
2fd543c989 | ||
|
|
50cf97fc72 | ||
|
|
4acd68188b | ||
|
|
b81b6da3fc | ||
|
|
56ad6aac4d | ||
|
|
1efb8ea280 | ||
|
|
9cfc01f791 | ||
|
|
86014cebd7 | ||
|
|
507f861c67 | ||
|
|
e073720a8f | ||
|
|
ce7cdadb71 | ||
|
|
a223b78872 | ||
|
|
d5181118cc | ||
|
|
886b3abac1 | ||
|
|
250f8d9371 | ||
|
|
8a429d12cf | ||
|
|
8bf4697dc2 | ||
|
|
584523672c | ||
|
|
a9585efd64 | ||
|
|
f6b1f05e0f | ||
|
|
cc8538e0d1 | ||
|
|
f7d9b15707 | ||
|
|
83406bc473 | ||
|
|
1cfce703b2 | ||
|
|
3b24a4cada | ||
|
|
135adb426e | ||
|
|
987dac9fe5 | ||
|
|
7fde48a805 | ||
|
|
ce9028bb5b | ||
|
|
52688a63c6 | ||
|
|
8904e81cdf | ||
|
|
bcbe393af3 | ||
|
|
47aada16a0 | ||
|
|
c22d04aa30 | ||
|
|
354b4f19ec | ||
|
|
0ed1857fa9 | ||
|
|
dfadd98969 | ||
|
|
19a8b66cee | ||
|
|
07dee18d6b | ||
|
|
70e8b11805 | ||
|
|
9d574c0d63 | ||
|
|
2e21c58e6a | ||
|
|
506342317b | ||
|
|
979bb07c86 | ||
|
|
dfeae0e70a | ||
|
|
f43a9ac17e | ||
|
|
c3ac9319f4 | ||
|
|
76ee3060d1 | ||
|
|
4bb241c435 | ||
|
|
a06f4c2514 | ||
|
|
53aa03cc44 | ||
|
|
1ce0b45965 | ||
|
|
7078311a84 | ||
|
|
ef9b717961 | ||
|
|
09246ed9d5 | ||
|
|
33ea55efed | ||
|
|
79474b2e4c | ||
|
|
fb001b6c01 | ||
|
|
2896f51a22 | ||
|
|
5b9115d87a | ||
|
|
211b08f771 | ||
|
|
f0905499e3 | ||
|
|
7985df3768 | ||
|
|
095c7bd801 | ||
|
|
23469c9c7c | ||
|
|
2347762b0d | ||
|
|
636fb5344a | ||
|
|
aaa8b7738a | ||
|
|
bc4282e49e | ||
|
|
2812816142 | ||
|
|
ceeac84cfe | ||
|
|
83d48f65b6 | ||
|
|
95d0410baa | ||
|
|
2708a7569e | ||
|
|
45e8bea8d0 | ||
|
|
f980f230c5 | ||
|
|
e204f89685 | ||
|
|
f7efce594b | ||
|
|
1fb6ad700f | ||
|
|
e3fe31f7cb | ||
|
|
8b96933e58 | ||
|
|
d69b96a94c | ||
|
|
d846210978 | ||
|
|
30c8b1b84f | ||
|
|
43e0929339 | ||
|
|
6c70c42577 | ||
|
|
cd2c06f2a7 | ||
|
|
af55a74bd2 | ||
|
|
d00c126cef | ||
|
|
bedf6e90d2 | ||
|
|
e8c84d8b53 | ||
|
|
f89ff3872d | ||
|
|
127f0fc64c | ||
|
|
0cfa89f316 | ||
|
|
bfcd4113c3 | ||
|
|
0e7fc7613f | ||
|
|
8ac2f52b6e | ||
|
|
1973fc1ecc | ||
|
|
7c39a13281 | ||
|
|
c5c503cbbe | ||
|
|
d09488b829 | ||
|
|
0a6196716c | ||
|
|
8bc9b2b883 | ||
|
|
a15f50254a | ||
|
|
5d4f77a022 | ||
|
|
a089de0964 | ||
|
|
3068ae8447 | ||
|
|
67ff153b0c | ||
|
|
3e1cb8302a | ||
|
|
e4a87f772f | ||
|
|
d4f38d45a5 | ||
|
|
bbe7eb35f1 | ||
|
|
87e54f2dde | ||
|
|
3f3afe489f | ||
|
|
70b21d9c87 | ||
|
|
e00bf3d723 | ||
|
|
605f2b819a | ||
|
|
bf2b975359 | ||
|
|
00a5086ff2 | ||
|
|
be6a888e50 | ||
|
|
dad8447423 | ||
|
|
65ff109065 | ||
|
|
b7253fc1c1 | ||
|
|
d143f576c6 | ||
|
|
a152351a71 | ||
|
|
a2fa1370c5 | ||
|
|
bed83b0b64 | ||
|
|
cf0bdad5de | ||
|
|
85d35ef03c | ||
|
|
514d10b314 | ||
|
|
5164c3d2d0 | ||
|
|
ffdd0719e7 | ||
|
|
4e2b5389d7 | ||
|
|
dc4e63631f | ||
|
|
275bf456d3 | ||
|
|
7dfa871095 | ||
|
|
70cc88de22 | ||
|
|
4bc0f46955 | ||
|
|
5b09599a23 | ||
|
|
f4dd8e3fe8 | ||
|
|
d0888edc0a | ||
|
|
51a230d7fd | ||
|
|
fc5b14b620 | ||
|
|
bbddadbd04 | ||
|
|
7428e47ebc | ||
|
|
72083c65ad | ||
|
|
70f92fd6b3 | ||
|
|
a86cedbc24 | ||
|
|
0906f8dd3b | ||
|
|
664213cedb | ||
|
|
75a7226174 | ||
|
|
9e925becb6 | ||
|
|
e3a5bb9b48 | ||
|
|
b7eeb0e260 | ||
|
|
84d64ddabc | ||
|
|
6c9f92aee6 | ||
|
|
893297760b | ||
|
|
c5c56cda02 | ||
|
|
2295123cad | ||
|
|
ff0280c0cb | ||
|
|
64d736a57b | ||
|
|
5f1d5a1897 | ||
|
|
aac2406e19 | ||
|
|
6dc28ef50a | ||
|
|
66def93373 | ||
|
|
c58023a9ba | ||
|
|
3edc9ff0b0 | ||
|
|
8e8ae1edc7 | ||
|
|
20b00db390 | ||
|
|
db4bbf9521 | ||
|
|
2b7994e739 | ||
|
|
e7fbdac8e0 | ||
|
|
41ec712aa9 | ||
|
|
17acae2b00 | ||
|
|
57261c7e97 | ||
|
|
d8239e0194 | ||
|
|
004c3796de | ||
|
|
18c7549770 | ||
|
|
e5190f14ce | ||
|
|
433b73a5a8 | ||
|
|
ab88a3341f | ||
|
|
181da3ce9b | ||
|
|
b14a58c9b8 | ||
|
|
60cc2cba1f | ||
|
|
c797494d88 | ||
|
|
e2a57182be | ||
|
|
8928441466 | ||
|
|
0e8965060f | ||
|
|
f3cf6fcdd7 | ||
|
|
18ccf0f871 | ||
|
|
313647bcf3 | ||
|
|
61fe068c90 | ||
|
|
5c49096e11 | ||
|
|
a73c78545d | ||
|
|
e0fd560711 | ||
|
|
6a56ac1032 | ||
|
|
96299629b4 | ||
|
|
75de30cfa8 | ||
|
|
233bed6a73 | ||
|
|
b3964efe4d | ||
|
|
575f061629 | ||
|
|
640d7d3b4e | ||
|
|
e92294b482 | ||
|
|
22937e8982 | ||
|
|
c3d1474eb9 | ||
|
|
e2426ea87b | ||
|
|
e58a61175f | ||
|
|
05bea46c3e | ||
|
|
c8a719ae0d | ||
|
|
c3884aafd9 | ||
|
|
0a9785a4ff | ||
|
|
8140f67092 | ||
|
|
4a001b8a02 | ||
|
|
525433e6dd | ||
|
|
f71f6c57d7 | ||
|
|
e35623c72e | ||
|
|
344bce7e2a | ||
|
|
3a4322a7ba | ||
|
|
27b9ae4fc3 | ||
|
|
7e2488af10 | ||
|
|
41ecb586c4 | ||
|
|
510ac341e1 | ||
|
|
358e2b2665 | ||
|
|
3305079a03 | ||
|
|
6ed8471a37 | ||
|
|
dc7ce37c32 | ||
|
|
57c10babfe | ||
|
|
23b2c58018 | ||
|
|
78abd21eec | ||
|
|
841edc729c | ||
|
|
b03fcbcc12 | ||
|
|
b60ac7b66a | ||
|
|
725ae91387 | ||
|
|
b7dd3ce608 | ||
|
|
70c8566cb8 | ||
|
|
0d066bdf46 | ||
|
|
3affc2e066 | ||
|
|
23c826db52 | ||
|
|
1ae36a4e32 | ||
|
|
bc969ad244 | ||
|
|
d7ac1f5b0e | ||
|
|
5bf53fe3ac | ||
|
|
9cc17cec9a | ||
|
|
e2816629d0 | ||
|
|
3f0d54daae | ||
|
|
7dcbebf9bc | ||
|
|
c31defbbd3 | ||
|
|
e54ce35019 | ||
|
|
75d54d720c | ||
|
|
cc0421cb9e | ||
|
|
9c01ac9894 | ||
|
|
20300d1f61 | ||
|
|
6231beefc5 | ||
|
|
068cfdaa00 | ||
|
|
7d62d1fc97 | ||
|
|
e13ac28b8d | ||
|
|
b30ee57cd9 | ||
|
|
921e384c4d | ||
|
|
bf685f600e | ||
|
|
b6d3cad70e | ||
|
|
c665201b85 | ||
|
|
d6996e3347 | ||
|
|
dffcc99373 | ||
|
|
09b79679cd | ||
|
|
cf68e61f40 | ||
|
|
22674d1146 | ||
|
|
f9ee0dc3f2 | ||
|
|
65fa6a946a | ||
|
|
4cf82118d9 | ||
|
|
5f56611a76 | ||
|
|
0f7a2f0f3c | ||
|
|
be2b310ace | ||
|
|
45afe97e8e | ||
|
|
fee8f21ce1 | ||
|
|
1abc252ed3 | ||
|
|
801a820c54 | ||
|
|
2bcc66c805 | ||
|
|
b5ba077a2f | ||
|
|
0931b84940 | ||
|
|
94a0991584 | ||
|
|
9d3d397f50 | ||
|
|
38e8415e77 | ||
|
|
fb9edbe34e | ||
|
|
85f9bd1abf | ||
|
|
63e4d2952b | ||
|
|
52247e9a9f | ||
|
|
d2ad293fae | ||
|
|
6082096f7e | ||
|
|
9a6fcd035b | ||
|
|
47d08ac1f1 | ||
|
|
c4c6a1ee7d | ||
|
|
29d6358f34 | ||
|
|
6308153ae7 | ||
|
|
a9713cd0ed | ||
|
|
1cae4152f9 | ||
|
|
4884bee8ba | ||
|
|
54fc2821cd | ||
|
|
5549fd25fc | ||
|
|
3d5a63607e | ||
|
|
cb7534dcdf | ||
|
|
770a6f2cad | ||
|
|
aab9aa8a2e | ||
|
|
3a14b1d5a9 | ||
|
|
ac044b1c54 | ||
|
|
61c7ea4085 | ||
|
|
01280798e9 | ||
|
|
db56d30078 | ||
|
|
a00274d2ab | ||
|
|
82975109af | ||
|
|
30eb094f28 | ||
|
|
b401a727f7 | ||
|
|
8eb16ce89c | ||
|
|
8e7eb37456 | ||
|
|
4d7f91309b | ||
|
|
109b695621 | ||
|
|
177d2f2f79 | ||
|
|
f5439ddc54 | ||
|
|
324077fb48 | ||
|
|
f50ab981f7 | ||
|
|
0c620ad076 | ||
|
|
49cf2eb7e4 | ||
|
|
a2afa9aadd | ||
|
|
c2f3949ded | ||
|
|
bf355c4527 | ||
|
|
3daa63cae8 | ||
|
|
4441e012cf | ||
|
|
122a47fba6 | ||
|
|
421585dd72 | ||
|
|
0bab9903ee | ||
|
|
700deb0a81 | ||
|
|
1222b78ec4 | ||
|
|
0ee16b51c4 | ||
|
|
26001d520a | ||
|
|
8bf265c775 | ||
|
|
62f0bbb598 | ||
|
|
d5f4c74697 | ||
|
|
8f42532b6d | ||
|
|
2288a5c617 | ||
|
|
957311f479 | ||
|
|
2cc381b91d | ||
|
|
f406dbbb4d | ||
|
|
3b2322285a | ||
|
|
47d093e863 | ||
|
|
b2ae94de5b | ||
|
|
4afea1ebaf | ||
|
|
711736054f | ||
|
|
d64212d902 | ||
|
|
8913679d88 | ||
|
|
4f9a80e2d3 | ||
|
|
aa93b39d9b | ||
|
|
101f82c6b3 | ||
|
|
d35673efc6 | ||
|
|
3286d1992b | ||
|
|
4ac662d144 | ||
|
|
d73a418a55 | ||
|
|
306a3e0cd7 | ||
|
|
975a53c9e3 | ||
|
|
78fdc5805b | ||
|
|
8f9d5af26d | ||
|
|
6ff5787b40 | ||
|
|
3c1c6d2f01 | ||
|
|
0272a7f405 | ||
|
|
e1d34ef427 | ||
|
|
26b4698212 | ||
|
|
2871268505 | ||
|
|
744828a4de | ||
|
|
ff84351655 | ||
|
|
8b6f2bbb4b | ||
|
|
d2efb4b29b | ||
|
|
db56b1bfec | ||
|
|
990a33b393 | ||
|
|
664c658da6 | ||
|
|
d1617ce7ce | ||
|
|
2b50d44a2f | ||
|
|
ddfde68140 | ||
|
|
811b30d116 | ||
|
|
bcd362fcd5 | ||
|
|
1fafcd4d28 | ||
|
|
2807a85f68 | ||
|
|
39515acf68 | ||
|
|
aaed74fe4e | ||
|
|
126efaadcc | ||
|
|
2adc057d95 | ||
|
|
59770a4953 | ||
|
|
67098511db | ||
|
|
07b2ce4ab2 | ||
|
|
80d2f38192 | ||
|
|
0792f4722c | ||
|
|
db37360a1d | ||
|
|
44ff766f98 | ||
|
|
bfa5715017 | ||
|
|
e2183ad661 | ||
|
|
e2201689cf | ||
|
|
0f72aa8a5f | ||
|
|
b2f4f52b64 | ||
|
|
c65ed26a7e | ||
|
|
df5dbaf49b | ||
|
|
80fe1f16db | ||
|
|
f524a4c1cc | ||
|
|
c61c3cddbd | ||
|
|
51767aee23 | ||
|
|
cd3d7e2dca | ||
|
|
4f7f5404ce | ||
|
|
d4b2709fb0 | ||
|
|
e6fdc3a932 | ||
|
|
63ebe4ca8d | ||
|
|
8d5bc7f28b | ||
|
|
50e36fb482 | ||
|
|
a1c5e76c27 | ||
|
|
54f2587c1e | ||
|
|
99c293a403 | ||
|
|
fefcbf60fa | ||
|
|
96c2fdb445 | ||
|
|
8301a72453 | ||
|
|
05ddef117a | ||
|
|
15402e46c9 | ||
|
|
939860eb85 | ||
|
|
530dc77cde | ||
|
|
5db15cb157 | ||
|
|
06a12f5e27 | ||
|
|
143abe39f2 | ||
|
|
ee04732cbb | ||
|
|
79455cc71e | ||
|
|
042e5fe097 | ||
|
|
d273a9d82d | ||
|
|
3eded3c4ac | ||
|
|
20f4fda3c9 | ||
|
|
ed32a759ed | ||
|
|
ef2d036884 | ||
|
|
746c41f527 | ||
|
|
b0fb457746 | ||
|
|
b9ff495483 | ||
|
|
8506066926 | ||
|
|
43018973ac | ||
|
|
7e4ba54608 | ||
|
|
2f66355f20 | ||
|
|
7781ea8d59 | ||
|
|
ce065614e2 | ||
|
|
fa472a340e | ||
|
|
279a516c53 | ||
|
|
9ac5c6de14 | ||
|
|
58a7faa281 | ||
|
|
496a87a665 | ||
|
|
e4e53a2e61 | ||
|
|
28255f1bac | ||
|
|
917cb4acb3 | ||
|
|
d84527a730 | ||
|
|
7d0783aad5 | ||
|
|
7622506fe2 | ||
|
|
ae8bbc63da | ||
|
|
79f5d940cf | ||
|
|
25662b9e05 | ||
|
|
c820576329 | ||
|
|
af601575cb | ||
|
|
c7eae60944 | ||
|
|
0afd5a2204 | ||
|
|
92cb21f0f2 | ||
|
|
0031130111 | ||
|
|
2a3b377d34 | ||
|
|
2aed3bf9ab | ||
|
|
ec4e0e4d58 | ||
|
|
696d012c05 | ||
|
|
61ff7306ae | ||
|
|
0bcf4769fe | ||
|
|
0bfbecf9cb | ||
|
|
9058ec32e1 | ||
|
|
61e4b4db42 | ||
|
|
fd7c63bc78 | ||
|
|
49a7d08a40 | ||
|
|
2c10ce64aa | ||
|
|
a41a294e1d | ||
|
|
47b17dc1bb | ||
|
|
5f75444ef6 | ||
|
|
54fda3422e | ||
|
|
fcc2db8093 | ||
|
|
89b7ffbd5c | ||
|
|
ada43b0e58 | ||
|
|
5050c33162 | ||
|
|
4e8fda228d | ||
|
|
cdfb3f7194 | ||
|
|
a2dd23efd3 | ||
|
|
fa43d02874 | ||
|
|
d0de39ebcd | ||
|
|
2121c0fa23 | ||
|
|
a8652e2252 | ||
|
|
81151523af | ||
|
|
3e82771413 | ||
|
|
9445b12328 | ||
|
|
4bb103ef43 | ||
|
|
0dba7b8a46 | ||
|
|
e247811db5 | ||
|
|
6768f999ed | ||
|
|
ce767bc3cf | ||
|
|
e780cda1d4 | ||
|
|
a55d882b7b | ||
|
|
5c5ad62208 | ||
|
|
62a1a561cf | ||
|
|
ce394426b0 | ||
|
|
6606602f1e | ||
|
|
b6b8958fb4 | ||
|
|
d8eea0e397 | ||
|
|
df9c930581 | ||
|
|
85bcacac90 | ||
|
|
4b4ee72796 | ||
|
|
40611fc4fc | ||
|
|
7c4ba9fcb2 | ||
|
|
a1c9612d75 | ||
|
|
33c8709439 | ||
|
|
5e6f4ab281 | ||
|
|
3efdf5e095 | ||
|
|
d174b97af7 | ||
|
|
fff8822239 | ||
|
|
7cfe3760f4 | ||
|
|
298bd640f3 | ||
|
|
945a37d0d2 | ||
|
|
68afa28b27 | ||
|
|
d6a9017298 | ||
|
|
da862f82cf | ||
|
|
f8b6727190 | ||
|
|
2d88d24881 | ||
|
|
62650a3eb3 | ||
|
|
2c4f7b61c1 | ||
|
|
a3f6fe5287 | ||
|
|
8d85c51a28 | ||
|
|
17d5a72416 | ||
|
|
c4ce260b49 | ||
|
|
4808958f93 | ||
|
|
b58bb03e95 | ||
|
|
ba7fbfa8a7 | ||
|
|
117ff1d781 | ||
|
|
160c97da13 | ||
|
|
0760bc09aa | ||
|
|
5ca82e2f05 | ||
|
|
746a6ef8d3 | ||
|
|
763944f673 | ||
|
|
f4d7e41f24 | ||
|
|
f9306218f8 | ||
|
|
fb06427c69 | ||
|
|
93bd601149 | ||
|
|
848c5b78e1 | ||
|
|
84d5df3c84 | ||
|
|
63e6d9d2d1 | ||
|
|
6a2b7b97d7 | ||
|
|
d8d19072c5 | ||
|
|
830ab37371 | ||
|
|
7e48ee8758 | ||
|
|
d55053098f | ||
|
|
63cf0b1cdd | ||
|
|
5866b1b017 | ||
|
|
8493f3939c | ||
|
|
095f4e9b9d | ||
|
|
a1382a03aa | ||
|
|
844b903595 | ||
|
|
a3b3e1f646 | ||
|
|
b23cf58a41 | ||
|
|
ba5eb230fb | ||
|
|
2ea15a72bc | ||
|
|
b5c654a100 | ||
|
|
6807b0e42f | ||
|
|
16422a6b78 | ||
|
|
b2ded6212b | ||
|
|
88df5927f9 | ||
|
|
8c37262e05 | ||
|
|
3c14a893fb | ||
|
|
05bc19c331 | ||
|
|
40fe97e946 | ||
|
|
7458d37d2a | ||
|
|
c4110780bf | ||
|
|
d729004554 | ||
|
|
c0521791db | ||
|
|
55ad1354b6 | ||
|
|
fb61ed8506 | ||
|
|
4c7f7582fd | ||
|
|
a4f1f3d4e8 | ||
|
|
973e3d6a7b | ||
|
|
b62d08d136 | ||
|
|
50e31c6636 | ||
|
|
151f03378f | ||
|
|
26fb9007da | ||
|
|
3b20335d2a | ||
|
|
8d55367a6a | ||
|
|
187ee62e3d | ||
|
|
10e2ec1fbb | ||
|
|
83999cd1d1 | ||
|
|
fef90ef0a9 | ||
|
|
72ae5626b0 | ||
|
|
eee28d0d39 | ||
|
|
b59999dd59 | ||
|
|
e62c032184 | ||
|
|
1635b37ff1 | ||
|
|
8774381e2e | ||
|
|
cbfe7a405b | ||
|
|
80391fbcd4 | ||
|
|
cbf3d43561 | ||
|
|
e7bd392a69 | ||
|
|
764b90a519 | ||
|
|
d785942ed5 | ||
|
|
1cceadaf7c | ||
|
|
6882aeff97 | ||
|
|
a0922643e6 | ||
|
|
4d7254f88f | ||
|
|
8499090038 | ||
|
|
ca0c4c7585 | ||
|
|
5aec01100e | ||
|
|
4d6af44045 | ||
|
|
256d17eba8 | ||
|
|
5777f4481f | ||
|
|
6e945fba82 | ||
|
|
ce7047d88a | ||
|
|
4a35100130 | ||
|
|
ef7662d2fa | ||
|
|
16e89706d3 | ||
|
|
41a58d7f6e | ||
|
|
2a7f3eecf4 | ||
|
|
41e12114a8 | ||
|
|
1b12d5d346 | ||
|
|
74b8cbfb84 | ||
|
|
06427371eb | ||
|
|
d08e1616a7 | ||
|
|
79b011305e | ||
|
|
050879f0ca | ||
|
|
0a74f8022e | ||
|
|
0db20c9c56 | ||
|
|
33e9db9745 | ||
|
|
d0145d4359 | ||
|
|
80dab10ec9 | ||
|
|
022cda3109 | ||
|
|
4030672b66 | ||
|
|
348379625c | ||
|
|
ab4a2275eb | ||
|
|
c8683fc916 | ||
|
|
273ee0d696 | ||
|
|
6d19bbba73 | ||
|
|
d6c31b51c6 | ||
|
|
af19f924ff | ||
|
|
80572c544b | ||
|
|
11f8cb32d1 | ||
|
|
62781d0925 | ||
|
|
2bd786a452 | ||
|
|
038648aaca | ||
|
|
0e3ac6b13c | ||
|
|
1e274b01fe | ||
|
|
c4f6439715 | ||
|
|
cdecb44789 | ||
|
|
8af3f61b6e | ||
|
|
48eef2fb3c | ||
|
|
7a5b531bd0 | ||
|
|
78ca08ba8a | ||
|
|
49ba4eeb86 | ||
|
|
c08617c70f | ||
|
|
1bd3365868 | ||
|
|
31f21551bf | ||
|
|
baaec5b126 | ||
|
|
2b72c7f709 | ||
|
|
f204d95a8b | ||
|
|
7a5b814e59 | ||
|
|
aa6c06d751 | ||
|
|
ffb031a71b | ||
|
|
041b201abd | ||
|
|
9db8ecbc32 | ||
|
|
518d39815c | ||
|
|
147f97d1f7 | ||
|
|
7f44735709 | ||
|
|
db9d94f5de | ||
|
|
a36ef8582f | ||
|
|
f34a40a709 | ||
|
|
4aee962233 | ||
|
|
5f71d186b2 | ||
|
|
56c9fdb53c | ||
|
|
47474687eb | ||
|
|
abe753ca86 | ||
|
|
cf5d0f5c1f | ||
|
|
4d431e94b9 | ||
|
|
bdafbad61e | ||
|
|
eb6e9b194a | ||
|
|
ecdfd80459 | ||
|
|
a268eedb1d | ||
|
|
19ff7c9302 | ||
|
|
fb169a8b54 | ||
|
|
bcbfad1482 | ||
|
|
8c37ae8f5c | ||
|
|
610f40f700 | ||
|
|
5cb2a2fa3c | ||
|
|
919a180ad2 | ||
|
|
951099dbed | ||
|
|
0f9267d5fc | ||
|
|
3de9bd9d04 | ||
|
|
57ee25d75a | ||
|
|
633f50cd3e | ||
|
|
d04d4edc40 | ||
|
|
98c34e413d | ||
|
|
c4bc249b66 | ||
|
|
899c8e0697 | ||
|
|
4006345cfb | ||
|
|
1319d7333c | ||
|
|
5f168b3b96 | ||
|
|
e4f1e19127 | ||
|
|
4a1b644bfb | ||
|
|
8c9c86c3d6 | ||
|
|
8a58e0235d | ||
|
|
52b7337d28 | ||
|
|
995cd0dc32 | ||
|
|
5eb558e058 | ||
|
|
33d9310c49 | ||
|
|
aba89e2737 | ||
|
|
d685e7b4b5 | ||
|
|
9e4b68a364 | ||
|
|
044a3b3920 | ||
|
|
d342f9f942 | ||
|
|
e91b509578 | ||
|
|
8ddb3fbb2e | ||
|
|
b91e01fd22 | ||
|
|
177195aeeb | ||
|
|
cb5979a468 | ||
|
|
32507774de | ||
|
|
0ce662faad | ||
|
|
03b629064a | ||
|
|
962fbc8257 | ||
|
|
bd4b91bd57 | ||
|
|
10a6a92e52 | ||
|
|
54b16bd054 | ||
|
|
f21e97001b | ||
|
|
1f005a82ad | ||
|
|
bb65974e2f | ||
|
|
bc0f487369 | ||
|
|
e103c4c26a | ||
|
|
79d29bb41e | ||
|
|
c80b6d96dd | ||
|
|
97f6f8fe19 | ||
|
|
94920d39ae | ||
|
|
9403bd2990 | ||
|
|
e098924e61 | ||
|
|
437f9e2cef | ||
|
|
395f259978 | ||
|
|
b78adc9f03 | ||
|
|
b7c21310b4 | ||
|
|
c754e89906 | ||
|
|
62cfe3f384 | ||
|
|
afde340c9e | ||
|
|
d0ad83de4b | ||
|
|
d119bfd934 | ||
|
|
bdc91eda0f | ||
|
|
ef9e6794c2 | ||
|
|
4362ca7bb9 | ||
|
|
dcf945ed58 | ||
|
|
a86196a156 | ||
|
|
856c2b565f | ||
|
|
1a8c5708c5 | ||
|
|
14cab0fff0 | ||
|
|
69888bf966 | ||
|
|
d260238f99 | ||
|
|
6ca7198f57 | ||
|
|
cfcdc85b26 | ||
|
|
7f8d74e903 | ||
|
|
f2b1fedc4f | ||
|
|
b03cad3cf6 | ||
|
|
70db13e6e8 | ||
|
|
4c98360356 | ||
|
|
42f9f7fb5d | ||
|
|
ca1856724c | ||
|
|
b52a39a84e | ||
|
|
a97261c54f | ||
|
|
0f5579c0ba | ||
|
|
2f5a2d3c48 | ||
|
|
ba7f7c8319 | ||
|
|
77fb3c2511 | ||
|
|
74d9dabdff | ||
|
|
54edf38d0e | ||
|
|
22f06590f7 | ||
|
|
3b4c24af4e | ||
|
|
f37af9afec | ||
|
|
a3f0992a22 | ||
|
|
f555873f18 | ||
|
|
1c8eab81a5 | ||
|
|
cbc5af329f | ||
|
|
90d738b561 | ||
|
|
d80fdad6da | ||
|
|
e2916f3a55 | ||
|
|
1aa1a2c174 | ||
|
|
195d152785 | ||
|
|
1f61027f51 | ||
|
|
37a53570d4 | ||
|
|
ee7219aa20 | ||
|
|
b1d8da484b | ||
|
|
4e869e03f7 | ||
|
|
52c9647b06 | ||
|
|
7238ae18f9 | ||
|
|
551a829eba | ||
|
|
8e91f83174 | ||
|
|
7f776c64f0 | ||
|
|
8bf6ab2c52 | ||
|
|
75fc3fe389 | ||
|
|
c4572ebc91 | ||
|
|
e56976839a | ||
|
|
0c0ed2fe04 | ||
|
|
ab6ed256e5 | ||
|
|
7c98ecd3ab | ||
|
|
f6346a4d29 | ||
|
|
b502a74cff | ||
|
|
8e9c25063a | ||
|
|
1dced3b3c4 | ||
|
|
087bf1d584 | ||
|
|
e051a34fc1 | ||
|
|
f5455d865b | ||
|
|
b705ead3fd | ||
|
|
c390fc8100 | ||
|
|
14f6ce1e77 | ||
|
|
385542e2f9 | ||
|
|
fc946d0c44 | ||
|
|
854c84d0ca | ||
|
|
90bd0eb44c | ||
|
|
3130f870bb | ||
|
|
51b617f601 | ||
|
|
011ca244b2 | ||
|
|
9ea1361044 | ||
|
|
776966e22c | ||
|
|
01cb256b84 | ||
|
|
0b0163dde2 | ||
|
|
38123c70eb | ||
|
|
5cb7229a16 | ||
|
|
9bf3d3da4c | ||
|
|
93caa459e3 | ||
|
|
f8039deb7c | ||
|
|
86eaf43b00 | ||
|
|
8176202e6d | ||
|
|
1b74879b8b | ||
|
|
39319b4858 | ||
|
|
4af5c9aed7 | ||
|
|
8a3c4c6a7b | ||
|
|
d22e6f5a96 | ||
|
|
1648c1a0f3 | ||
|
|
44b1a591a8 | ||
|
|
bbb6f94377 | ||
|
|
3f654dac37 | ||
|
|
eed9c5738d | ||
|
|
fd39cbc193 | ||
|
|
b25f5eb0d1 | ||
|
|
0961763082 | ||
|
|
49e5299a95 | ||
|
|
07908f3f54 | ||
|
|
fdada79ebf | ||
|
|
7f15cc9556 | ||
|
|
cd3c699f28 | ||
|
|
36d2c46bcf | ||
|
|
1f50b70919 | ||
|
|
19db0df639 | ||
|
|
238f26cc90 | ||
|
|
268fcbb973 | ||
|
|
1e4589db18 | ||
|
|
31a1cc46b7 | ||
|
|
9d4b3580a5 | ||
|
|
b07bef2a6b | ||
|
|
705e60d0ad | ||
|
|
4c258787b5 | ||
|
|
58ea15078f | ||
|
|
756d47fb50 | ||
|
|
53874bd8ee | ||
|
|
e2bf91452a | ||
|
|
9eb17e4ade | ||
|
|
2c4aadb588 | ||
|
|
424554bc85 | ||
|
|
12a208a880 | ||
|
|
6893ce0bbf | ||
|
|
399cf18013 | ||
|
|
64b5105edd | ||
|
|
2c2f4a6a05 | ||
|
|
da41db4712 | ||
|
|
9f3449d944 | ||
|
|
ec8a884787 | ||
|
|
fc663d98d1 | ||
|
|
08c2cb784f | ||
|
|
3911a49256 | ||
|
|
2a62471e4c | ||
|
|
815ae7df45 | ||
|
|
ff0a299bfb | ||
|
|
5fa6a28f70 | ||
|
|
9a5178be7a | ||
|
|
66e08e0cc8 | ||
|
|
b5f78cd7b4 | ||
|
|
ef99ca68aa | ||
|
|
a5c2f2c138 | ||
|
|
b2c9ef23fa | ||
|
|
5f9be3dd05 | ||
|
|
b5f1bebc52 | ||
|
|
ad9c7ff7ed | ||
|
|
1af9fcbbfa | ||
|
|
6765303de4 | ||
|
|
304ee97944 | ||
|
|
d91a547d59 | ||
|
|
7d9ca3998e | ||
|
|
9aa32bc269 | ||
|
|
d9c8c47e02 | ||
|
|
243a868a5b | ||
|
|
6c351c15f8 | ||
|
|
45b63e2d45 | ||
|
|
32df634cb6 | ||
|
|
e569977c06 | ||
|
|
b49ab9f9c7 | ||
|
|
78a9e7440a | ||
|
|
93f5125f51 | ||
|
|
410e17a2ec | ||
|
|
23f7943645 | ||
|
|
1108895180 | ||
|
|
158870bcdb | ||
|
|
36717c7d98 | ||
|
|
1d3987bbbd | ||
|
|
472d4799d1 | ||
|
|
84caf1e158 | ||
|
|
72eba4dbb6 | ||
|
|
0f20f23651 | ||
|
|
47e2d5c415 | ||
|
|
1e9b8e043a | ||
|
|
eb0fc21533 | ||
|
|
a6a2eec392 | ||
|
|
c227a90b52 | ||
|
|
1e3d899db8 | ||
|
|
84369286df | ||
|
|
4c82b1f3c6 | ||
|
|
f94257115f | ||
|
|
77e94be280 | ||
|
|
37d5e75a56 | ||
|
|
dc06973796 | ||
|
|
b03462ab04 | ||
|
|
d4e87a841d | ||
|
|
6d0063d685 | ||
|
|
6fdd7149c1 | ||
|
|
fdb07f2f89 | ||
|
|
a433698b00 | ||
|
|
f14871caf7 | ||
|
|
132ce94139 | ||
|
|
a492c0fb0e | ||
|
|
dfc7215bf9 | ||
|
|
38e59ebdf3 | ||
|
|
5ee24f804f | ||
|
|
747edf42c1 | ||
|
|
ce23cb2093 | ||
|
|
6ff0bb825e | ||
|
|
fef2c6bf7a | ||
|
|
0c6f14c694 | ||
|
|
1c800efbac | ||
|
|
e2e400e63c | ||
|
|
4d8d1e287b | ||
|
|
452fdbf1c1 | ||
|
|
51686bd1ef | ||
|
|
38a4d50e73 | ||
|
|
3fd38cbe8d | ||
|
|
2b3d13a841 | ||
|
|
6f1766dd9e | ||
|
|
7d70eb0346 | ||
|
|
bae2644667 | ||
|
|
f6f95822c1 | ||
|
|
b1b5e09081 | ||
|
|
2b268f9724 | ||
|
|
7a5a74cecb | ||
|
|
54a0c6b8ad | ||
|
|
1ad23c4dc8 | ||
|
|
7586a345ff | ||
|
|
393b94bb70 | ||
|
|
e3c11c9ca1 | ||
|
|
3c91abce74 | ||
|
|
87d856d71b | ||
|
|
3855c003ce | ||
|
|
abb9f89f65 | ||
|
|
17b4058ee9 | ||
|
|
9663f9b2ab | ||
|
|
d6e10dba33 | ||
|
|
da5cbc194a | ||
|
|
e8eb658ba5 | ||
|
|
28f69f25a0 | ||
|
|
07e4b9bb7f | ||
|
|
708b967f15 | ||
|
|
7e2568a312 | ||
|
|
bde0334bd8 | ||
|
|
5470d34740 | ||
|
|
ac9cb50fdb | ||
|
|
4a8b548add | ||
|
|
481c8a40ea | ||
|
|
25ef3a281b | ||
|
|
219bd97e8a | ||
|
|
8b14cd24aa | ||
|
|
3893c14889 | ||
|
|
c41fbc0f90 | ||
|
|
f45425e5a9 | ||
|
|
bd9fd629bc | ||
|
|
3b19f48929 | ||
|
|
4996edc030 | ||
|
|
964f1f6a7e | ||
|
|
e75c1f70bb | ||
|
|
19a4d74ee7 | ||
|
|
55b5eded23 | ||
|
|
3dbcf0af2d | ||
|
|
4e1a511f88 | ||
|
|
b71e1a16b1 | ||
|
|
ec1271818f | ||
|
|
8318020387 | ||
|
|
c38d7be373 | ||
|
|
dc31212c3d | ||
|
|
ac60b36e77 | ||
|
|
1d73f071f6 | ||
|
|
5c869d5bd3 | ||
|
|
a54210a2e4 | ||
|
|
040d226028 | ||
|
|
8b664c3ec5 | ||
|
|
102a38bb95 | ||
|
|
7a54e13110 | ||
|
|
feee92c790 | ||
|
|
de93852512 | ||
|
|
dfb710eab7 | ||
|
|
25cfeb2a64 | ||
|
|
90377f5e65 | ||
|
|
f1d9bd5eab | ||
|
|
4ee3c21a9d | ||
|
|
fe6f4135b4 | ||
|
|
3dfa63b85c | ||
|
|
ff2343475a | ||
|
|
bffd7f0f14 | ||
|
|
7c55fafe33 | ||
|
|
2e7fe06beb | ||
|
|
8ff91ff31b | ||
|
|
4d1c616e97 | ||
|
|
43daecd89b | ||
|
|
9f99c20232 | ||
|
|
97ed8db75d | ||
|
|
f80d98553a | ||
|
|
b3e7a9d01c | ||
|
|
01fc063128 | ||
|
|
e71edd5577 | ||
|
|
27a34dd183 | ||
|
|
7662f15939 | ||
|
|
bfd9f32188 | ||
|
|
9c9cdf1712 | ||
|
|
0e5537cd25 | ||
|
|
151d0a274e | ||
|
|
dc77ec4ba1 | ||
|
|
0d7573dd81 | ||
|
|
e4d2d228bd | ||
|
|
ede36b001b | ||
|
|
3afb2a4798 | ||
|
|
62dbdcdbcc | ||
|
|
06df133159 | ||
|
|
0ab2693da6 | ||
|
|
4b1cb1be43 | ||
|
|
9d96680329 | ||
|
|
d694bb30e5 | ||
|
|
9c858c3228 | ||
|
|
7125cb10f5 | ||
|
|
ba421fd069 | ||
|
|
77e55b8265 | ||
|
|
18d26e2ddb | ||
|
|
f338a2d907 | ||
|
|
77fa8194f2 | ||
|
|
ccaca04a5d | ||
|
|
84191ac6dc | ||
|
|
7cf8ea354c | ||
|
|
24ef00a258 | ||
|
|
00d30ce0d7 | ||
|
|
db39adeb3e | ||
|
|
ef7ac088c0 | ||
|
|
08a3957880 | ||
|
|
4499b08afc | ||
|
|
422ad38e5b | ||
|
|
0b7f959433 | ||
|
|
4b9da601be | ||
|
|
c789436580 | ||
|
|
277d94feac | ||
|
|
6757244918 | ||
|
|
36157d8ae5 | ||
|
|
251cfc100e | ||
|
|
9fb10064ee | ||
|
|
bedeaf23af | ||
|
|
14e93bfd8a | ||
|
|
65071599a2 | ||
|
|
5403e1c79a | ||
|
|
5697caf20b | ||
|
|
68056f08ab | ||
|
|
81002747c5 | ||
|
|
1bd9f522e0 | ||
|
|
3a1b41ac22 | ||
|
|
375d25f158 | ||
|
|
0e57335396 | ||
|
|
bafe7d5a73 | ||
|
|
c555dc71c2 | ||
|
|
3c620d521d | ||
|
|
0a5c83ece1 | ||
|
|
1ba5e99152 | ||
|
|
95c83b37fb | ||
|
|
89634795b0 | ||
|
|
b88dec51e5 | ||
|
|
f2a789ea98 | ||
|
|
63128834da | ||
|
|
5f822f2660 | ||
|
|
b81601baff | ||
|
|
58064bdd2b | ||
|
|
ba01d5e8ab | ||
|
|
e510d460c2 | ||
|
|
42de601fa6 | ||
|
|
3801b8109e | ||
|
|
e0d41da3e3 | ||
|
|
92662baceb | ||
|
|
87c844bce1 |
No files matched your search
@@ -0,0 +1,4 @@
|
|||||||
|
github: [ncw]
|
||||||
|
patreon: njcw
|
||||||
|
liberapay: ncw
|
||||||
|
custom: ["https://rclone.org/donate/"]
|
||||||
@@ -33,18 +33,18 @@ The Rclone Developers
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
#### Which OS you are using and how many bits (eg Windows 7, 64 bit)
|
#### Which OS you are using and how many bits (e.g. Windows 7, 64 bit)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
#### Which cloud storage system are you using? (eg Google Drive)
|
#### Which cloud storage system are you using? (e.g. Google Drive)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
#### The command you were trying to run (eg `rclone copy /tmp remote:tmp`)
|
#### The command you were trying to run (e.g. `rclone copy /tmp remote:tmp`)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
#### A log from the command with the `-vv` flag (eg output from `rclone -vv copy /tmp remote:tmp`)
|
#### A log from the command with the `-vv` flag (e.g. output from `rclone -vv copy /tmp remote:tmp`)
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
blank_issues_enabled: false
|
||||||
|
contact_links:
|
||||||
|
- name: Rclone Forum Community Support
|
||||||
|
url: https://forum.rclone.org/
|
||||||
|
about: Please ask and answer questions here.
|
||||||
+59
-58
@@ -19,24 +19,23 @@ jobs:
|
|||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
job_name: ['linux', 'mac', 'windows_amd64', 'windows_386', 'other_os', 'modules_race', 'go1.10', 'go1.11', 'go1.12']
|
job_name: ['linux', 'mac', 'windows_amd64', 'windows_386', 'other_os', 'go1.13', 'go1.14', 'go1.15']
|
||||||
|
|
||||||
include:
|
include:
|
||||||
- job_name: linux
|
- job_name: linux
|
||||||
os: ubuntu-latest
|
os: ubuntu-latest
|
||||||
go: '1.13.x'
|
go: '1.16.0-rc1'
|
||||||
modules: 'off'
|
|
||||||
gotags: cmount
|
gotags: cmount
|
||||||
build_flags: '-include "^linux/"'
|
build_flags: '-include "^linux/"'
|
||||||
check: true
|
check: true
|
||||||
quicktest: true
|
quicktest: true
|
||||||
|
racequicktest: true
|
||||||
deploy: true
|
deploy: true
|
||||||
|
|
||||||
- job_name: mac
|
- job_name: mac
|
||||||
os: macOS-latest
|
os: macOS-latest
|
||||||
go: '1.13.x'
|
go: '1.16.0-rc1'
|
||||||
modules: 'off'
|
gotags: 'cmount'
|
||||||
gotags: '' # cmount doesn't work on osx travis for some reason
|
|
||||||
build_flags: '-include "^darwin/amd64" -cgo'
|
build_flags: '-include "^darwin/amd64" -cgo'
|
||||||
quicktest: true
|
quicktest: true
|
||||||
racequicktest: true
|
racequicktest: true
|
||||||
@@ -44,57 +43,48 @@ jobs:
|
|||||||
|
|
||||||
- job_name: windows_amd64
|
- job_name: windows_amd64
|
||||||
os: windows-latest
|
os: windows-latest
|
||||||
go: '1.13.x'
|
go: '1.16.0-rc1'
|
||||||
modules: 'off'
|
|
||||||
gotags: cmount
|
gotags: cmount
|
||||||
build_flags: '-include "^windows/amd64" -cgo'
|
build_flags: '-include "^windows/amd64" -cgo'
|
||||||
|
build_args: '-buildmode exe'
|
||||||
quicktest: true
|
quicktest: true
|
||||||
racequicktest: true
|
racequicktest: true
|
||||||
deploy: true
|
deploy: true
|
||||||
|
|
||||||
- job_name: windows_386
|
- job_name: windows_386
|
||||||
os: windows-latest
|
os: windows-latest
|
||||||
go: '1.13.x'
|
go: '1.16.0-rc1'
|
||||||
modules: 'off'
|
|
||||||
gotags: cmount
|
gotags: cmount
|
||||||
goarch: '386'
|
goarch: '386'
|
||||||
cgo: '1'
|
cgo: '1'
|
||||||
build_flags: '-include "^windows/386" -cgo'
|
build_flags: '-include "^windows/386" -cgo'
|
||||||
|
build_args: '-buildmode exe'
|
||||||
quicktest: true
|
quicktest: true
|
||||||
deploy: true
|
deploy: true
|
||||||
|
|
||||||
- job_name: other_os
|
- job_name: other_os
|
||||||
os: ubuntu-latest
|
os: ubuntu-latest
|
||||||
go: '1.13.x'
|
go: '1.16.0-rc1'
|
||||||
modules: 'off'
|
|
||||||
build_flags: '-exclude "^(windows/|darwin/amd64|linux/)"'
|
build_flags: '-exclude "^(windows/|darwin/amd64|linux/)"'
|
||||||
compile_all: true
|
compile_all: true
|
||||||
deploy: true
|
deploy: true
|
||||||
|
|
||||||
- job_name: modules_race
|
- job_name: go1.13
|
||||||
os: ubuntu-latest
|
os: ubuntu-latest
|
||||||
go: '1.13.x'
|
go: '1.13.x'
|
||||||
modules: 'on'
|
quicktest: true
|
||||||
|
|
||||||
|
- job_name: go1.14
|
||||||
|
os: ubuntu-latest
|
||||||
|
go: '1.14.x'
|
||||||
quicktest: true
|
quicktest: true
|
||||||
racequicktest: true
|
racequicktest: true
|
||||||
|
|
||||||
- job_name: go1.10
|
- job_name: go1.15
|
||||||
os: ubuntu-latest
|
os: ubuntu-latest
|
||||||
go: '1.10.x'
|
go: '1.15.x'
|
||||||
modules: 'off'
|
|
||||||
quicktest: true
|
|
||||||
|
|
||||||
- job_name: go1.11
|
|
||||||
os: ubuntu-latest
|
|
||||||
go: '1.11.x'
|
|
||||||
modules: 'off'
|
|
||||||
quicktest: true
|
|
||||||
|
|
||||||
- job_name: go1.12
|
|
||||||
os: ubuntu-latest
|
|
||||||
go: '1.12.x'
|
|
||||||
modules: 'off'
|
|
||||||
quicktest: true
|
quicktest: true
|
||||||
|
racequicktest: true
|
||||||
|
|
||||||
name: ${{ matrix.job_name }}
|
name: ${{ matrix.job_name }}
|
||||||
|
|
||||||
@@ -102,26 +92,24 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v1
|
uses: actions/checkout@v2
|
||||||
with:
|
with:
|
||||||
# Checkout into a fixed path to avoid import path problems on go < 1.11
|
fetch-depth: 0
|
||||||
path: ./src/github.com/rclone/rclone
|
|
||||||
|
|
||||||
- name: Install Go
|
- name: Install Go
|
||||||
uses: actions/setup-go@v1
|
uses: actions/setup-go@v2
|
||||||
with:
|
with:
|
||||||
|
stable: 'false'
|
||||||
go-version: ${{ matrix.go }}
|
go-version: ${{ matrix.go }}
|
||||||
|
|
||||||
- name: Set environment variables
|
- name: Set environment variables
|
||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
echo '::set-env name=GOPATH::${{ runner.workspace }}'
|
echo 'GOTAGS=${{ matrix.gotags }}' >> $GITHUB_ENV
|
||||||
echo '::add-path::${{ runner.workspace }}/bin'
|
echo 'BUILD_FLAGS=${{ matrix.build_flags }}' >> $GITHUB_ENV
|
||||||
echo '::set-env name=GO111MODULE::${{ matrix.modules }}'
|
echo 'BUILD_ARGS=${{ matrix.build_args }}' >> $GITHUB_ENV
|
||||||
echo '::set-env name=GOTAGS::${{ matrix.gotags }}'
|
if [[ "${{ matrix.goarch }}" != "" ]]; then echo 'GOARCH=${{ matrix.goarch }}' >> $GITHUB_ENV ; fi
|
||||||
echo '::set-env name=BUILD_FLAGS::${{ matrix.build_flags }}'
|
if [[ "${{ matrix.cgo }}" != "" ]]; then echo 'CGO_ENABLED=${{ matrix.cgo }}' >> $GITHUB_ENV ; fi
|
||||||
if [[ "${{ matrix.goarch }}" != "" ]]; then echo '::set-env name=GOARCH::${{ matrix.goarch }}' ; fi
|
|
||||||
if [[ "${{ matrix.cgo }}" != "" ]]; then echo '::set-env name=CGO_ENABLED::${{ matrix.cgo }}' ; fi
|
|
||||||
|
|
||||||
- name: Install Libraries on Linux
|
- name: Install Libraries on Linux
|
||||||
shell: bash
|
shell: bash
|
||||||
@@ -136,7 +124,7 @@ jobs:
|
|||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
brew update
|
brew update
|
||||||
brew cask install osxfuse
|
brew install --cask osxfuse
|
||||||
if: matrix.os == 'macOS-latest'
|
if: matrix.os == 'macOS-latest'
|
||||||
|
|
||||||
- name: Install Libraries on Windows
|
- name: Install Libraries on Windows
|
||||||
@@ -144,10 +132,10 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
$ProgressPreference = 'SilentlyContinue'
|
$ProgressPreference = 'SilentlyContinue'
|
||||||
choco install -y winfsp zip
|
choco install -y winfsp zip
|
||||||
Write-Host "::set-env name=CPATH::C:\Program Files\WinFsp\inc\fuse;C:\Program Files (x86)\WinFsp\inc\fuse"
|
echo "CPATH=C:\Program Files\WinFsp\inc\fuse;C:\Program Files (x86)\WinFsp\inc\fuse" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
|
||||||
if ($env:GOARCH -eq "386") {
|
if ($env:GOARCH -eq "386") {
|
||||||
choco install -y mingw --forcex86 --force
|
choco install -y mingw --forcex86 --force
|
||||||
Write-Host "::add-path::C:\\ProgramData\\chocolatey\\lib\\mingw\\tools\\install\\mingw32\\bin"
|
echo "C:\\ProgramData\\chocolatey\\lib\\mingw\\tools\\install\\mingw32\\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
|
||||||
}
|
}
|
||||||
# Copy mingw32-make.exe to make.exe so the same command line
|
# Copy mingw32-make.exe to make.exe so the same command line
|
||||||
# can be used on Windows as on macOS and Linux
|
# can be used on Windows as on macOS and Linux
|
||||||
@@ -167,10 +155,22 @@ jobs:
|
|||||||
printf "\n\nSystem environment:\n\n"
|
printf "\n\nSystem environment:\n\n"
|
||||||
env
|
env
|
||||||
|
|
||||||
- name: Run tests
|
- name: Go module cache
|
||||||
|
uses: actions/cache@v2
|
||||||
|
with:
|
||||||
|
path: ~/go/pkg/mod
|
||||||
|
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-go-
|
||||||
|
|
||||||
|
- name: Build rclone
|
||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
make
|
make
|
||||||
|
|
||||||
|
- name: Run tests
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
make quicktest
|
make quicktest
|
||||||
if: matrix.quicktest
|
if: matrix.quicktest
|
||||||
|
|
||||||
@@ -197,8 +197,9 @@ jobs:
|
|||||||
- name: Deploy built binaries
|
- name: Deploy built binaries
|
||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
if [[ "${{ matrix.os }}" == "ubuntu-latest" ]]; then make release_dep ; fi
|
if [[ "${{ matrix.os }}" == "ubuntu-latest" ]]; then make release_dep_linux ; fi
|
||||||
make travis_beta
|
if [[ "${{ matrix.os }}" == "windows-latest" ]]; then make release_dep_windows ; fi
|
||||||
|
make ci_beta
|
||||||
env:
|
env:
|
||||||
RCLONE_CONFIG_PASS: ${{ secrets.RCLONE_CONFIG_PASS }}
|
RCLONE_CONFIG_PASS: ${{ secrets.RCLONE_CONFIG_PASS }}
|
||||||
# working-directory: '$(modulePath)'
|
# working-directory: '$(modulePath)'
|
||||||
@@ -221,19 +222,19 @@ jobs:
|
|||||||
- name: Set environment variables
|
- name: Set environment variables
|
||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
echo '::set-env name=GOPATH::${{ runner.workspace }}'
|
echo 'GOPATH=${{ runner.workspace }}' >> $GITHUB_ENV
|
||||||
echo '::add-path::${{ runner.workspace }}/bin'
|
echo '${{ runner.workspace }}/bin' >> $GITHUB_PATH
|
||||||
|
|
||||||
- name: Cross-compile rclone
|
- name: Cross-compile rclone
|
||||||
run: |
|
run: |
|
||||||
docker pull billziss/xgo-cgofuse
|
docker pull billziss/xgo-cgofuse
|
||||||
go get -v github.com/karalabe/xgo
|
GO111MODULE=off go get -v github.com/karalabe/xgo # don't add to go.mod
|
||||||
xgo \
|
# xgo \
|
||||||
-image=billziss/xgo-cgofuse \
|
# -image=billziss/xgo-cgofuse \
|
||||||
-targets=darwin/386,darwin/amd64,linux/386,linux/amd64,windows/386,windows/amd64 \
|
# -targets=darwin/amd64,linux/386,linux/amd64,windows/386,windows/amd64 \
|
||||||
-tags cmount \
|
# -tags cmount \
|
||||||
-dest build \
|
# -dest build \
|
||||||
.
|
# .
|
||||||
xgo \
|
xgo \
|
||||||
-image=billziss/xgo-cgofuse \
|
-image=billziss/xgo-cgofuse \
|
||||||
-targets=android/*,ios/* \
|
-targets=android/*,ios/* \
|
||||||
@@ -241,13 +242,13 @@ jobs:
|
|||||||
.
|
.
|
||||||
|
|
||||||
- name: Build rclone
|
- name: Build rclone
|
||||||
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
docker pull golang
|
make
|
||||||
docker run --rm -v "$PWD":/usr/src/rclone -w /usr/src/rclone golang go build -mod=vendor -v
|
|
||||||
|
|
||||||
- name: Upload artifacts
|
- name: Upload artifacts
|
||||||
run: |
|
run: |
|
||||||
make circleci_upload
|
make ci_upload
|
||||||
env:
|
env:
|
||||||
RCLONE_CONFIG_PASS: ${{ secrets.RCLONE_CONFIG_PASS }}
|
RCLONE_CONFIG_PASS: ${{ secrets.RCLONE_CONFIG_PASS }}
|
||||||
# Upload artifacts if not a PR && not a fork
|
# Upload artifacts if not a PR && not a fork
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
name: Docker beta build
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- master
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
name: Build image job
|
||||||
|
steps:
|
||||||
|
- name: Checkout master
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
- name: Build and publish image
|
||||||
|
uses: ilteoood/docker_buildx@1.1.0
|
||||||
|
with:
|
||||||
|
tag: beta
|
||||||
|
imageName: rclone/rclone
|
||||||
|
platform: linux/amd64,linux/386,linux/arm64,linux/arm/v7
|
||||||
|
publish: true
|
||||||
|
dockerHubUser: ${{ secrets.DOCKER_HUB_USER }}
|
||||||
|
dockerHubPassword: ${{ secrets.DOCKER_HUB_PASSWORD }}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
name: Docker release build
|
||||||
|
|
||||||
|
on:
|
||||||
|
release:
|
||||||
|
types: [published]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
name: Build image job
|
||||||
|
steps:
|
||||||
|
- name: Checkout master
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
- name: Get actual patch version
|
||||||
|
id: actual_patch_version
|
||||||
|
run: echo ::set-output name=ACTUAL_PATCH_VERSION::$(echo $GITHUB_REF | cut -d / -f 3 | sed 's/v//g')
|
||||||
|
- name: Get actual minor version
|
||||||
|
id: actual_minor_version
|
||||||
|
run: echo ::set-output name=ACTUAL_MINOR_VERSION::$(echo $GITHUB_REF | cut -d / -f 3 | sed 's/v//g' | cut -d "." -f 1,2)
|
||||||
|
- name: Get actual major version
|
||||||
|
id: actual_major_version
|
||||||
|
run: echo ::set-output name=ACTUAL_MAJOR_VERSION::$(echo $GITHUB_REF | cut -d / -f 3 | sed 's/v//g' | cut -d "." -f 1)
|
||||||
|
- name: Build and publish image
|
||||||
|
uses: ilteoood/docker_buildx@1.1.0
|
||||||
|
with:
|
||||||
|
tag: latest,${{ steps.actual_patch_version.outputs.ACTUAL_PATCH_VERSION }},${{ steps.actual_minor_version.outputs.ACTUAL_MINOR_VERSION }},${{ steps.actual_major_version.outputs.ACTUAL_MAJOR_VERSION }}
|
||||||
|
imageName: rclone/rclone
|
||||||
|
platform: linux/amd64,linux/386,linux/arm64,linux/arm/v7
|
||||||
|
publish: true
|
||||||
|
dockerHubUser: ${{ secrets.DOCKER_HUB_USER }}
|
||||||
|
dockerHubPassword: ${{ secrets.DOCKER_HUB_PASSWORD }}
|
||||||
+3
-1
@@ -7,4 +7,6 @@ rclone.iml
|
|||||||
.idea
|
.idea
|
||||||
.history
|
.history
|
||||||
*.test
|
*.test
|
||||||
*.log
|
*.log
|
||||||
|
*.iml
|
||||||
|
fuzz-build.zip
|
||||||
+34
-41
@@ -12,10 +12,10 @@ When filing an issue, please include the following information if
|
|||||||
possible as well as a description of the problem. Make sure you test
|
possible as well as a description of the problem. Make sure you test
|
||||||
with the [latest beta of rclone](https://beta.rclone.org/):
|
with the [latest beta of rclone](https://beta.rclone.org/):
|
||||||
|
|
||||||
* Rclone version (eg output from `rclone -V`)
|
* Rclone version (e.g. output from `rclone -V`)
|
||||||
* Which OS you are using and how many bits (eg Windows 7, 64 bit)
|
* Which OS you are using and how many bits (e.g. Windows 7, 64 bit)
|
||||||
* The command you were trying to run (eg `rclone copy /tmp remote:tmp`)
|
* The command you were trying to run (e.g. `rclone copy /tmp remote:tmp`)
|
||||||
* A log of the command with the `-vv` flag (eg output from `rclone -vv copy /tmp remote:tmp`)
|
* A log of the command with the `-vv` flag (e.g. output from `rclone -vv copy /tmp remote:tmp`)
|
||||||
* if the log contains secrets then edit the file with a text editor first to obscure them
|
* if the log contains secrets then edit the file with a text editor first to obscure them
|
||||||
|
|
||||||
## Submitting a pull request ##
|
## Submitting a pull request ##
|
||||||
@@ -48,7 +48,7 @@ When ready - run the unit tests for the code you changed
|
|||||||
|
|
||||||
go test -v
|
go test -v
|
||||||
|
|
||||||
Note that you may need to make a test remote, eg `TestSwift` for some
|
Note that you may need to make a test remote, e.g. `TestSwift` for some
|
||||||
of the unit tests.
|
of the unit tests.
|
||||||
|
|
||||||
Note the top level Makefile targets
|
Note the top level Makefile targets
|
||||||
@@ -79,8 +79,15 @@ request](https://help.github.com/articles/creating-a-pull-request/).
|
|||||||
|
|
||||||
You patch will get reviewed and you might get asked to fix some stuff.
|
You patch will get reviewed and you might get asked to fix some stuff.
|
||||||
|
|
||||||
If so, then make the changes in the same branch, squash the commits,
|
If so, then make the changes in the same branch, squash the commits (make multiple commits one commit) by running:
|
||||||
rebase it to master then push it to GitHub with `--force`.
|
```
|
||||||
|
git log # See how many commits you want to squash
|
||||||
|
git reset --soft HEAD~2 # This squashes the 2 latest commits together.
|
||||||
|
git status # Check what will happen, if you made a mistake resetting, you can run git reset 'HEAD@{1}' to undo.
|
||||||
|
git commit # Add a new commit message.
|
||||||
|
git push --force # Push the squashed commit to your GitHub repo.
|
||||||
|
# For more, see Stack Overflow, Git docs, or generally Duck around the web. jtagcat also recommends wizardzines.com
|
||||||
|
```
|
||||||
|
|
||||||
## CI for your fork ##
|
## CI for your fork ##
|
||||||
|
|
||||||
@@ -148,6 +155,7 @@ with modules beneath.
|
|||||||
* ...commands
|
* ...commands
|
||||||
* docs - the documentation and website
|
* docs - the documentation and website
|
||||||
* content - adjust these docs only - everything else is autogenerated
|
* content - adjust these docs only - everything else is autogenerated
|
||||||
|
* command - these are auto generated - edit the corresponding .go file
|
||||||
* fs - main rclone definitions - minimal amount of code
|
* fs - main rclone definitions - minimal amount of code
|
||||||
* accounting - bandwidth limiting and statistics
|
* accounting - bandwidth limiting and statistics
|
||||||
* asyncreader - an io.Reader which reads ahead
|
* asyncreader - an io.Reader which reads ahead
|
||||||
@@ -157,12 +165,12 @@ with modules beneath.
|
|||||||
* fserrors - rclone specific error handling
|
* fserrors - rclone specific error handling
|
||||||
* fshttp - http handling for rclone
|
* fshttp - http handling for rclone
|
||||||
* fspath - path handling for rclone
|
* fspath - path handling for rclone
|
||||||
* hash - defines rclones hash types and functions
|
* hash - defines rclone's hash types and functions
|
||||||
* list - list a remote
|
* list - list a remote
|
||||||
* log - logging facilities
|
* log - logging facilities
|
||||||
* march - iterates directories in lock step
|
* march - iterates directories in lock step
|
||||||
* object - in memory Fs objects
|
* object - in memory Fs objects
|
||||||
* operations - primitives for sync, eg Copy, Move
|
* operations - primitives for sync, e.g. Copy, Move
|
||||||
* sync - sync directories
|
* sync - sync directories
|
||||||
* walk - walk a directory
|
* walk - walk a directory
|
||||||
* fstest - provides integration test framework
|
* fstest - provides integration test framework
|
||||||
@@ -170,7 +178,7 @@ with modules beneath.
|
|||||||
* mockdir - mocks an fs.Directory
|
* mockdir - mocks an fs.Directory
|
||||||
* mockobject - mocks an fs.Object
|
* mockobject - mocks an fs.Object
|
||||||
* test_all - Runs integration tests for everything
|
* test_all - Runs integration tests for everything
|
||||||
* graphics - the images used in the website etc
|
* graphics - the images used in the website, etc.
|
||||||
* lib - libraries used by the backend
|
* lib - libraries used by the backend
|
||||||
* atexit - register functions to run when rclone exits
|
* atexit - register functions to run when rclone exits
|
||||||
* dircache - directory ID to name caching
|
* dircache - directory ID to name caching
|
||||||
@@ -178,7 +186,6 @@ with modules beneath.
|
|||||||
* pacer - retries with backoff and paces operations
|
* pacer - retries with backoff and paces operations
|
||||||
* readers - a selection of useful io.Readers
|
* readers - a selection of useful io.Readers
|
||||||
* rest - a thin abstraction over net/http for REST
|
* rest - a thin abstraction over net/http for REST
|
||||||
* vendor - 3rd party code managed by `go mod`
|
|
||||||
* vfs - Virtual FileSystem layer for implementing rclone mount and similar
|
* vfs - Virtual FileSystem layer for implementing rclone mount and similar
|
||||||
|
|
||||||
## Writing Documentation ##
|
## Writing Documentation ##
|
||||||
@@ -195,14 +202,17 @@ for the flag help, the remainder is shown to the user in `rclone
|
|||||||
config` and is added to the docs with `make backenddocs`.
|
config` and is added to the docs with `make backenddocs`.
|
||||||
|
|
||||||
The only documentation you need to edit are the `docs/content/*.md`
|
The only documentation you need to edit are the `docs/content/*.md`
|
||||||
files. The MANUAL.*, rclone.1, web site etc are all auto generated
|
files. The MANUAL.*, rclone.1, web site, etc. are all auto generated
|
||||||
from those during the release process. See the `make doc` and `make
|
from those during the release process. See the `make doc` and `make
|
||||||
website` targets in the Makefile if you are interested in how. You
|
website` targets in the Makefile if you are interested in how. You
|
||||||
don't need to run these when adding a feature.
|
don't need to run these when adding a feature.
|
||||||
|
|
||||||
Documentation for rclone sub commands is with their code, eg
|
Documentation for rclone sub commands is with their code, e.g.
|
||||||
`cmd/ls/ls.go`.
|
`cmd/ls/ls.go`.
|
||||||
|
|
||||||
|
Note that you can use [GitHub's online editor](https://help.github.com/en/github/managing-files-in-a-repository/editing-files-in-another-users-repository)
|
||||||
|
for small changes in the docs which makes it very easy.
|
||||||
|
|
||||||
## Making a release ##
|
## Making a release ##
|
||||||
|
|
||||||
There are separate instructions for making a release in the RELEASE.md
|
There are separate instructions for making a release in the RELEASE.md
|
||||||
@@ -255,43 +265,27 @@ rclone uses the [go
|
|||||||
modules](https://tip.golang.org/cmd/go/#hdr-Modules__module_versions__and_more)
|
modules](https://tip.golang.org/cmd/go/#hdr-Modules__module_versions__and_more)
|
||||||
support in go1.11 and later to manage its dependencies.
|
support in go1.11 and later to manage its dependencies.
|
||||||
|
|
||||||
**NB** you must be using go1.11 or above to add a dependency to
|
rclone can be built with modules outside of the GOPATH
|
||||||
rclone. Rclone will still build with older versions of go, but we use
|
|
||||||
the `go mod` command for dependencies which is only in go1.11 and
|
|
||||||
above.
|
|
||||||
|
|
||||||
rclone can be built with modules outside of the GOPATH, but for
|
|
||||||
backwards compatibility with older go versions, rclone also maintains
|
|
||||||
a `vendor` directory with all the external code rclone needs for
|
|
||||||
building.
|
|
||||||
|
|
||||||
The `vendor` directory is entirely managed by the `go mod` tool, do
|
|
||||||
not add things manually.
|
|
||||||
|
|
||||||
To add a dependency `github.com/ncw/new_dependency` see the
|
To add a dependency `github.com/ncw/new_dependency` see the
|
||||||
instructions below. These will fetch the dependency, add it to
|
instructions below. These will fetch the dependency and add it to
|
||||||
`go.mod` and `go.sum` and vendor it for older go versions.
|
`go.mod` and `go.sum`.
|
||||||
|
|
||||||
GO111MODULE=on go get github.com/ncw/new_dependency
|
GO111MODULE=on go get github.com/ncw/new_dependency
|
||||||
GO111MODULE=on go mod vendor
|
|
||||||
|
|
||||||
You can add constraints on that package when doing `go get` (see the
|
You can add constraints on that package when doing `go get` (see the
|
||||||
go docs linked above), but don't unless you really need to.
|
go docs linked above), but don't unless you really need to.
|
||||||
|
|
||||||
Please check in the changes generated by `go mod` including the
|
Please check in the changes generated by `go mod` including `go.mod`
|
||||||
`vendor` directory and `go.mod` and `go.sum` in a single commit
|
and `go.sum` in the same commit as your other changes.
|
||||||
separate from any other code changes with the title "vendor: add
|
|
||||||
github.com/ncw/new_dependency". Remember to `git add` any new files
|
|
||||||
in `vendor`.
|
|
||||||
|
|
||||||
## Updating a dependency ##
|
## Updating a dependency ##
|
||||||
|
|
||||||
If you need to update a dependency then run
|
If you need to update a dependency then run
|
||||||
|
|
||||||
GO111MODULE=on go get -u github.com/pkg/errors
|
GO111MODULE=on go get -u github.com/pkg/errors
|
||||||
GO111MODULE=on go mod vendor
|
|
||||||
|
|
||||||
Check in in a single commit as above.
|
Check in a single commit as above.
|
||||||
|
|
||||||
## Updating all the dependencies ##
|
## Updating all the dependencies ##
|
||||||
|
|
||||||
@@ -337,10 +331,9 @@ Getting going
|
|||||||
* Add your remote to the imports in `backend/all/all.go`
|
* Add your remote to the imports in `backend/all/all.go`
|
||||||
* HTTP based remotes are easiest to maintain if they use rclone's rest module, but if there is a really good go SDK then use that instead.
|
* HTTP based remotes are easiest to maintain if they use rclone's rest module, but if there is a really good go SDK then use that instead.
|
||||||
* Try to implement as many optional methods as possible as it makes the remote more usable.
|
* Try to implement as many optional methods as possible as it makes the remote more usable.
|
||||||
* Use fs/encoder to make sure we can encode any path name and `rclone info` to help determine the encodings needed
|
* Use lib/encoder to make sure we can encode any path name and `rclone info` to help determine the encodings needed
|
||||||
* `go install -tags noencode`
|
|
||||||
* `rclone purge -v TestRemote:rclone-info`
|
* `rclone purge -v TestRemote:rclone-info`
|
||||||
* `rclone info -vv --write-json remote.json TestRemote:rclone-info`
|
* `rclone info --remote-encoding None -vv --write-json remote.json TestRemote:rclone-info`
|
||||||
* `go run cmd/info/internal/build_csv/main.go -o remote.csv remote.json`
|
* `go run cmd/info/internal/build_csv/main.go -o remote.csv remote.json`
|
||||||
* open `remote.csv` in a spreadsheet and examine
|
* open `remote.csv` in a spreadsheet and examine
|
||||||
|
|
||||||
@@ -355,7 +348,7 @@ Integration tests
|
|||||||
* Add your backend to `fstest/test_all/config.yaml`
|
* Add your backend to `fstest/test_all/config.yaml`
|
||||||
* Once you've done that then you can use the integration test framework from the project root:
|
* Once you've done that then you can use the integration test framework from the project root:
|
||||||
* go install ./...
|
* go install ./...
|
||||||
* test_all -backend remote
|
* test_all -backends remote
|
||||||
|
|
||||||
Or if you want to run the integration tests manually:
|
Or if you want to run the integration tests manually:
|
||||||
|
|
||||||
@@ -371,7 +364,7 @@ See the [testing](#testing) section for more information on integration tests.
|
|||||||
|
|
||||||
Add your fs to the docs - you'll need to pick an icon for it from
|
Add your fs to the docs - you'll need to pick an icon for it from
|
||||||
[fontawesome](http://fontawesome.io/icons/). Keep lists of remotes in
|
[fontawesome](http://fontawesome.io/icons/). Keep lists of remotes in
|
||||||
alphabetical order of full name of remote (eg `drive` is ordered as
|
alphabetical order of full name of remote (e.g. `drive` is ordered as
|
||||||
`Google Drive`) but with the local file system last.
|
`Google Drive`) but with the local file system last.
|
||||||
|
|
||||||
* `README.md` - main GitHub page
|
* `README.md` - main GitHub page
|
||||||
@@ -380,7 +373,7 @@ alphabetical order of full name of remote (eg `drive` is ordered as
|
|||||||
* update them with `make backenddocs` - revert any changes in other backends
|
* update them with `make backenddocs` - revert any changes in other backends
|
||||||
* `docs/content/overview.md` - overview docs
|
* `docs/content/overview.md` - overview docs
|
||||||
* `docs/content/docs.md` - list of remotes in config section
|
* `docs/content/docs.md` - list of remotes in config section
|
||||||
* `docs/content/about.md` - front page of rclone.org
|
* `docs/content/_index.md` - front page of rclone.org
|
||||||
* `docs/layouts/chrome/navbar.html` - add it to the website navigation
|
* `docs/layouts/chrome/navbar.html` - add it to the website navigation
|
||||||
* `bin/make_manual.py` - add the page to the `docs` constant
|
* `bin/make_manual.py` - add the page to the `docs` constant
|
||||||
|
|
||||||
|
|||||||
+3
-3
@@ -3,16 +3,16 @@ FROM golang AS builder
|
|||||||
COPY . /go/src/github.com/rclone/rclone/
|
COPY . /go/src/github.com/rclone/rclone/
|
||||||
WORKDIR /go/src/github.com/rclone/rclone/
|
WORKDIR /go/src/github.com/rclone/rclone/
|
||||||
|
|
||||||
RUN make quicktest
|
|
||||||
RUN \
|
RUN \
|
||||||
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
|
CGO_ENABLED=0 \
|
||||||
make
|
make
|
||||||
RUN ./rclone version
|
RUN ./rclone version
|
||||||
|
|
||||||
# Begin final image
|
# Begin final image
|
||||||
FROM alpine:latest
|
FROM alpine:latest
|
||||||
|
|
||||||
RUN apk --no-cache add ca-certificates fuse
|
RUN apk --no-cache add ca-certificates fuse tzdata && \
|
||||||
|
echo "user_allow_other" >> /etc/fuse.conf
|
||||||
|
|
||||||
COPY --from=builder /go/src/github.com/rclone/rclone/rclone /usr/local/bin/
|
COPY --from=builder /go/src/github.com/rclone/rclone/rclone /usr/local/bin/
|
||||||
|
|
||||||
|
|||||||
+17
-14
@@ -2,17 +2,20 @@
|
|||||||
|
|
||||||
Current active maintainers of rclone are:
|
Current active maintainers of rclone are:
|
||||||
|
|
||||||
| Name | GitHub ID | Specific Responsibilities |
|
| Name | GitHub ID | Specific Responsibilities |
|
||||||
| :--------------- | :---------- | :-------------------------- |
|
| :--------------- | :---------------- | :-------------------------- |
|
||||||
| Nick Craig-Wood | @ncw | overall project health |
|
| Nick Craig-Wood | @ncw | overall project health |
|
||||||
| Stefan Breunig | @breunigs | |
|
| Stefan Breunig | @breunigs | |
|
||||||
| Ishuah Kariuki | @ishuah | |
|
| Ishuah Kariuki | @ishuah | |
|
||||||
| Remus Bunduc | @remusb | cache backend |
|
| Remus Bunduc | @remusb | cache backend |
|
||||||
| Fabian Möller | @B4dM4n | |
|
| Fabian Möller | @B4dM4n | |
|
||||||
| Alex Chen | @Cnly | onedrive backend |
|
| Alex Chen | @Cnly | onedrive backend |
|
||||||
| Sandeep Ummadi | @sandeepkru | azureblob backend |
|
| Sandeep Ummadi | @sandeepkru | azureblob backend |
|
||||||
| Sebastian Bünger | @buengese | jottacloud & yandex backends |
|
| Sebastian Bünger | @buengese | jottacloud, yandex & compress backends |
|
||||||
| Ivan Andreev | @ivandeex | chunker & mailru backends |
|
| Ivan Andreev | @ivandeex | chunker & mailru backends |
|
||||||
|
| Max Sum | @Max-Sum | union backend |
|
||||||
|
| Fred | @creativeprojects | seafile backend |
|
||||||
|
| Caleb Case | @calebcase | tardigrade backend |
|
||||||
|
|
||||||
**This is a work in progress Draft**
|
**This is a work in progress Draft**
|
||||||
|
|
||||||
@@ -30,11 +33,11 @@ Rclone uses the labels like this:
|
|||||||
* `duplicate` - normally close these and ask the user to subscribe to the original
|
* `duplicate` - normally close these and ask the user to subscribe to the original
|
||||||
* `enhancement: new remote` - a new rclone backend
|
* `enhancement: new remote` - a new rclone backend
|
||||||
* `enhancement` - a new feature
|
* `enhancement` - a new feature
|
||||||
* `FUSE` - do do with `rclone mount` command
|
* `FUSE` - to do with `rclone mount` command
|
||||||
* `good first issue` - mark these if you find a small self contained issue - these get shown to new visitors to the project
|
* `good first issue` - mark these if you find a small self contained issue - these get shown to new visitors to the project
|
||||||
* `help` wanted - mark these if you find a self contained issue - these get shown to new visitors to the project
|
* `help` wanted - mark these if you find a self contained issue - these get shown to new visitors to the project
|
||||||
* `IMPORTANT` - note to maintainers not to forget to fix this for the release
|
* `IMPORTANT` - note to maintainers not to forget to fix this for the release
|
||||||
* `maintenance` - internal enhancement, code re-organisation etc
|
* `maintenance` - internal enhancement, code re-organisation, etc.
|
||||||
* `Needs Go 1.XX` - waiting for that version of Go to be released
|
* `Needs Go 1.XX` - waiting for that version of Go to be released
|
||||||
* `question` - not a `bug` or `enhancement` - direct to the forum for next time
|
* `question` - not a `bug` or `enhancement` - direct to the forum for next time
|
||||||
* `Remote: XXX` - which rclone backend this affects
|
* `Remote: XXX` - which rclone backend this affects
|
||||||
@@ -42,7 +45,7 @@ Rclone uses the labels like this:
|
|||||||
|
|
||||||
If it turns out to be a bug or an enhancement it should be tagged as such, with the appropriate other tags. Don't forget the "good first issue" tag to give new contributors something easy to do to get going.
|
If it turns out to be a bug or an enhancement it should be tagged as such, with the appropriate other tags. Don't forget the "good first issue" tag to give new contributors something easy to do to get going.
|
||||||
|
|
||||||
When a ticket is tagged it should be added to a milestone, either the next release, the one after, Soon or Help Wanted. Bugs can be added to the "Known Bugs" milestone if they aren't planned to be fixed or need to wait for something (eg the next go release).
|
When a ticket is tagged it should be added to a milestone, either the next release, the one after, Soon or Help Wanted. Bugs can be added to the "Known Bugs" milestone if they aren't planned to be fixed or need to wait for something (e.g. the next go release).
|
||||||
|
|
||||||
The milestones have these meanings:
|
The milestones have these meanings:
|
||||||
|
|
||||||
|
|||||||
Generated
+16743
-8763
File diff suppressed because it is too large.
Load diff
Generated
+19104
-8481
File diff suppressed because it is too large.
Load diff
@@ -1,33 +1,35 @@
|
|||||||
SHELL = bash
|
SHELL = bash
|
||||||
# Branch we are working on
|
# Branch we are working on
|
||||||
BRANCH := $(or $(APPVEYOR_REPO_BRANCH),$(TRAVIS_BRANCH),$(BUILD_SOURCEBRANCHNAME),$(lastword $(subst /, ,$(GITHUB_REF))),$(shell git rev-parse --abbrev-ref HEAD))
|
BRANCH := $(or $(BUILD_SOURCEBRANCHNAME),$(lastword $(subst /, ,$(GITHUB_REF))),$(shell git rev-parse --abbrev-ref HEAD))
|
||||||
# Tag of the current commit, if any. If this is not "" then we are building a release
|
# Tag of the current commit, if any. If this is not "" then we are building a release
|
||||||
RELEASE_TAG := $(shell git tag -l --points-at HEAD)
|
RELEASE_TAG := $(shell git tag -l --points-at HEAD)
|
||||||
# Version of last release (may not be on this branch)
|
# Version of last release (may not be on this branch)
|
||||||
VERSION := $(shell cat VERSION)
|
VERSION := $(shell cat VERSION)
|
||||||
# Last tag on this branch
|
# Last tag on this branch
|
||||||
LAST_TAG := $(shell git describe --tags --abbrev=0)
|
LAST_TAG := $(shell git describe --tags --abbrev=0)
|
||||||
|
# Next version
|
||||||
|
NEXT_VERSION := $(shell echo $(VERSION) | awk -F. -v OFS=. '{print $$1,$$2+1,0}')
|
||||||
|
NEXT_PATCH_VERSION := $(shell echo $(VERSION) | awk -F. -v OFS=. '{print $$1,$$2,$$3+1}')
|
||||||
# If we are working on a release, override branch to master
|
# If we are working on a release, override branch to master
|
||||||
ifdef RELEASE_TAG
|
ifdef RELEASE_TAG
|
||||||
BRANCH := master
|
BRANCH := master
|
||||||
|
LAST_TAG := $(shell git describe --abbrev=0 --tags $(VERSION)^)
|
||||||
endif
|
endif
|
||||||
TAG_BRANCH := -$(BRANCH)
|
TAG_BRANCH := .$(BRANCH)
|
||||||
BRANCH_PATH := branch/
|
BRANCH_PATH := branch/$(BRANCH)/
|
||||||
# If building HEAD or master then unset TAG_BRANCH and BRANCH_PATH
|
# If building HEAD or master then unset TAG_BRANCH and BRANCH_PATH
|
||||||
ifeq ($(subst HEAD,,$(subst master,,$(BRANCH))),)
|
ifeq ($(subst HEAD,,$(subst master,,$(BRANCH))),)
|
||||||
TAG_BRANCH :=
|
TAG_BRANCH :=
|
||||||
BRANCH_PATH :=
|
BRANCH_PATH :=
|
||||||
endif
|
endif
|
||||||
# Make version suffix -DDD-gCCCCCCCC (D=commits since last relase, C=Commit) or blank
|
# Make version suffix -beta.NNNN.CCCCCCCC (N=Commit number, C=Commit)
|
||||||
VERSION_SUFFIX := $(shell git describe --abbrev=8 --tags | perl -lpe 's/^v\d+\.\d+\.\d+//; s/^-(\d+)/"-".sprintf("%03d",$$1)/e;')
|
VERSION_SUFFIX := -beta.$(shell git rev-list --count HEAD).$(shell git show --no-patch --no-notes --pretty='%h' HEAD)
|
||||||
# TAG is current version + number of commits since last release + branch
|
# TAG is current version + commit number + commit + branch
|
||||||
TAG := $(VERSION)$(VERSION_SUFFIX)$(TAG_BRANCH)
|
TAG := $(VERSION)$(VERSION_SUFFIX)$(TAG_BRANCH)
|
||||||
NEXT_VERSION := $(shell echo $(VERSION) | perl -lpe 's/v//; $$_ += 0.01; $$_ = sprintf("v%.2f.0", $$_)')
|
ifdef RELEASE_TAG
|
||||||
ifndef RELEASE_TAG
|
TAG := $(RELEASE_TAG)
|
||||||
TAG := $(TAG)-beta
|
|
||||||
endif
|
endif
|
||||||
GO_VERSION := $(shell go version)
|
GO_VERSION := $(shell go version)
|
||||||
GO_FILES := $(shell go list ./... | grep -v /vendor/ )
|
|
||||||
ifdef BETA_SUBDIR
|
ifdef BETA_SUBDIR
|
||||||
BETA_SUBDIR := /$(BETA_SUBDIR)
|
BETA_SUBDIR := /$(BETA_SUBDIR)
|
||||||
endif
|
endif
|
||||||
@@ -44,23 +46,26 @@ endif
|
|||||||
.PHONY: rclone test_all vars version
|
.PHONY: rclone test_all vars version
|
||||||
|
|
||||||
rclone:
|
rclone:
|
||||||
go build -v --ldflags "-s -X github.com/rclone/rclone/fs.Version=$(TAG)" $(BUILDTAGS)
|
go build -v --ldflags "-s -X github.com/rclone/rclone/fs.Version=$(TAG)" $(BUILDTAGS) $(BUILD_ARGS)
|
||||||
mkdir -p `go env GOPATH`/bin/
|
mkdir -p `go env GOPATH`/bin/
|
||||||
cp -av rclone`go env GOEXE` `go env GOPATH`/bin/rclone`go env GOEXE`.new
|
cp -av rclone`go env GOEXE` `go env GOPATH`/bin/rclone`go env GOEXE`.new
|
||||||
mv -v `go env GOPATH`/bin/rclone`go env GOEXE`.new `go env GOPATH`/bin/rclone`go env GOEXE`
|
mv -v `go env GOPATH`/bin/rclone`go env GOEXE`.new `go env GOPATH`/bin/rclone`go env GOEXE`
|
||||||
|
|
||||||
test_all:
|
test_all:
|
||||||
go install --ldflags "-s -X github.com/rclone/rclone/fs.Version=$(TAG)" $(BUILDTAGS) github.com/rclone/rclone/fstest/test_all
|
go install --ldflags "-s -X github.com/rclone/rclone/fs.Version=$(TAG)" $(BUILDTAGS) $(BUILD_ARGS) github.com/rclone/rclone/fstest/test_all
|
||||||
|
|
||||||
vars:
|
vars:
|
||||||
@echo SHELL="'$(SHELL)'"
|
@echo SHELL="'$(SHELL)'"
|
||||||
@echo BRANCH="'$(BRANCH)'"
|
@echo BRANCH="'$(BRANCH)'"
|
||||||
@echo TAG="'$(TAG)'"
|
@echo TAG="'$(TAG)'"
|
||||||
@echo VERSION="'$(VERSION)'"
|
@echo VERSION="'$(VERSION)'"
|
||||||
@echo NEXT_VERSION="'$(NEXT_VERSION)'"
|
|
||||||
@echo GO_VERSION="'$(GO_VERSION)'"
|
@echo GO_VERSION="'$(GO_VERSION)'"
|
||||||
@echo BETA_URL="'$(BETA_URL)'"
|
@echo BETA_URL="'$(BETA_URL)'"
|
||||||
|
|
||||||
|
btest:
|
||||||
|
@echo "[$(TAG)]($(BETA_URL)) on branch [$(BRANCH)](https://github.com/rclone/rclone/tree/$(BRANCH)) (uploaded in 15-30 mins)" | xclip -r -sel clip
|
||||||
|
@echo "Copied markdown of beta release to clip board"
|
||||||
|
|
||||||
version:
|
version:
|
||||||
@echo '$(TAG)'
|
@echo '$(TAG)'
|
||||||
|
|
||||||
@@ -71,10 +76,10 @@ test: rclone test_all
|
|||||||
|
|
||||||
# Quick test
|
# Quick test
|
||||||
quicktest:
|
quicktest:
|
||||||
RCLONE_CONFIG="/notfound" go test $(BUILDTAGS) $(GO_FILES)
|
RCLONE_CONFIG="/notfound" go test $(BUILDTAGS) ./...
|
||||||
|
|
||||||
racequicktest:
|
racequicktest:
|
||||||
RCLONE_CONFIG="/notfound" go test $(BUILDTAGS) -cpu=2 -race $(GO_FILES)
|
RCLONE_CONFIG="/notfound" go test $(BUILDTAGS) -cpu=2 -race ./...
|
||||||
|
|
||||||
# Do source code quality checks
|
# Do source code quality checks
|
||||||
check: rclone
|
check: rclone
|
||||||
@@ -86,35 +91,42 @@ check: rclone
|
|||||||
build_dep:
|
build_dep:
|
||||||
go run bin/get-github-release.go -extract golangci-lint golangci/golangci-lint 'golangci-lint-.*\.tar\.gz'
|
go run bin/get-github-release.go -extract golangci-lint golangci/golangci-lint 'golangci-lint-.*\.tar\.gz'
|
||||||
|
|
||||||
# Get the release dependencies
|
# Get the release dependencies we only install on linux
|
||||||
release_dep:
|
release_dep_linux:
|
||||||
go run bin/get-github-release.go -extract nfpm goreleaser/nfpm 'nfpm_.*_Linux_x86_64.tar.gz'
|
cd /tmp && go get github.com/goreleaser/nfpm/v2/...
|
||||||
go run bin/get-github-release.go -extract github-release aktau/github-release 'linux-amd64-github-release.tar.bz2'
|
|
||||||
|
# Get the release dependencies we only install on Windows
|
||||||
|
release_dep_windows:
|
||||||
|
GO111MODULE=off GOOS="" GOARCH="" go get github.com/josephspurrier/goversioninfo/cmd/goversioninfo
|
||||||
|
|
||||||
# Update dependencies
|
# Update dependencies
|
||||||
|
showupdates:
|
||||||
|
@echo "*** Direct dependencies that could be updated ***"
|
||||||
|
@GO111MODULE=on go list -u -f '{{if (and (not (or .Main .Indirect)) .Update)}}{{.Path}}: {{.Version}} -> {{.Update.Version}}{{end}}' -m all 2> /dev/null
|
||||||
|
|
||||||
|
# Update direct and indirect dependencies and test dependencies
|
||||||
update:
|
update:
|
||||||
GO111MODULE=on go get -u ./...
|
GO111MODULE=on go get -u -t ./...
|
||||||
|
-#GO111MODULE=on go get -d $(go list -m -f '{{if not (or .Main .Indirect)}}{{.Path}}{{end}}' all)
|
||||||
GO111MODULE=on go mod tidy
|
GO111MODULE=on go mod tidy
|
||||||
GO111MODULE=on go mod vendor
|
|
||||||
|
|
||||||
# Tidy the module dependencies
|
# Tidy the module dependencies
|
||||||
tidy:
|
tidy:
|
||||||
GO111MODULE=on go mod tidy
|
GO111MODULE=on go mod tidy
|
||||||
GO111MODULE=on go mod vendor
|
|
||||||
|
|
||||||
doc: rclone.1 MANUAL.html MANUAL.txt rcdocs commanddocs
|
doc: rclone.1 MANUAL.html MANUAL.txt rcdocs commanddocs
|
||||||
|
|
||||||
rclone.1: MANUAL.md
|
rclone.1: MANUAL.md
|
||||||
pandoc -s --from markdown --to man MANUAL.md -o rclone.1
|
pandoc -s --from markdown-smart --to man MANUAL.md -o rclone.1
|
||||||
|
|
||||||
MANUAL.md: bin/make_manual.py docs/content/*.md commanddocs backenddocs
|
MANUAL.md: bin/make_manual.py docs/content/*.md commanddocs backenddocs
|
||||||
./bin/make_manual.py
|
./bin/make_manual.py
|
||||||
|
|
||||||
MANUAL.html: MANUAL.md
|
MANUAL.html: MANUAL.md
|
||||||
pandoc -s --from markdown --to html MANUAL.md -o MANUAL.html
|
pandoc -s --from markdown-smart --to html MANUAL.md -o MANUAL.html
|
||||||
|
|
||||||
MANUAL.txt: MANUAL.md
|
MANUAL.txt: MANUAL.md
|
||||||
pandoc -s --from markdown --to plain MANUAL.md -o MANUAL.txt
|
pandoc -s --from markdown-smart --to plain MANUAL.md -o MANUAL.txt
|
||||||
|
|
||||||
commanddocs: rclone
|
commanddocs: rclone
|
||||||
XDG_CACHE_HOME="" XDG_CONFIG_HOME="" HOME="\$$HOME" USER="\$$USER" rclone gendocs docs/content/
|
XDG_CACHE_HOME="" XDG_CONFIG_HOME="" HOME="\$$HOME" USER="\$$USER" rclone gendocs docs/content/
|
||||||
@@ -136,14 +148,27 @@ clean:
|
|||||||
rm -f rclone fs/operations/operations.test fs/sync/sync.test fs/test_all.log test.log
|
rm -f rclone fs/operations/operations.test fs/sync/sync.test fs/test_all.log test.log
|
||||||
|
|
||||||
website:
|
website:
|
||||||
|
rm -rf docs/public
|
||||||
cd docs && hugo
|
cd docs && hugo
|
||||||
|
@if grep -R "raw HTML omitted" docs/public ; then echo "ERROR: found unescaped HTML - fix the markdown source" ; fi
|
||||||
|
|
||||||
upload_website: website
|
upload_website: website
|
||||||
rclone -v sync docs/public memstore:www-rclone-org
|
rclone -v sync docs/public memstore:www-rclone-org
|
||||||
|
|
||||||
|
upload_test_website: website
|
||||||
|
rclone -P sync docs/public test-rclone-org:
|
||||||
|
|
||||||
|
validate_website: website
|
||||||
|
find docs/public -type f -name "*.html" | xargs tidy --mute-id yes -errors --gnu-emacs yes --drop-empty-elements no --warn-proprietary-attributes no --mute MISMATCHED_ATTRIBUTE_WARN
|
||||||
|
|
||||||
tarball:
|
tarball:
|
||||||
git archive -9 --format=tar.gz --prefix=rclone-$(TAG)/ -o build/rclone-$(TAG).tar.gz $(TAG)
|
git archive -9 --format=tar.gz --prefix=rclone-$(TAG)/ -o build/rclone-$(TAG).tar.gz $(TAG)
|
||||||
|
|
||||||
|
vendorball:
|
||||||
|
go mod vendor
|
||||||
|
tar -zcf build/rclone-$(TAG)-vendor.tar.gz vendor
|
||||||
|
rm -rf vendor
|
||||||
|
|
||||||
sign_upload:
|
sign_upload:
|
||||||
cd build && md5sum rclone-v* | gpg --clearsign > MD5SUMS
|
cd build && md5sum rclone-v* | gpg --clearsign > MD5SUMS
|
||||||
cd build && sha1sum rclone-v* | gpg --clearsign > SHA1SUMS
|
cd build && sha1sum rclone-v* | gpg --clearsign > SHA1SUMS
|
||||||
@@ -162,10 +187,10 @@ upload_github:
|
|||||||
./bin/upload-github $(TAG)
|
./bin/upload-github $(TAG)
|
||||||
|
|
||||||
cross: doc
|
cross: doc
|
||||||
go run bin/cross-compile.go -release current $(BUILDTAGS) $(TAG)
|
go run bin/cross-compile.go -release current $(BUILDTAGS) $(BUILD_ARGS) $(TAG)
|
||||||
|
|
||||||
beta:
|
beta:
|
||||||
go run bin/cross-compile.go $(BUILDTAGS) $(TAG)
|
go run bin/cross-compile.go $(BUILDTAGS) $(BUILD_ARGS) $(TAG)
|
||||||
rclone -v copy build/ memstore:pub-rclone-org/$(TAG)
|
rclone -v copy build/ memstore:pub-rclone-org/$(TAG)
|
||||||
@echo Beta release ready at https://pub.rclone.org/$(TAG)/
|
@echo Beta release ready at https://pub.rclone.org/$(TAG)/
|
||||||
|
|
||||||
@@ -173,61 +198,61 @@ log_since_last_release:
|
|||||||
git log $(LAST_TAG)..
|
git log $(LAST_TAG)..
|
||||||
|
|
||||||
compile_all:
|
compile_all:
|
||||||
go run bin/cross-compile.go -compile-only $(BUILDTAGS) $(TAG)
|
go run bin/cross-compile.go -compile-only $(BUILDTAGS) $(BUILD_ARGS) $(TAG)
|
||||||
|
|
||||||
appveyor_upload:
|
ci_upload:
|
||||||
rclone --config bin/travis.rclone.conf -v copy --exclude '*beta-latest*' build/ $(BETA_UPLOAD)
|
sudo chown -R $$USER build
|
||||||
ifndef BRANCH_PATH
|
find build -type l -delete
|
||||||
rclone --config bin/travis.rclone.conf -v copy --include '*beta-latest*' --include version.txt build/ $(BETA_UPLOAD_ROOT)
|
gzip -r9v build
|
||||||
endif
|
|
||||||
@echo Beta release ready at $(BETA_URL)
|
|
||||||
|
|
||||||
circleci_upload:
|
|
||||||
./rclone --config bin/travis.rclone.conf -v copy build/ $(BETA_UPLOAD)/testbuilds
|
./rclone --config bin/travis.rclone.conf -v copy build/ $(BETA_UPLOAD)/testbuilds
|
||||||
ifndef BRANCH_PATH
|
ifeq ($(or $(BRANCH_PATH),$(RELEASE_TAG)),)
|
||||||
./rclone --config bin/travis.rclone.conf -v copy build/ $(BETA_UPLOAD_ROOT)/test/testbuilds-latest
|
./rclone --config bin/travis.rclone.conf -v copy build/ $(BETA_UPLOAD_ROOT)/test/testbuilds-latest
|
||||||
endif
|
endif
|
||||||
@echo Beta release ready at $(BETA_URL)/testbuilds
|
@echo Beta release ready at $(BETA_URL)/testbuilds
|
||||||
|
|
||||||
travis_beta:
|
ci_beta:
|
||||||
ifeq (linux,$(filter linux,$(subst Linux,linux,$(TRAVIS_OS_NAME) $(AGENT_OS))))
|
|
||||||
go run bin/get-github-release.go -extract nfpm goreleaser/nfpm 'nfpm_.*\.tar.gz'
|
|
||||||
endif
|
|
||||||
git log $(LAST_TAG).. > /tmp/git-log.txt
|
git log $(LAST_TAG).. > /tmp/git-log.txt
|
||||||
go run bin/cross-compile.go -release beta-latest -git-log /tmp/git-log.txt $(BUILD_FLAGS) $(BUILDTAGS) $(TAG)
|
go run bin/cross-compile.go -release beta-latest -git-log /tmp/git-log.txt $(BUILD_FLAGS) $(BUILDTAGS) $(BUILD_ARGS) $(TAG)
|
||||||
rclone --config bin/travis.rclone.conf -v copy --exclude '*beta-latest*' build/ $(BETA_UPLOAD)
|
rclone --config bin/travis.rclone.conf -v copy --exclude '*beta-latest*' build/ $(BETA_UPLOAD)
|
||||||
ifndef BRANCH_PATH
|
ifeq ($(or $(BRANCH_PATH),$(RELEASE_TAG)),)
|
||||||
rclone --config bin/travis.rclone.conf -v copy --include '*beta-latest*' --include version.txt build/ $(BETA_UPLOAD_ROOT)$(BETA_SUBDIR)
|
rclone --config bin/travis.rclone.conf -v copy --include '*beta-latest*' --include version.txt build/ $(BETA_UPLOAD_ROOT)$(BETA_SUBDIR)
|
||||||
endif
|
endif
|
||||||
@echo Beta release ready at $(BETA_URL)
|
@echo Beta release ready at $(BETA_URL)
|
||||||
|
|
||||||
# Fetch the binary builds from travis and appveyor
|
# Fetch the binary builds from GitHub actions
|
||||||
fetch_binaries:
|
fetch_binaries:
|
||||||
rclone -P sync --exclude "/testbuilds/**" --delete-excluded $(BETA_UPLOAD) build/
|
rclone -P sync --exclude "/testbuilds/**" --delete-excluded $(BETA_UPLOAD) build/
|
||||||
|
|
||||||
serve: website
|
serve: website
|
||||||
cd docs && hugo server -v -w
|
cd docs && hugo server -v -w --disableFastRender
|
||||||
|
|
||||||
tag: doc
|
tag: retag doc
|
||||||
@echo "Old tag is $(VERSION)"
|
bin/make_changelog.py $(LAST_TAG) $(VERSION) > docs/content/changelog.md.new
|
||||||
@echo "New tag is $(NEXT_VERSION)"
|
|
||||||
echo -e "package fs\n\n// Version of rclone\nvar Version = \"$(NEXT_VERSION)\"\n" | gofmt > fs/version.go
|
|
||||||
echo -n "$(NEXT_VERSION)" > docs/layouts/partials/version.html
|
|
||||||
echo "$(NEXT_VERSION)" > VERSION
|
|
||||||
git tag -s -m "Version $(NEXT_VERSION)" $(NEXT_VERSION)
|
|
||||||
bin/make_changelog.py $(LAST_TAG) $(NEXT_VERSION) > docs/content/changelog.md.new
|
|
||||||
mv docs/content/changelog.md.new docs/content/changelog.md
|
mv docs/content/changelog.md.new docs/content/changelog.md
|
||||||
@echo "Edit the new changelog in docs/content/changelog.md"
|
@echo "Edit the new changelog in docs/content/changelog.md"
|
||||||
@echo "Then commit all the changes"
|
@echo "Then commit all the changes"
|
||||||
@echo git commit -m \"Version $(NEXT_VERSION)\" -a -v
|
@echo git commit -m \"Version $(VERSION)\" -a -v
|
||||||
@echo "And finally run make retag before make cross etc"
|
@echo "And finally run make retag before make cross, etc."
|
||||||
|
|
||||||
retag:
|
retag:
|
||||||
|
@echo "Version is $(VERSION)"
|
||||||
git tag -f -s -m "Version $(VERSION)" $(VERSION)
|
git tag -f -s -m "Version $(VERSION)" $(VERSION)
|
||||||
|
|
||||||
startdev:
|
startdev:
|
||||||
echo -e "package fs\n\n// Version of rclone\nvar Version = \"$(VERSION)-DEV\"\n" | gofmt > fs/version.go
|
@echo "Version is $(VERSION)"
|
||||||
git commit -m "Start $(VERSION)-DEV development" fs/version.go
|
@echo "Next version is $(NEXT_VERSION)"
|
||||||
|
echo -e "package fs\n\n// Version of rclone\nvar Version = \"$(NEXT_VERSION)-DEV\"\n" | gofmt > fs/version.go
|
||||||
|
echo -n "$(NEXT_VERSION)" > docs/layouts/partials/version.html
|
||||||
|
echo "$(NEXT_VERSION)" > VERSION
|
||||||
|
git commit -m "Start $(NEXT_VERSION)-DEV development" fs/version.go VERSION docs/layouts/partials/version.html
|
||||||
|
|
||||||
|
startstable:
|
||||||
|
@echo "Version is $(VERSION)"
|
||||||
|
@echo "Next stable version is $(NEXT_PATCH_VERSION)"
|
||||||
|
echo -e "package fs\n\n// Version of rclone\nvar Version = \"$(NEXT_PATCH_VERSION)-DEV\"\n" | gofmt > fs/version.go
|
||||||
|
echo -n "$(NEXT_PATCH_VERSION)" > docs/layouts/partials/version.html
|
||||||
|
echo "$(NEXT_PATCH_VERSION)" > VERSION
|
||||||
|
git commit -m "Start $(NEXT_PATCH_VERSION)-DEV development" fs/version.go VERSION docs/layouts/partials/version.html
|
||||||
|
|
||||||
winzip:
|
winzip:
|
||||||
zip -9 rclone-$(TAG).zip rclone.exe
|
zip -9 rclone-$(TAG).zip rclone.exe
|
||||||
@@ -8,10 +8,7 @@
|
|||||||
[Installation](https://rclone.org/install/) |
|
[Installation](https://rclone.org/install/) |
|
||||||
[Forum](https://forum.rclone.org/)
|
[Forum](https://forum.rclone.org/)
|
||||||
|
|
||||||
[](https://travis-ci.org/rclone/rclone)
|
[](https://github.com/rclone/rclone/actions?query=workflow%3Abuild)
|
||||||
[](https://ci.appveyor.com/project/rclone/rclone)
|
|
||||||
[](https://dev.azure.com/rclone/rclone/_build/latest?definitionId=2&branchName=master)
|
|
||||||
[](https://circleci.com/gh/rclone/rclone/tree/master)
|
|
||||||
[](https://goreportcard.com/report/github.com/rclone/rclone)
|
[](https://goreportcard.com/report/github.com/rclone/rclone)
|
||||||
[](https://godoc.org/github.com/rclone/rclone)
|
[](https://godoc.org/github.com/rclone/rclone)
|
||||||
[](https://hub.docker.com/r/rclone/rclone)
|
[](https://hub.docker.com/r/rclone/rclone)
|
||||||
@@ -33,11 +30,13 @@ Rclone *("rsync for cloud storage")* is a command line program to sync files and
|
|||||||
* DigitalOcean Spaces [:page_facing_up:](https://rclone.org/s3/#digitalocean-spaces)
|
* DigitalOcean Spaces [:page_facing_up:](https://rclone.org/s3/#digitalocean-spaces)
|
||||||
* Dreamhost [:page_facing_up:](https://rclone.org/s3/#dreamhost)
|
* Dreamhost [:page_facing_up:](https://rclone.org/s3/#dreamhost)
|
||||||
* Dropbox [:page_facing_up:](https://rclone.org/dropbox/)
|
* Dropbox [:page_facing_up:](https://rclone.org/dropbox/)
|
||||||
|
* Enterprise File Fabric [:page_facing_up:](https://rclone.org/filefabric/)
|
||||||
* FTP [:page_facing_up:](https://rclone.org/ftp/)
|
* FTP [:page_facing_up:](https://rclone.org/ftp/)
|
||||||
* GetSky [:page_facing_up:](https://rclone.org/jottacloud/)
|
* GetSky [:page_facing_up:](https://rclone.org/jottacloud/)
|
||||||
* Google Cloud Storage [:page_facing_up:](https://rclone.org/googlecloudstorage/)
|
* Google Cloud Storage [:page_facing_up:](https://rclone.org/googlecloudstorage/)
|
||||||
* Google Drive [:page_facing_up:](https://rclone.org/drive/)
|
* Google Drive [:page_facing_up:](https://rclone.org/drive/)
|
||||||
* Google Photos [:page_facing_up:](https://rclone.org/googlephotos/)
|
* Google Photos [:page_facing_up:](https://rclone.org/googlephotos/)
|
||||||
|
* HDFS (Hadoop Distributed Filesystem) [:page_facing_up:](https://rclone.org/hdfs/)
|
||||||
* HTTP [:page_facing_up:](https://rclone.org/http/)
|
* HTTP [:page_facing_up:](https://rclone.org/http/)
|
||||||
* Hubic [:page_facing_up:](https://rclone.org/hubic/)
|
* Hubic [:page_facing_up:](https://rclone.org/hubic/)
|
||||||
* Jottacloud [:page_facing_up:](https://rclone.org/jottacloud/)
|
* Jottacloud [:page_facing_up:](https://rclone.org/jottacloud/)
|
||||||
@@ -46,6 +45,7 @@ Rclone *("rsync for cloud storage")* is a command line program to sync files and
|
|||||||
* Mail.ru Cloud [:page_facing_up:](https://rclone.org/mailru/)
|
* Mail.ru Cloud [:page_facing_up:](https://rclone.org/mailru/)
|
||||||
* Memset Memstore [:page_facing_up:](https://rclone.org/swift/)
|
* Memset Memstore [:page_facing_up:](https://rclone.org/swift/)
|
||||||
* Mega [:page_facing_up:](https://rclone.org/mega/)
|
* Mega [:page_facing_up:](https://rclone.org/mega/)
|
||||||
|
* Memory [:page_facing_up:](https://rclone.org/memory/)
|
||||||
* Microsoft Azure Blob Storage [:page_facing_up:](https://rclone.org/azureblob/)
|
* Microsoft Azure Blob Storage [:page_facing_up:](https://rclone.org/azureblob/)
|
||||||
* Microsoft OneDrive [:page_facing_up:](https://rclone.org/onedrive/)
|
* Microsoft OneDrive [:page_facing_up:](https://rclone.org/onedrive/)
|
||||||
* Minio [:page_facing_up:](https://rclone.org/s3/#minio)
|
* Minio [:page_facing_up:](https://rclone.org/s3/#minio)
|
||||||
@@ -61,10 +61,16 @@ Rclone *("rsync for cloud storage")* is a command line program to sync files and
|
|||||||
* QingStor [:page_facing_up:](https://rclone.org/qingstor/)
|
* QingStor [:page_facing_up:](https://rclone.org/qingstor/)
|
||||||
* Rackspace Cloud Files [:page_facing_up:](https://rclone.org/swift/)
|
* Rackspace Cloud Files [:page_facing_up:](https://rclone.org/swift/)
|
||||||
* Scaleway [:page_facing_up:](https://rclone.org/s3/#scaleway)
|
* Scaleway [:page_facing_up:](https://rclone.org/s3/#scaleway)
|
||||||
|
* Seafile [:page_facing_up:](https://rclone.org/seafile/)
|
||||||
* SFTP [:page_facing_up:](https://rclone.org/sftp/)
|
* SFTP [:page_facing_up:](https://rclone.org/sftp/)
|
||||||
|
* StackPath [:page_facing_up:](https://rclone.org/s3/#stackpath)
|
||||||
|
* SugarSync [:page_facing_up:](https://rclone.org/sugarsync/)
|
||||||
|
* Tardigrade [:page_facing_up:](https://rclone.org/tardigrade/)
|
||||||
|
* Tencent Cloud Object Storage (COS) [:page_facing_up:](https://rclone.org/s3/#tencent-cos)
|
||||||
* Wasabi [:page_facing_up:](https://rclone.org/s3/#wasabi)
|
* Wasabi [:page_facing_up:](https://rclone.org/s3/#wasabi)
|
||||||
* WebDAV [:page_facing_up:](https://rclone.org/webdav/)
|
* WebDAV [:page_facing_up:](https://rclone.org/webdav/)
|
||||||
* Yandex Disk [:page_facing_up:](https://rclone.org/yandex/)
|
* Yandex Disk [:page_facing_up:](https://rclone.org/yandex/)
|
||||||
|
* Zoho WorkDrive [:page_facing_up:](https://rclone.org/zoho/)
|
||||||
* The local filesystem [:page_facing_up:](https://rclone.org/local/)
|
* The local filesystem [:page_facing_up:](https://rclone.org/local/)
|
||||||
|
|
||||||
Please see [the full list of all storage providers and their features](https://rclone.org/overview/)
|
Please see [the full list of all storage providers and their features](https://rclone.org/overview/)
|
||||||
@@ -79,6 +85,7 @@ Please see [the full list of all storage providers and their features](https://r
|
|||||||
* [Check](https://rclone.org/commands/rclone_check/) mode to check for file hash equality
|
* [Check](https://rclone.org/commands/rclone_check/) mode to check for file hash equality
|
||||||
* Can sync to and from network, e.g. two different cloud accounts
|
* Can sync to and from network, e.g. two different cloud accounts
|
||||||
* Optional large file chunking ([Chunker](https://rclone.org/chunker/))
|
* Optional large file chunking ([Chunker](https://rclone.org/chunker/))
|
||||||
|
* Optional transparent compression ([Compress](https://rclone.org/compress/))
|
||||||
* Optional encryption ([Crypt](https://rclone.org/crypt/))
|
* Optional encryption ([Crypt](https://rclone.org/crypt/))
|
||||||
* Optional cache ([Cache](https://rclone.org/cache/))
|
* Optional cache ([Cache](https://rclone.org/cache/))
|
||||||
* Optional FUSE mount ([rclone mount](https://rclone.org/commands/rclone_mount/))
|
* Optional FUSE mount ([rclone mount](https://rclone.org/commands/rclone_mount/))
|
||||||
|
|||||||
+31
-55
@@ -4,35 +4,37 @@ This file describes how to make the various kinds of releases
|
|||||||
|
|
||||||
## Extra required software for making a release
|
## Extra required software for making a release
|
||||||
|
|
||||||
* [github-release](https://github.com/aktau/github-release) for uploading packages
|
* [gh the github cli](https://github.com/cli/cli) for uploading packages
|
||||||
* pandoc for making the html and man pages
|
* pandoc for making the html and man pages
|
||||||
|
|
||||||
## Making a release
|
## Making a release
|
||||||
|
|
||||||
|
* git checkout master # see below for stable branch
|
||||||
|
* git pull
|
||||||
* git status - make sure everything is checked in
|
* git status - make sure everything is checked in
|
||||||
* Check travis & appveyor builds are green
|
* Check GitHub actions build for master is Green
|
||||||
* make check
|
|
||||||
* make test # see integration test server or run locally
|
* make test # see integration test server or run locally
|
||||||
* make tag
|
* make tag
|
||||||
* edit docs/content/changelog.md
|
* edit docs/content/changelog.md # make sure to remove duplicate logs from point releases
|
||||||
* make tidy
|
* make tidy
|
||||||
* make doc
|
* make doc
|
||||||
* git status - to check for new man pages - git add them
|
* git status - to check for new man pages - git add them
|
||||||
* git commit -a -v -m "Version v1.XX.0"
|
* git commit -a -v -m "Version v1.XX.0"
|
||||||
* make retag
|
* make retag
|
||||||
* git push --tags origin master
|
* git push --follow-tags origin
|
||||||
* # Wait for the appveyor and travis builds to complete then...
|
* # Wait for the GitHub builds to complete then...
|
||||||
* make fetch_binaries
|
* make fetch_binaries
|
||||||
* make tarball
|
* make tarball
|
||||||
|
* make vendorball
|
||||||
* make sign_upload
|
* make sign_upload
|
||||||
* make check_sign
|
* make check_sign
|
||||||
* make upload
|
* make upload
|
||||||
* make upload_website
|
* make upload_website
|
||||||
* make upload_github
|
* make upload_github
|
||||||
* make startdev
|
* make startdev # make startstable for stable branch
|
||||||
* # announce with forum post, twitter post, G+ post
|
* # announce with forum post, twitter post, patreon post
|
||||||
|
|
||||||
Early in the next release cycle update the vendored dependencies
|
Early in the next release cycle update the dependencies
|
||||||
|
|
||||||
* Review any pinned packages in go.mod and remove if possible
|
* Review any pinned packages in go.mod and remove if possible
|
||||||
* make update
|
* make update
|
||||||
@@ -40,71 +42,45 @@ Early in the next release cycle update the vendored dependencies
|
|||||||
* git add new files
|
* git add new files
|
||||||
* git commit -a -v
|
* git commit -a -v
|
||||||
|
|
||||||
If `make update` fails with errors like this:
|
|
||||||
|
|
||||||
```
|
|
||||||
# github.com/cpuguy83/go-md2man/md2man
|
|
||||||
../../../../pkg/mod/github.com/cpuguy83/go-md2man@v1.0.8/md2man/md2man.go:11:16: undefined: blackfriday.EXTENSION_NO_INTRA_EMPHASIS
|
|
||||||
../../../../pkg/mod/github.com/cpuguy83/go-md2man@v1.0.8/md2man/md2man.go:12:16: undefined: blackfriday.EXTENSION_TABLES
|
|
||||||
```
|
|
||||||
|
|
||||||
Can be fixed with
|
|
||||||
|
|
||||||
* GO111MODULE=on go get -u github.com/russross/blackfriday@v1.5.2
|
|
||||||
* GO111MODULE=on go mod tidy
|
|
||||||
* GO111MODULE=on go mod vendor
|
|
||||||
|
|
||||||
|
|
||||||
## Making a point release
|
## Making a point release
|
||||||
|
|
||||||
If rclone needs a point release due to some horrendous bug:
|
If rclone needs a point release due to some horrendous bug:
|
||||||
|
|
||||||
|
Set vars
|
||||||
|
|
||||||
|
* BASE_TAG=v1.XX # e.g. v1.52
|
||||||
|
* NEW_TAG=${BASE_TAG}.Y # e.g. v1.52.1
|
||||||
|
* echo $BASE_TAG $NEW_TAG # v1.52 v1.52.1
|
||||||
|
|
||||||
First make the release branch. If this is a second point release then
|
First make the release branch. If this is a second point release then
|
||||||
this will be done already.
|
this will be done already.
|
||||||
|
|
||||||
* BASE_TAG=v1.XX # eg v1.49
|
* git branch ${BASE_TAG} ${BASE_TAG}-stable
|
||||||
* NEW_TAG=${BASE_TAG}.Y # eg v1.49.1
|
* git co ${BASE_TAG}-stable
|
||||||
* echo $BASE_TAG $NEW_TAG # v1.49 v1.49.1
|
* make startstable
|
||||||
* git branch ${BASE_TAG} ${BASE_TAG}-fixes
|
|
||||||
|
|
||||||
Now
|
Now
|
||||||
|
|
||||||
* git co ${BASE_TAG}-fixes
|
* git co ${BASE_TAG}-stable
|
||||||
* git cherry-pick any fixes
|
* git cherry-pick any fixes
|
||||||
* Test (see above)
|
* Do the steps as above
|
||||||
* make NEXT_VERSION=${NEW_TAG} tag
|
* make startstable
|
||||||
* edit docs/content/changelog.md
|
|
||||||
* make TAG=${NEW_TAG} doc
|
|
||||||
* git commit -a -v -m "Version ${NEW_TAG}"
|
|
||||||
* git tag -d ${NEW_TAG}
|
|
||||||
* git tag -s -m "Version ${NEW_TAG}" ${NEW_TAG}
|
|
||||||
* git push --tags -u origin ${BASE_TAG}-fixes
|
|
||||||
* Wait for builds to complete
|
|
||||||
* make BRANCH_PATH= TAG=${NEW_TAG} fetch_binaries
|
|
||||||
* make TAG=${NEW_TAG} tarball
|
|
||||||
* make TAG=${NEW_TAG} sign_upload
|
|
||||||
* make TAG=${NEW_TAG} check_sign
|
|
||||||
* make TAG=${NEW_TAG} upload
|
|
||||||
* make TAG=${NEW_TAG} upload_website
|
|
||||||
* make TAG=${NEW_TAG} upload_github
|
|
||||||
* NB this overwrites the current beta so we need to do this
|
|
||||||
* git co master
|
* git co master
|
||||||
* make VERSION=${NEW_TAG} startdev
|
* `#` cherry pick the changes to the changelog - check the diff to make sure it is correct
|
||||||
* # cherry pick the changes to the changelog and VERSION
|
* git checkout ${BASE_TAG}-stable docs/content/changelog.md
|
||||||
* git checkout ${BASE_TAG}-fixes VERSION docs/content/changelog.md
|
* git commit -a -v -m "Changelog updates from Version ${NEW_TAG}"
|
||||||
* git commit --amend
|
|
||||||
* git push
|
* git push
|
||||||
* Announce!
|
|
||||||
|
|
||||||
## Making a manual build of docker
|
## Making a manual build of docker
|
||||||
|
|
||||||
The rclone docker image should autobuild on docker hub. If it doesn't
|
The rclone docker image should autobuild on via GitHub actions. If it doesn't
|
||||||
or needs to be updated then rebuild like this.
|
or needs to be updated then rebuild like this.
|
||||||
|
|
||||||
```
|
```
|
||||||
docker build -t rclone/rclone:1.49.1 -t rclone/rclone:1.49 -t rclone/rclone:1 -t rclone/rclone:latest .
|
docker pull golang
|
||||||
docker push rclone/rclone:1.49.1
|
docker build --rm --ulimit memlock=67108864 -t rclone/rclone:1.52.0 -t rclone/rclone:1.52 -t rclone/rclone:1 -t rclone/rclone:latest .
|
||||||
docker push rclone/rclone:1.49
|
docker push rclone/rclone:1.52.0
|
||||||
|
docker push rclone/rclone:1.52
|
||||||
docker push rclone/rclone:1
|
docker push rclone/rclone:1
|
||||||
docker push rclone/rclone:latest
|
docker push rclone/rclone:latest
|
||||||
```
|
```
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
package alias
|
package alias
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/rclone/rclone/fs"
|
"github.com/rclone/rclone/fs"
|
||||||
|
"github.com/rclone/rclone/fs/cache"
|
||||||
"github.com/rclone/rclone/fs/config/configmap"
|
"github.com/rclone/rclone/fs/config/configmap"
|
||||||
"github.com/rclone/rclone/fs/config/configstruct"
|
"github.com/rclone/rclone/fs/config/configstruct"
|
||||||
"github.com/rclone/rclone/fs/fspath"
|
"github.com/rclone/rclone/fs/fspath"
|
||||||
@@ -33,7 +35,7 @@ type Options struct {
|
|||||||
// NewFs constructs an Fs from the path.
|
// NewFs constructs an Fs from the path.
|
||||||
//
|
//
|
||||||
// The returned Fs is the actual Fs, referenced by remote in the config
|
// The returned Fs is the actual Fs, referenced by remote in the config
|
||||||
func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {
|
||||||
// Parse config into Options struct
|
// Parse config into Options struct
|
||||||
opt := new(Options)
|
opt := new(Options)
|
||||||
err := configstruct.Set(m, opt)
|
err := configstruct.Set(m, opt)
|
||||||
@@ -46,9 +48,5 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
if strings.HasPrefix(opt.Remote, name+":") {
|
if strings.HasPrefix(opt.Remote, name+":") {
|
||||||
return nil, errors.New("can't point alias remote at itself - check the value of the remote setting")
|
return nil, errors.New("can't point alias remote at itself - check the value of the remote setting")
|
||||||
}
|
}
|
||||||
fsInfo, configName, fsPath, config, err := fs.ConfigFs(opt.Remote)
|
return cache.Get(ctx, fspath.JoinRootPath(opt.Remote, root))
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return fsInfo.NewFs(configName, fspath.JoinRootPath(fsPath, root), config)
|
|
||||||
}
|
}
|
||||||
@@ -19,7 +19,7 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func prepare(t *testing.T, root string) {
|
func prepare(t *testing.T, root string) {
|
||||||
config.LoadConfig()
|
config.LoadConfig(context.Background())
|
||||||
|
|
||||||
// Configure the remote
|
// Configure the remote
|
||||||
config.FileSet(remoteName, "type", "alias")
|
config.FileSet(remoteName, "type", "alias")
|
||||||
@@ -54,21 +54,22 @@ func TestNewFS(t *testing.T) {
|
|||||||
{"four/under four.txt", 9, false},
|
{"four/under four.txt", 9, false},
|
||||||
}},
|
}},
|
||||||
{"four", "..", "", true, []testEntry{
|
{"four", "..", "", true, []testEntry{
|
||||||
{"four", -1, true},
|
{"five", -1, true},
|
||||||
{"one%.txt", 6, false},
|
{"under four.txt", 9, false},
|
||||||
{"three", -1, true},
|
|
||||||
{"two.html", 7, false},
|
|
||||||
}},
|
}},
|
||||||
{"four", "../three", "", true, []testEntry{
|
{"", "../../three", "", true, []testEntry{
|
||||||
{"underthree.txt", 9, false},
|
{"underthree.txt", 9, false},
|
||||||
}},
|
}},
|
||||||
|
{"four", "../../five", "", true, []testEntry{
|
||||||
|
{"underfive.txt", 6, false},
|
||||||
|
}},
|
||||||
} {
|
} {
|
||||||
what := fmt.Sprintf("test %d remoteRoot=%q, fsRoot=%q, fsList=%q", testi, test.remoteRoot, test.fsRoot, test.fsList)
|
what := fmt.Sprintf("test %d remoteRoot=%q, fsRoot=%q, fsList=%q", testi, test.remoteRoot, test.fsRoot, test.fsList)
|
||||||
|
|
||||||
remoteRoot, err := filepath.Abs(filepath.FromSlash(path.Join("test/files", test.remoteRoot)))
|
remoteRoot, err := filepath.Abs(filepath.FromSlash(path.Join("test/files", test.remoteRoot)))
|
||||||
require.NoError(t, err, what)
|
require.NoError(t, err, what)
|
||||||
prepare(t, remoteRoot)
|
prepare(t, remoteRoot)
|
||||||
f, err := fs.NewFs(fmt.Sprintf("%s:%s", remoteName, test.fsRoot))
|
f, err := fs.NewFs(context.Background(), fmt.Sprintf("%s:%s", remoteName, test.fsRoot))
|
||||||
require.NoError(t, err, what)
|
require.NoError(t, err, what)
|
||||||
gotEntries, err := f.List(context.Background(), test.fsList)
|
gotEntries, err := f.List(context.Background(), test.fsList)
|
||||||
require.NoError(t, err, what)
|
require.NoError(t, err, what)
|
||||||
@@ -90,7 +91,7 @@ func TestNewFS(t *testing.T) {
|
|||||||
|
|
||||||
func TestNewFSNoRemote(t *testing.T) {
|
func TestNewFSNoRemote(t *testing.T) {
|
||||||
prepare(t, "")
|
prepare(t, "")
|
||||||
f, err := fs.NewFs(fmt.Sprintf("%s:", remoteName))
|
f, err := fs.NewFs(context.Background(), fmt.Sprintf("%s:", remoteName))
|
||||||
|
|
||||||
require.Error(t, err)
|
require.Error(t, err)
|
||||||
require.Nil(t, f)
|
require.Nil(t, f)
|
||||||
@@ -98,7 +99,7 @@ func TestNewFSNoRemote(t *testing.T) {
|
|||||||
|
|
||||||
func TestNewFSInvalidRemote(t *testing.T) {
|
func TestNewFSInvalidRemote(t *testing.T) {
|
||||||
prepare(t, "not_existing_test_remote:")
|
prepare(t, "not_existing_test_remote:")
|
||||||
f, err := fs.NewFs(fmt.Sprintf("%s:", remoteName))
|
f, err := fs.NewFs(context.Background(), fmt.Sprintf("%s:", remoteName))
|
||||||
|
|
||||||
require.Error(t, err)
|
require.Error(t, err)
|
||||||
require.Nil(t, f)
|
require.Nil(t, f)
|
||||||
|
|||||||
@@ -9,13 +9,16 @@ import (
|
|||||||
_ "github.com/rclone/rclone/backend/box"
|
_ "github.com/rclone/rclone/backend/box"
|
||||||
_ "github.com/rclone/rclone/backend/cache"
|
_ "github.com/rclone/rclone/backend/cache"
|
||||||
_ "github.com/rclone/rclone/backend/chunker"
|
_ "github.com/rclone/rclone/backend/chunker"
|
||||||
|
_ "github.com/rclone/rclone/backend/compress"
|
||||||
_ "github.com/rclone/rclone/backend/crypt"
|
_ "github.com/rclone/rclone/backend/crypt"
|
||||||
_ "github.com/rclone/rclone/backend/drive"
|
_ "github.com/rclone/rclone/backend/drive"
|
||||||
_ "github.com/rclone/rclone/backend/dropbox"
|
_ "github.com/rclone/rclone/backend/dropbox"
|
||||||
_ "github.com/rclone/rclone/backend/fichier"
|
_ "github.com/rclone/rclone/backend/fichier"
|
||||||
|
_ "github.com/rclone/rclone/backend/filefabric"
|
||||||
_ "github.com/rclone/rclone/backend/ftp"
|
_ "github.com/rclone/rclone/backend/ftp"
|
||||||
_ "github.com/rclone/rclone/backend/googlecloudstorage"
|
_ "github.com/rclone/rclone/backend/googlecloudstorage"
|
||||||
_ "github.com/rclone/rclone/backend/googlephotos"
|
_ "github.com/rclone/rclone/backend/googlephotos"
|
||||||
|
_ "github.com/rclone/rclone/backend/hdfs"
|
||||||
_ "github.com/rclone/rclone/backend/http"
|
_ "github.com/rclone/rclone/backend/http"
|
||||||
_ "github.com/rclone/rclone/backend/hubic"
|
_ "github.com/rclone/rclone/backend/hubic"
|
||||||
_ "github.com/rclone/rclone/backend/jottacloud"
|
_ "github.com/rclone/rclone/backend/jottacloud"
|
||||||
@@ -23,6 +26,7 @@ import (
|
|||||||
_ "github.com/rclone/rclone/backend/local"
|
_ "github.com/rclone/rclone/backend/local"
|
||||||
_ "github.com/rclone/rclone/backend/mailru"
|
_ "github.com/rclone/rclone/backend/mailru"
|
||||||
_ "github.com/rclone/rclone/backend/mega"
|
_ "github.com/rclone/rclone/backend/mega"
|
||||||
|
_ "github.com/rclone/rclone/backend/memory"
|
||||||
_ "github.com/rclone/rclone/backend/onedrive"
|
_ "github.com/rclone/rclone/backend/onedrive"
|
||||||
_ "github.com/rclone/rclone/backend/opendrive"
|
_ "github.com/rclone/rclone/backend/opendrive"
|
||||||
_ "github.com/rclone/rclone/backend/pcloud"
|
_ "github.com/rclone/rclone/backend/pcloud"
|
||||||
@@ -30,10 +34,14 @@ import (
|
|||||||
_ "github.com/rclone/rclone/backend/putio"
|
_ "github.com/rclone/rclone/backend/putio"
|
||||||
_ "github.com/rclone/rclone/backend/qingstor"
|
_ "github.com/rclone/rclone/backend/qingstor"
|
||||||
_ "github.com/rclone/rclone/backend/s3"
|
_ "github.com/rclone/rclone/backend/s3"
|
||||||
|
_ "github.com/rclone/rclone/backend/seafile"
|
||||||
_ "github.com/rclone/rclone/backend/sftp"
|
_ "github.com/rclone/rclone/backend/sftp"
|
||||||
_ "github.com/rclone/rclone/backend/sharefile"
|
_ "github.com/rclone/rclone/backend/sharefile"
|
||||||
|
_ "github.com/rclone/rclone/backend/sugarsync"
|
||||||
_ "github.com/rclone/rclone/backend/swift"
|
_ "github.com/rclone/rclone/backend/swift"
|
||||||
|
_ "github.com/rclone/rclone/backend/tardigrade"
|
||||||
_ "github.com/rclone/rclone/backend/union"
|
_ "github.com/rclone/rclone/backend/union"
|
||||||
_ "github.com/rclone/rclone/backend/webdav"
|
_ "github.com/rclone/rclone/backend/webdav"
|
||||||
_ "github.com/rclone/rclone/backend/yandex"
|
_ "github.com/rclone/rclone/backend/yandex"
|
||||||
|
_ "github.com/rclone/rclone/backend/zoho"
|
||||||
)
|
)
|
||||||
@@ -28,18 +28,17 @@ import (
|
|||||||
"github.com/rclone/rclone/fs/config"
|
"github.com/rclone/rclone/fs/config"
|
||||||
"github.com/rclone/rclone/fs/config/configmap"
|
"github.com/rclone/rclone/fs/config/configmap"
|
||||||
"github.com/rclone/rclone/fs/config/configstruct"
|
"github.com/rclone/rclone/fs/config/configstruct"
|
||||||
"github.com/rclone/rclone/fs/encodings"
|
|
||||||
"github.com/rclone/rclone/fs/fserrors"
|
"github.com/rclone/rclone/fs/fserrors"
|
||||||
"github.com/rclone/rclone/fs/fshttp"
|
"github.com/rclone/rclone/fs/fshttp"
|
||||||
"github.com/rclone/rclone/fs/hash"
|
"github.com/rclone/rclone/fs/hash"
|
||||||
"github.com/rclone/rclone/lib/dircache"
|
"github.com/rclone/rclone/lib/dircache"
|
||||||
|
"github.com/rclone/rclone/lib/encoder"
|
||||||
"github.com/rclone/rclone/lib/oauthutil"
|
"github.com/rclone/rclone/lib/oauthutil"
|
||||||
"github.com/rclone/rclone/lib/pacer"
|
"github.com/rclone/rclone/lib/pacer"
|
||||||
"golang.org/x/oauth2"
|
"golang.org/x/oauth2"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
enc = encodings.AmazonCloudDrive
|
|
||||||
folderKind = "FOLDER"
|
folderKind = "FOLDER"
|
||||||
fileKind = "FILE"
|
fileKind = "FILE"
|
||||||
statusAvailable = "AVAILABLE"
|
statusAvailable = "AVAILABLE"
|
||||||
@@ -71,29 +70,13 @@ func init() {
|
|||||||
Prefix: "acd",
|
Prefix: "acd",
|
||||||
Description: "Amazon Drive",
|
Description: "Amazon Drive",
|
||||||
NewFs: NewFs,
|
NewFs: NewFs,
|
||||||
Config: func(name string, m configmap.Mapper) {
|
Config: func(ctx context.Context, name string, m configmap.Mapper) {
|
||||||
err := oauthutil.Config("amazon cloud drive", name, m, acdConfig)
|
err := oauthutil.Config(ctx, "amazon cloud drive", name, m, acdConfig, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Failed to configure token: %v", err)
|
log.Fatalf("Failed to configure token: %v", err)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
Options: []fs.Option{{
|
Options: append(oauthutil.SharedOptions, []fs.Option{{
|
||||||
Name: config.ConfigClientID,
|
|
||||||
Help: "Amazon Application Client ID.",
|
|
||||||
Required: true,
|
|
||||||
}, {
|
|
||||||
Name: config.ConfigClientSecret,
|
|
||||||
Help: "Amazon Application Client Secret.",
|
|
||||||
Required: true,
|
|
||||||
}, {
|
|
||||||
Name: config.ConfigAuthURL,
|
|
||||||
Help: "Auth server URL.\nLeave blank to use Amazon's.",
|
|
||||||
Advanced: true,
|
|
||||||
}, {
|
|
||||||
Name: config.ConfigTokenURL,
|
|
||||||
Help: "Token server url.\nleave blank to use Amazon's.",
|
|
||||||
Advanced: true,
|
|
||||||
}, {
|
|
||||||
Name: "checkpoint",
|
Name: "checkpoint",
|
||||||
Help: "Checkpoint for internal polling (debug).",
|
Help: "Checkpoint for internal polling (debug).",
|
||||||
Hide: fs.OptionHideBoth,
|
Hide: fs.OptionHideBoth,
|
||||||
@@ -137,15 +120,23 @@ which downloads the file through a temporary URL directly from the
|
|||||||
underlying S3 storage.`,
|
underlying S3 storage.`,
|
||||||
Default: defaultTempLinkThreshold,
|
Default: defaultTempLinkThreshold,
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
}},
|
}, {
|
||||||
|
Name: config.ConfigEncoding,
|
||||||
|
Help: config.ConfigEncodingHelp,
|
||||||
|
Advanced: true,
|
||||||
|
// Encode invalid UTF-8 bytes as json doesn't handle them properly.
|
||||||
|
Default: (encoder.Base |
|
||||||
|
encoder.EncodeInvalidUtf8),
|
||||||
|
}}...),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Options defines the configuration for this backend
|
// Options defines the configuration for this backend
|
||||||
type Options struct {
|
type Options struct {
|
||||||
Checkpoint string `config:"checkpoint"`
|
Checkpoint string `config:"checkpoint"`
|
||||||
UploadWaitPerGB fs.Duration `config:"upload_wait_per_gb"`
|
UploadWaitPerGB fs.Duration `config:"upload_wait_per_gb"`
|
||||||
TempLinkThreshold fs.SizeSuffix `config:"templink_threshold"`
|
TempLinkThreshold fs.SizeSuffix `config:"templink_threshold"`
|
||||||
|
Enc encoder.MultiEncoder `config:"encoding"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fs represents a remote acd server
|
// Fs represents a remote acd server
|
||||||
@@ -153,6 +144,7 @@ type Fs struct {
|
|||||||
name string // name of this remote
|
name string // name of this remote
|
||||||
features *fs.Features // optional features
|
features *fs.Features // optional features
|
||||||
opt Options // options for this Fs
|
opt Options // options for this Fs
|
||||||
|
ci *fs.ConfigInfo // global config
|
||||||
c *acd.Client // the connection to the acd server
|
c *acd.Client // the connection to the acd server
|
||||||
noAuthClient *http.Client // unauthenticated http client
|
noAuthClient *http.Client // unauthenticated http client
|
||||||
root string // the path we are working on
|
root string // the path we are working on
|
||||||
@@ -162,7 +154,7 @@ type Fs struct {
|
|||||||
tokenRenewer *oauthutil.Renew // renew the token on expiry
|
tokenRenewer *oauthutil.Renew // renew the token on expiry
|
||||||
}
|
}
|
||||||
|
|
||||||
// Object describes a acd object
|
// Object describes an acd object
|
||||||
//
|
//
|
||||||
// Will definitely have info but maybe not meta
|
// Will definitely have info but maybe not meta
|
||||||
type Object struct {
|
type Object struct {
|
||||||
@@ -222,7 +214,7 @@ func (f *Fs) shouldRetry(resp *http.Response, err error) (bool, error) {
|
|||||||
}
|
}
|
||||||
// Work around receiving this error sporadically on authentication
|
// Work around receiving this error sporadically on authentication
|
||||||
//
|
//
|
||||||
// HTTP code 403: "403 Forbidden", reponse body: {"message":"Authorization header requires 'Credential' parameter. Authorization header requires 'Signature' parameter. Authorization header requires 'SignedHeaders' parameter. Authorization header requires existence of either a 'X-Amz-Date' or a 'Date' header. Authorization=Bearer"}
|
// HTTP code 403: "403 Forbidden", response body: {"message":"Authorization header requires 'Credential' parameter. Authorization header requires 'Signature' parameter. Authorization header requires 'SignedHeaders' parameter. Authorization header requires existence of either a 'X-Amz-Date' or a 'Date' header. Authorization=Bearer"}
|
||||||
if resp.StatusCode == 403 && strings.Contains(err.Error(), "Authorization header requires") {
|
if resp.StatusCode == 403 && strings.Contains(err.Error(), "Authorization header requires") {
|
||||||
fs.Debugf(f, "403 \"Authorization header requires...\" error received - retry")
|
fs.Debugf(f, "403 \"Authorization header requires...\" error received - retry")
|
||||||
return true, err
|
return true, err
|
||||||
@@ -248,8 +240,7 @@ func filterRequest(req *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// NewFs constructs an Fs from the path, container:path
|
// NewFs constructs an Fs from the path, container:path
|
||||||
func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {
|
||||||
ctx := context.Background()
|
|
||||||
// Parse config into Options struct
|
// Parse config into Options struct
|
||||||
opt := new(Options)
|
opt := new(Options)
|
||||||
err := configstruct.Set(m, opt)
|
err := configstruct.Set(m, opt)
|
||||||
@@ -257,7 +248,7 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
root = parsePath(root)
|
root = parsePath(root)
|
||||||
baseClient := fshttp.NewClient(fs.Config)
|
baseClient := fshttp.NewClient(ctx)
|
||||||
if do, ok := baseClient.Transport.(interface {
|
if do, ok := baseClient.Transport.(interface {
|
||||||
SetRequestFilter(f func(req *http.Request))
|
SetRequestFilter(f func(req *http.Request))
|
||||||
}); ok {
|
}); ok {
|
||||||
@@ -265,25 +256,27 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
} else {
|
} else {
|
||||||
fs.Debugf(name+":", "Couldn't add request filter - large file downloads will fail")
|
fs.Debugf(name+":", "Couldn't add request filter - large file downloads will fail")
|
||||||
}
|
}
|
||||||
oAuthClient, ts, err := oauthutil.NewClientWithBaseClient(name, m, acdConfig, baseClient)
|
oAuthClient, ts, err := oauthutil.NewClientWithBaseClient(ctx, name, m, acdConfig, baseClient)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "failed to configure Amazon Drive")
|
return nil, errors.Wrap(err, "failed to configure Amazon Drive")
|
||||||
}
|
}
|
||||||
|
|
||||||
c := acd.NewClient(oAuthClient)
|
c := acd.NewClient(oAuthClient)
|
||||||
|
ci := fs.GetConfig(ctx)
|
||||||
f := &Fs{
|
f := &Fs{
|
||||||
name: name,
|
name: name,
|
||||||
root: root,
|
root: root,
|
||||||
opt: *opt,
|
opt: *opt,
|
||||||
|
ci: ci,
|
||||||
c: c,
|
c: c,
|
||||||
pacer: fs.NewPacer(pacer.NewAmazonCloudDrive(pacer.MinSleep(minSleep))),
|
pacer: fs.NewPacer(ctx, pacer.NewAmazonCloudDrive(pacer.MinSleep(minSleep))),
|
||||||
noAuthClient: fshttp.NewClient(fs.Config),
|
noAuthClient: fshttp.NewClient(ctx),
|
||||||
}
|
}
|
||||||
f.features = (&fs.Features{
|
f.features = (&fs.Features{
|
||||||
CaseInsensitive: true,
|
CaseInsensitive: true,
|
||||||
ReadMimeType: true,
|
ReadMimeType: true,
|
||||||
CanHaveEmptyDirectories: true,
|
CanHaveEmptyDirectories: true,
|
||||||
}).Fill(f)
|
}).Fill(ctx, f)
|
||||||
|
|
||||||
// Renew the token in the background
|
// Renew the token in the background
|
||||||
f.tokenRenewer = oauthutil.NewRenew(f.String(), ts, func() error {
|
f.tokenRenewer = oauthutil.NewRenew(f.String(), ts, func() error {
|
||||||
@@ -386,7 +379,7 @@ func (f *Fs) FindLeaf(ctx context.Context, pathID, leaf string) (pathIDOut strin
|
|||||||
var resp *http.Response
|
var resp *http.Response
|
||||||
var subFolder *acd.Folder
|
var subFolder *acd.Folder
|
||||||
err = f.pacer.Call(func() (bool, error) {
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
subFolder, resp, err = folder.GetFolder(enc.FromStandardName(leaf))
|
subFolder, resp, err = folder.GetFolder(f.opt.Enc.FromStandardName(leaf))
|
||||||
return f.shouldRetry(resp, err)
|
return f.shouldRetry(resp, err)
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -413,7 +406,7 @@ func (f *Fs) CreateDir(ctx context.Context, pathID, leaf string) (newID string,
|
|||||||
var resp *http.Response
|
var resp *http.Response
|
||||||
var info *acd.Folder
|
var info *acd.Folder
|
||||||
err = f.pacer.Call(func() (bool, error) {
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
info, resp, err = folder.CreateFolder(enc.FromStandardName(leaf))
|
info, resp, err = folder.CreateFolder(f.opt.Enc.FromStandardName(leaf))
|
||||||
return f.shouldRetry(resp, err)
|
return f.shouldRetry(resp, err)
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -481,7 +474,7 @@ func (f *Fs) listAll(dirID string, title string, directoriesOnly bool, filesOnly
|
|||||||
if !hasValidParent {
|
if !hasValidParent {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
*node.Name = enc.ToStandardName(*node.Name)
|
*node.Name = f.opt.Enc.ToStandardName(*node.Name)
|
||||||
// Store the nodes up in case we have to retry the listing
|
// Store the nodes up in case we have to retry the listing
|
||||||
out = append(out, node)
|
out = append(out, node)
|
||||||
}
|
}
|
||||||
@@ -507,15 +500,11 @@ func (f *Fs) listAll(dirID string, title string, directoriesOnly bool, filesOnly
|
|||||||
// This should return ErrDirNotFound if the directory isn't
|
// This should return ErrDirNotFound if the directory isn't
|
||||||
// found.
|
// found.
|
||||||
func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) {
|
func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) {
|
||||||
err = f.dirCache.FindRoot(ctx, false)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
directoryID, err := f.dirCache.FindDir(ctx, dir, false)
|
directoryID, err := f.dirCache.FindDir(ctx, dir, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
maxTries := fs.Config.LowLevelRetries
|
maxTries := f.ci.LowLevelRetries
|
||||||
var iErr error
|
var iErr error
|
||||||
for tries := 1; tries <= maxTries; tries++ {
|
for tries := 1; tries <= maxTries; tries++ {
|
||||||
entries = nil
|
entries = nil
|
||||||
@@ -536,7 +525,7 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
|
|||||||
}
|
}
|
||||||
entries = append(entries, o)
|
entries = append(entries, o)
|
||||||
default:
|
default:
|
||||||
// ignore ASSET etc
|
// ignore ASSET, etc.
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
})
|
})
|
||||||
@@ -658,7 +647,7 @@ func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options .
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
// If not create it
|
// If not create it
|
||||||
leaf, directoryID, err := f.dirCache.FindRootAndPath(ctx, remote, true)
|
leaf, directoryID, err := f.dirCache.FindPath(ctx, remote, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -671,7 +660,7 @@ func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options .
|
|||||||
err = f.pacer.CallNoRetry(func() (bool, error) {
|
err = f.pacer.CallNoRetry(func() (bool, error) {
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
f.tokenRenewer.Start()
|
f.tokenRenewer.Start()
|
||||||
info, resp, err = folder.Put(in, enc.FromStandardName(leaf))
|
info, resp, err = folder.Put(in, f.opt.Enc.FromStandardName(leaf))
|
||||||
f.tokenRenewer.Stop()
|
f.tokenRenewer.Stop()
|
||||||
var ok bool
|
var ok bool
|
||||||
ok, info, err = f.checkUpload(ctx, resp, in, src, info, err, time.Since(start))
|
ok, info, err = f.checkUpload(ctx, resp, in, src, info, err, time.Since(start))
|
||||||
@@ -689,17 +678,11 @@ func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options .
|
|||||||
|
|
||||||
// Mkdir creates the container if it doesn't exist
|
// Mkdir creates the container if it doesn't exist
|
||||||
func (f *Fs) Mkdir(ctx context.Context, dir string) error {
|
func (f *Fs) Mkdir(ctx context.Context, dir string) error {
|
||||||
err := f.dirCache.FindRoot(ctx, true)
|
_, err := f.dirCache.FindDir(ctx, dir, true)
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if dir != "" {
|
|
||||||
_, err = f.dirCache.FindDir(ctx, dir, true)
|
|
||||||
}
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Move src to this remote using server side move operations.
|
// Move src to this remote using server-side move operations.
|
||||||
//
|
//
|
||||||
// This is stored with the remote path given
|
// This is stored with the remote path given
|
||||||
//
|
//
|
||||||
@@ -717,10 +700,6 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// create the destination directory if necessary
|
// create the destination directory if necessary
|
||||||
err := f.dirCache.FindRoot(ctx, true)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
srcLeaf, srcDirectoryID, err := srcObj.fs.dirCache.FindPath(ctx, srcObj.remote, false)
|
srcLeaf, srcDirectoryID, err := srcObj.fs.dirCache.FindPath(ctx, srcObj.remote, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -740,7 +719,7 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
dstObj fs.Object
|
dstObj fs.Object
|
||||||
srcErr, dstErr error
|
srcErr, dstErr error
|
||||||
)
|
)
|
||||||
for i := 1; i <= fs.Config.LowLevelRetries; i++ {
|
for i := 1; i <= f.ci.LowLevelRetries; i++ {
|
||||||
_, srcErr = srcObj.fs.NewObject(ctx, srcObj.remote) // try reading the object
|
_, srcErr = srcObj.fs.NewObject(ctx, srcObj.remote) // try reading the object
|
||||||
if srcErr != nil && srcErr != fs.ErrorObjectNotFound {
|
if srcErr != nil && srcErr != fs.ErrorObjectNotFound {
|
||||||
// exit if error on source
|
// exit if error on source
|
||||||
@@ -755,7 +734,7 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
// finished if src not found and dst found
|
// finished if src not found and dst found
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
fs.Debugf(src, "Wait for directory listing to update after move %d/%d", i, fs.Config.LowLevelRetries)
|
fs.Debugf(src, "Wait for directory listing to update after move %d/%d", i, f.ci.LowLevelRetries)
|
||||||
time.Sleep(1 * time.Second)
|
time.Sleep(1 * time.Second)
|
||||||
}
|
}
|
||||||
return dstObj, dstErr
|
return dstObj, dstErr
|
||||||
@@ -768,7 +747,7 @@ func (f *Fs) DirCacheFlush() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DirMove moves src, srcRemote to this remote at dstRemote
|
// DirMove moves src, srcRemote to this remote at dstRemote
|
||||||
// using server side move operations.
|
// using server-side move operations.
|
||||||
//
|
//
|
||||||
// Will only be called if src.Fs().Name() == f.Name()
|
// Will only be called if src.Fs().Name() == f.Name()
|
||||||
//
|
//
|
||||||
@@ -790,54 +769,24 @@ func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string
|
|||||||
return errors.New("can't move root directory")
|
return errors.New("can't move root directory")
|
||||||
}
|
}
|
||||||
|
|
||||||
// find the root src directory
|
|
||||||
err = srcFs.dirCache.FindRoot(ctx, false)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// find the root dst directory
|
|
||||||
if dstRemote != "" {
|
|
||||||
err = f.dirCache.FindRoot(ctx, true)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if f.dirCache.FoundRoot() {
|
|
||||||
return fs.ErrorDirExists
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Find ID of dst parent, creating subdirs if necessary
|
// Find ID of dst parent, creating subdirs if necessary
|
||||||
findPath := dstRemote
|
dstLeaf, dstDirectoryID, err := f.dirCache.FindPath(ctx, dstRemote, true)
|
||||||
if dstRemote == "" {
|
|
||||||
findPath = f.root
|
|
||||||
}
|
|
||||||
dstLeaf, dstDirectoryID, err := f.dirCache.FindPath(ctx, findPath, true)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check destination does not exist
|
// Check destination does not exist
|
||||||
if dstRemote != "" {
|
_, err = f.dirCache.FindDir(ctx, dstRemote, false)
|
||||||
_, err = f.dirCache.FindDir(ctx, dstRemote, false)
|
if err == fs.ErrorDirNotFound {
|
||||||
if err == fs.ErrorDirNotFound {
|
// OK
|
||||||
// OK
|
} else if err != nil {
|
||||||
} else if err != nil {
|
return err
|
||||||
return err
|
} else {
|
||||||
} else {
|
return fs.ErrorDirExists
|
||||||
return fs.ErrorDirExists
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find ID of src parent
|
// Find ID of src parent
|
||||||
findPath = srcRemote
|
_, srcDirectoryID, err := srcFs.dirCache.FindPath(ctx, srcRemote, false)
|
||||||
var srcDirectoryID string
|
|
||||||
if srcRemote == "" {
|
|
||||||
srcDirectoryID, err = srcFs.dirCache.RootParentID()
|
|
||||||
} else {
|
|
||||||
_, srcDirectoryID, err = srcFs.dirCache.FindPath(ctx, findPath, false)
|
|
||||||
}
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -883,10 +832,6 @@ func (f *Fs) purgeCheck(ctx context.Context, dir string, check bool) error {
|
|||||||
return errors.New("can't purge root directory")
|
return errors.New("can't purge root directory")
|
||||||
}
|
}
|
||||||
dc := f.dirCache
|
dc := f.dirCache
|
||||||
err := dc.FindRoot(ctx, false)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
rootID, err := dc.FindDir(ctx, dir, false)
|
rootID, err := dc.FindDir(ctx, dir, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -950,7 +895,7 @@ func (f *Fs) Hashes() hash.Set {
|
|||||||
return hash.Set(hash.MD5)
|
return hash.Set(hash.MD5)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Copy src to this remote using server side copy operations.
|
// Copy src to this remote using server-side copy operations.
|
||||||
//
|
//
|
||||||
// This is stored with the remote path given
|
// This is stored with the remote path given
|
||||||
//
|
//
|
||||||
@@ -978,8 +923,8 @@ func (f *Fs) Hashes() hash.Set {
|
|||||||
// Optional interface: Only implement this if you have a way of
|
// Optional interface: Only implement this if you have a way of
|
||||||
// deleting all the files quicker than just running Remove() on the
|
// deleting all the files quicker than just running Remove() on the
|
||||||
// result of List()
|
// result of List()
|
||||||
func (f *Fs) Purge(ctx context.Context) error {
|
func (f *Fs) Purge(ctx context.Context, dir string) error {
|
||||||
return f.purgeCheck(ctx, "", false)
|
return f.purgeCheck(ctx, dir, false)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------
|
// ------------------------------------------------------------
|
||||||
@@ -1030,7 +975,7 @@ func (o *Object) readMetaData(ctx context.Context) (err error) {
|
|||||||
if o.info != nil {
|
if o.info != nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
leaf, directoryID, err := o.fs.dirCache.FindRootAndPath(ctx, o.remote, false)
|
leaf, directoryID, err := o.fs.dirCache.FindPath(ctx, o.remote, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err == fs.ErrorDirNotFound {
|
if err == fs.ErrorDirNotFound {
|
||||||
return fs.ErrorObjectNotFound
|
return fs.ErrorObjectNotFound
|
||||||
@@ -1041,7 +986,7 @@ func (o *Object) readMetaData(ctx context.Context) (err error) {
|
|||||||
var resp *http.Response
|
var resp *http.Response
|
||||||
var info *acd.File
|
var info *acd.File
|
||||||
err = o.fs.pacer.Call(func() (bool, error) {
|
err = o.fs.pacer.Call(func() (bool, error) {
|
||||||
info, resp, err = folder.GetFile(enc.FromStandardName(leaf))
|
info, resp, err = folder.GetFile(o.fs.opt.Enc.FromStandardName(leaf))
|
||||||
return o.fs.shouldRetry(resp, err)
|
return o.fs.shouldRetry(resp, err)
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -1161,7 +1106,7 @@ func (f *Fs) restoreNode(info *acd.Node) (newInfo *acd.Node, err error) {
|
|||||||
func (f *Fs) renameNode(info *acd.Node, newName string) (newInfo *acd.Node, err error) {
|
func (f *Fs) renameNode(info *acd.Node, newName string) (newInfo *acd.Node, err error) {
|
||||||
var resp *http.Response
|
var resp *http.Response
|
||||||
err = f.pacer.Call(func() (bool, error) {
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
newInfo, resp, err = info.Rename(enc.FromStandardName(newName))
|
newInfo, resp, err = info.Rename(f.opt.Enc.FromStandardName(newName))
|
||||||
return f.shouldRetry(resp, err)
|
return f.shouldRetry(resp, err)
|
||||||
})
|
})
|
||||||
return newInfo, err
|
return newInfo, err
|
||||||
@@ -1357,7 +1302,7 @@ func (f *Fs) changeNotifyRunner(notifyFunc func(string, fs.EntryType), checkpoin
|
|||||||
if len(node.Parents) > 0 {
|
if len(node.Parents) > 0 {
|
||||||
if path, ok := f.dirCache.GetInv(node.Parents[0]); ok {
|
if path, ok := f.dirCache.GetInv(node.Parents[0]); ok {
|
||||||
// and append the drive file name to compute the full file name
|
// and append the drive file name to compute the full file name
|
||||||
name := enc.ToStandardName(*node.Name)
|
name := f.opt.Enc.ToStandardName(*node.Name)
|
||||||
if len(path) > 0 {
|
if len(path) > 0 {
|
||||||
path = path + "/" + name
|
path = path + "/" + name
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
+433
-271
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,4 @@
|
|||||||
// +build !plan9,!solaris
|
// +build !plan9,!solaris,!js,go1.14
|
||||||
|
|
||||||
package azureblob
|
package azureblob
|
||||||
|
|
||||||
@@ -16,3 +16,20 @@ func (f *Fs) InternalTest(t *testing.T) {
|
|||||||
enabled = f.Features().GetTier
|
enabled = f.Features().GetTier
|
||||||
assert.True(t, enabled)
|
assert.True(t, enabled)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestIncrement(t *testing.T) {
|
||||||
|
for _, test := range []struct {
|
||||||
|
in []byte
|
||||||
|
want []byte
|
||||||
|
}{
|
||||||
|
{[]byte{0, 0, 0, 0}, []byte{1, 0, 0, 0}},
|
||||||
|
{[]byte{0xFE, 0, 0, 0}, []byte{0xFF, 0, 0, 0}},
|
||||||
|
{[]byte{0xFF, 0, 0, 0}, []byte{0, 1, 0, 0}},
|
||||||
|
{[]byte{0, 1, 0, 0}, []byte{1, 1, 0, 0}},
|
||||||
|
{[]byte{0xFF, 0xFF, 0xFF, 0xFE}, []byte{0, 0, 0, 0xFF}},
|
||||||
|
{[]byte{0xFF, 0xFF, 0xFF, 0xFF}, []byte{0, 0, 0, 0}},
|
||||||
|
} {
|
||||||
|
increment(test.in)
|
||||||
|
assert.Equal(t, test.want, test.in)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,14 +1,16 @@
|
|||||||
// Test AzureBlob filesystem interface
|
// Test AzureBlob filesystem interface
|
||||||
|
|
||||||
// +build !plan9,!solaris
|
// +build !plan9,!solaris,!js,go1.14
|
||||||
|
|
||||||
package azureblob
|
package azureblob
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/rclone/rclone/fs"
|
"github.com/rclone/rclone/fs"
|
||||||
"github.com/rclone/rclone/fstest/fstests"
|
"github.com/rclone/rclone/fstest/fstests"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TestIntegration runs integration tests against the remote
|
// TestIntegration runs integration tests against the remote
|
||||||
@@ -27,11 +29,36 @@ func (f *Fs) SetUploadChunkSize(cs fs.SizeSuffix) (fs.SizeSuffix, error) {
|
|||||||
return f.setUploadChunkSize(cs)
|
return f.setUploadChunkSize(cs)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fs) SetUploadCutoff(cs fs.SizeSuffix) (fs.SizeSuffix, error) {
|
|
||||||
return f.setUploadCutoff(cs)
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
var (
|
||||||
_ fstests.SetUploadChunkSizer = (*Fs)(nil)
|
_ fstests.SetUploadChunkSizer = (*Fs)(nil)
|
||||||
_ fstests.SetUploadCutoffer = (*Fs)(nil)
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// TestServicePrincipalFileSuccess checks that, given a proper JSON file, we can create a token.
|
||||||
|
func TestServicePrincipalFileSuccess(t *testing.T) {
|
||||||
|
ctx := context.TODO()
|
||||||
|
credentials := `
|
||||||
|
{
|
||||||
|
"appId": "my application (client) ID",
|
||||||
|
"password": "my secret",
|
||||||
|
"tenant": "my active directory tenant ID"
|
||||||
|
}
|
||||||
|
`
|
||||||
|
tokenRefresher, err := newServicePrincipalTokenRefresher(ctx, []byte(credentials))
|
||||||
|
if assert.NoError(t, err) {
|
||||||
|
assert.NotNil(t, tokenRefresher)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestServicePrincipalFileFailure checks that, given a JSON file with a missing secret, it returns an error.
|
||||||
|
func TestServicePrincipalFileFailure(t *testing.T) {
|
||||||
|
ctx := context.TODO()
|
||||||
|
credentials := `
|
||||||
|
{
|
||||||
|
"appId": "my application (client) ID",
|
||||||
|
"tenant": "my active directory tenant ID"
|
||||||
|
}
|
||||||
|
`
|
||||||
|
_, err := newServicePrincipalTokenRefresher(ctx, []byte(credentials))
|
||||||
|
assert.Error(t, err)
|
||||||
|
assert.EqualError(t, err, "error creating service principal token: parameter 'secret' cannot be empty")
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
// Build for azureblob for unsupported platforms to stop go complaining
|
// Build for azureblob for unsupported platforms to stop go complaining
|
||||||
// about "no buildable Go source files "
|
// about "no buildable Go source files "
|
||||||
|
|
||||||
// +build plan9 solaris
|
// +build plan9 solaris js !go1.14
|
||||||
|
|
||||||
package azureblob
|
package azureblob
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
// +build !plan9,!solaris,!js,go1.14
|
||||||
|
|
||||||
|
package azureblob
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"io/ioutil"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/Azure/go-autorest/autorest/adal"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"github.com/rclone/rclone/fs"
|
||||||
|
"github.com/rclone/rclone/fs/fshttp"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
azureResource = "https://storage.azure.com"
|
||||||
|
imdsAPIVersion = "2018-02-01"
|
||||||
|
msiEndpointDefault = "http://169.254.169.254/metadata/identity/oauth2/token"
|
||||||
|
)
|
||||||
|
|
||||||
|
// This custom type is used to add the port the test server has bound to
|
||||||
|
// to the request context.
|
||||||
|
type testPortKey string
|
||||||
|
|
||||||
|
type msiIdentifierType int
|
||||||
|
|
||||||
|
const (
|
||||||
|
msiClientID msiIdentifierType = iota
|
||||||
|
msiObjectID
|
||||||
|
msiResourceID
|
||||||
|
)
|
||||||
|
|
||||||
|
type userMSI struct {
|
||||||
|
Type msiIdentifierType
|
||||||
|
Value string
|
||||||
|
}
|
||||||
|
|
||||||
|
type httpError struct {
|
||||||
|
Response *http.Response
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e httpError) Error() string {
|
||||||
|
return fmt.Sprintf("HTTP error %v (%v)", e.Response.StatusCode, e.Response.Status)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetMSIToken attempts to obtain an MSI token from the Azure Instance
|
||||||
|
// Metadata Service.
|
||||||
|
func GetMSIToken(ctx context.Context, identity *userMSI) (adal.Token, error) {
|
||||||
|
// Attempt to get an MSI token; silently continue if unsuccessful.
|
||||||
|
// This code has been lovingly stolen from azcopy's OAuthTokenManager.
|
||||||
|
result := adal.Token{}
|
||||||
|
req, err := http.NewRequestWithContext(ctx, "GET", msiEndpointDefault, nil)
|
||||||
|
if err != nil {
|
||||||
|
fs.Debugf(nil, "Failed to create request: %v", err)
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
params := req.URL.Query()
|
||||||
|
params.Set("resource", azureResource)
|
||||||
|
params.Set("api-version", imdsAPIVersion)
|
||||||
|
|
||||||
|
// Specify user-assigned identity if requested.
|
||||||
|
if identity != nil {
|
||||||
|
switch identity.Type {
|
||||||
|
case msiClientID:
|
||||||
|
params.Set("client_id", identity.Value)
|
||||||
|
case msiObjectID:
|
||||||
|
params.Set("object_id", identity.Value)
|
||||||
|
case msiResourceID:
|
||||||
|
params.Set("mi_res_id", identity.Value)
|
||||||
|
default:
|
||||||
|
// If this happens, the calling function and this one don't agree on
|
||||||
|
// what valid ID types exist.
|
||||||
|
return result, fmt.Errorf("unknown MSI identity type specified")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
req.URL.RawQuery = params.Encode()
|
||||||
|
|
||||||
|
// The Metadata header is required by all calls to IMDS.
|
||||||
|
req.Header.Set("Metadata", "true")
|
||||||
|
|
||||||
|
// If this function is run in a test, query the test server instead of IMDS.
|
||||||
|
testPort, isTest := ctx.Value(testPortKey("testPort")).(int)
|
||||||
|
if isTest {
|
||||||
|
req.URL.Host = fmt.Sprintf("localhost:%d", testPort)
|
||||||
|
req.Host = req.URL.Host
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send request
|
||||||
|
httpClient := fshttp.NewClient(ctx)
|
||||||
|
resp, err := httpClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return result, errors.Wrap(err, "MSI is not enabled on this VM")
|
||||||
|
}
|
||||||
|
defer func() { // resp and Body should not be nil
|
||||||
|
_, err = io.Copy(ioutil.Discard, resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
fs.Debugf(nil, "Unable to drain IMDS response: %v", err)
|
||||||
|
}
|
||||||
|
err = resp.Body.Close()
|
||||||
|
if err != nil {
|
||||||
|
fs.Debugf(nil, "Unable to close IMDS response: %v", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
// Check if the status code indicates success
|
||||||
|
// The request returns 200 currently, add 201 and 202 as well for possible extension.
|
||||||
|
switch resp.StatusCode {
|
||||||
|
case 200, 201, 202:
|
||||||
|
break
|
||||||
|
default:
|
||||||
|
body, _ := ioutil.ReadAll(resp.Body)
|
||||||
|
fs.Errorf(nil, "Couldn't obtain OAuth token from IMDS; server returned status code %d and body: %v", resp.StatusCode, string(body))
|
||||||
|
return result, httpError{Response: resp}
|
||||||
|
}
|
||||||
|
|
||||||
|
b, err := ioutil.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return result, errors.Wrap(err, "Couldn't read IMDS response")
|
||||||
|
}
|
||||||
|
// Remove BOM, if any. azcopy does this so I'm following along.
|
||||||
|
b = bytes.TrimPrefix(b, []byte("\xef\xbb\xbf"))
|
||||||
|
|
||||||
|
// This would be a good place to persist the token if a large number of rclone
|
||||||
|
// invocations are being made in a short amount of time. If the token is
|
||||||
|
// persisted, the azureblob code will need to check for expiry before every
|
||||||
|
// storage API call.
|
||||||
|
err = json.Unmarshal(b, &result)
|
||||||
|
if err != nil {
|
||||||
|
return result, errors.Wrap(err, "Couldn't unmarshal IMDS response")
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
// +build !plan9,!solaris,!js,go1.14
|
||||||
|
|
||||||
|
package azureblob
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/Azure/go-autorest/autorest/adal"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func handler(t *testing.T, actual *map[string]string) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
err := r.ParseForm()
|
||||||
|
require.NoError(t, err)
|
||||||
|
parameters := r.URL.Query()
|
||||||
|
(*actual)["path"] = r.URL.Path
|
||||||
|
(*actual)["Metadata"] = r.Header.Get("Metadata")
|
||||||
|
(*actual)["method"] = r.Method
|
||||||
|
for paramName := range parameters {
|
||||||
|
(*actual)[paramName] = parameters.Get(paramName)
|
||||||
|
}
|
||||||
|
// Make response.
|
||||||
|
response := adal.Token{}
|
||||||
|
responseBytes, err := json.Marshal(response)
|
||||||
|
require.NoError(t, err)
|
||||||
|
_, err = w.Write(responseBytes)
|
||||||
|
require.NoError(t, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestManagedIdentity(t *testing.T) {
|
||||||
|
// test user-assigned identity specifiers to use
|
||||||
|
testMSIClientID := "d859b29f-5c9c-42f8-a327-ec1bc6408d79"
|
||||||
|
testMSIObjectID := "9ffeb650-3ca0-4278-962b-5a38d520591a"
|
||||||
|
testMSIResourceID := "/subscriptions/fe714c49-b8a4-4d49-9388-96a20daa318f/resourceGroups/somerg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/someidentity"
|
||||||
|
tests := []struct {
|
||||||
|
identity *userMSI
|
||||||
|
identityParameterName string
|
||||||
|
expectedAbsent []string
|
||||||
|
}{
|
||||||
|
{&userMSI{msiClientID, testMSIClientID}, "client_id", []string{"object_id", "mi_res_id"}},
|
||||||
|
{&userMSI{msiObjectID, testMSIObjectID}, "object_id", []string{"client_id", "mi_res_id"}},
|
||||||
|
{&userMSI{msiResourceID, testMSIResourceID}, "mi_res_id", []string{"object_id", "client_id"}},
|
||||||
|
{nil, "(default)", []string{"object_id", "client_id", "mi_res_id"}},
|
||||||
|
}
|
||||||
|
alwaysExpected := map[string]string{
|
||||||
|
"path": "/metadata/identity/oauth2/token",
|
||||||
|
"resource": "https://storage.azure.com",
|
||||||
|
"Metadata": "true",
|
||||||
|
"api-version": "2018-02-01",
|
||||||
|
"method": "GET",
|
||||||
|
}
|
||||||
|
for _, test := range tests {
|
||||||
|
actual := make(map[string]string, 10)
|
||||||
|
testServer := httptest.NewServer(handler(t, &actual))
|
||||||
|
defer testServer.Close()
|
||||||
|
testServerPort, err := strconv.Atoi(strings.Split(testServer.URL, ":")[2])
|
||||||
|
require.NoError(t, err)
|
||||||
|
ctx := context.WithValue(context.TODO(), testPortKey("testPort"), testServerPort)
|
||||||
|
_, err = GetMSIToken(ctx, test.identity)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
// Validate expected query parameters present
|
||||||
|
expected := make(map[string]string)
|
||||||
|
for k, v := range alwaysExpected {
|
||||||
|
expected[k] = v
|
||||||
|
}
|
||||||
|
if test.identity != nil {
|
||||||
|
expected[test.identityParameterName] = test.identity.Value
|
||||||
|
}
|
||||||
|
|
||||||
|
for key := range expected {
|
||||||
|
value, exists := actual[key]
|
||||||
|
if assert.Truef(t, exists, "test of %s: query parameter %s was not passed",
|
||||||
|
test.identityParameterName, key) {
|
||||||
|
assert.Equalf(t, expected[key], value,
|
||||||
|
"test of %s: parameter %s has incorrect value", test.identityParameterName, key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate unexpected query parameters absent
|
||||||
|
for _, key := range test.expectedAbsent {
|
||||||
|
_, exists := actual[key]
|
||||||
|
assert.Falsef(t, exists, "query parameter %s was unexpectedly passed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func errorHandler(resultCode int) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
http.Error(w, "Test error generated", resultCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIMDSErrors(t *testing.T) {
|
||||||
|
errorCodes := []int{404, 429, 500}
|
||||||
|
for _, code := range errorCodes {
|
||||||
|
testServer := httptest.NewServer(errorHandler(code))
|
||||||
|
defer testServer.Close()
|
||||||
|
testServerPort, err := strconv.Atoi(strings.Split(testServer.URL, ":")[2])
|
||||||
|
require.NoError(t, err)
|
||||||
|
ctx := context.WithValue(context.TODO(), testPortKey("testPort"), testServerPort)
|
||||||
|
_, err = GetMSIToken(ctx, nil)
|
||||||
|
require.Error(t, err)
|
||||||
|
httpErr, ok := err.(httpError)
|
||||||
|
require.Truef(t, ok, "HTTP error %d did not result in an httpError object", code)
|
||||||
|
assert.Equalf(t, httpErr.Response.StatusCode, code, "desired error %d but didn't get it", code)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -337,3 +337,11 @@ type CopyFileRequest struct {
|
|||||||
Info map[string]string `json:"fileInfo,omitempty"` // This field stores the metadata that will be stored with the file. (REPLACE only)
|
Info map[string]string `json:"fileInfo,omitempty"` // This field stores the metadata that will be stored with the file. (REPLACE only)
|
||||||
DestBucketID string `json:"destinationBucketId,omitempty"` // The destination ID of the bucket if set, if not the source bucket will be used
|
DestBucketID string `json:"destinationBucketId,omitempty"` // The destination ID of the bucket if set, if not the source bucket will be used
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CopyPartRequest is the request for b2_copy_part - the response is UploadPartResponse
|
||||||
|
type CopyPartRequest struct {
|
||||||
|
SourceID string `json:"sourceFileId"` // The ID of the source file being copied.
|
||||||
|
LargeFileID string `json:"largeFileId"` // The ID of the large file the part will belong to, as returned by b2_start_large_file.
|
||||||
|
PartNumber int64 `json:"partNumber"` // Which part this is (starting from 1)
|
||||||
|
Range string `json:"range,omitempty"` // The range of bytes to copy. If not provided, the whole source file will be copied.
|
||||||
|
}
|
||||||
+290
-163
@@ -23,20 +23,20 @@ import (
|
|||||||
"github.com/rclone/rclone/backend/b2/api"
|
"github.com/rclone/rclone/backend/b2/api"
|
||||||
"github.com/rclone/rclone/fs"
|
"github.com/rclone/rclone/fs"
|
||||||
"github.com/rclone/rclone/fs/accounting"
|
"github.com/rclone/rclone/fs/accounting"
|
||||||
|
"github.com/rclone/rclone/fs/config"
|
||||||
"github.com/rclone/rclone/fs/config/configmap"
|
"github.com/rclone/rclone/fs/config/configmap"
|
||||||
"github.com/rclone/rclone/fs/config/configstruct"
|
"github.com/rclone/rclone/fs/config/configstruct"
|
||||||
"github.com/rclone/rclone/fs/encodings"
|
|
||||||
"github.com/rclone/rclone/fs/fserrors"
|
"github.com/rclone/rclone/fs/fserrors"
|
||||||
"github.com/rclone/rclone/fs/fshttp"
|
"github.com/rclone/rclone/fs/fshttp"
|
||||||
"github.com/rclone/rclone/fs/hash"
|
"github.com/rclone/rclone/fs/hash"
|
||||||
"github.com/rclone/rclone/fs/walk"
|
"github.com/rclone/rclone/fs/walk"
|
||||||
"github.com/rclone/rclone/lib/bucket"
|
"github.com/rclone/rclone/lib/bucket"
|
||||||
|
"github.com/rclone/rclone/lib/encoder"
|
||||||
"github.com/rclone/rclone/lib/pacer"
|
"github.com/rclone/rclone/lib/pacer"
|
||||||
|
"github.com/rclone/rclone/lib/pool"
|
||||||
"github.com/rclone/rclone/lib/rest"
|
"github.com/rclone/rclone/lib/rest"
|
||||||
)
|
)
|
||||||
|
|
||||||
const enc = encodings.B2
|
|
||||||
|
|
||||||
const (
|
const (
|
||||||
defaultEndpoint = "https://api.backblazeb2.com"
|
defaultEndpoint = "https://api.backblazeb2.com"
|
||||||
headerPrefix = "x-bz-info-" // lower case as that is what the server returns
|
headerPrefix = "x-bz-info-" // lower case as that is what the server returns
|
||||||
@@ -44,8 +44,10 @@ const (
|
|||||||
timeHeader = headerPrefix + timeKey
|
timeHeader = headerPrefix + timeKey
|
||||||
sha1Key = "large_file_sha1"
|
sha1Key = "large_file_sha1"
|
||||||
sha1Header = "X-Bz-Content-Sha1"
|
sha1Header = "X-Bz-Content-Sha1"
|
||||||
sha1InfoHeader = headerPrefix + sha1Key
|
|
||||||
testModeHeader = "X-Bz-Test-Mode"
|
testModeHeader = "X-Bz-Test-Mode"
|
||||||
|
idHeader = "X-Bz-File-Id"
|
||||||
|
nameHeader = "X-Bz-File-Name"
|
||||||
|
timestampHeader = "X-Bz-Upload-Timestamp"
|
||||||
retryAfterHeader = "Retry-After"
|
retryAfterHeader = "Retry-After"
|
||||||
minSleep = 10 * time.Millisecond
|
minSleep = 10 * time.Millisecond
|
||||||
maxSleep = 5 * time.Minute
|
maxSleep = 5 * time.Minute
|
||||||
@@ -55,6 +57,9 @@ const (
|
|||||||
minChunkSize = 5 * fs.MebiByte
|
minChunkSize = 5 * fs.MebiByte
|
||||||
defaultChunkSize = 96 * fs.MebiByte
|
defaultChunkSize = 96 * fs.MebiByte
|
||||||
defaultUploadCutoff = 200 * fs.MebiByte
|
defaultUploadCutoff = 200 * fs.MebiByte
|
||||||
|
largeFileCopyCutoff = 4 * fs.GibiByte // 5E9 is the max
|
||||||
|
memoryPoolFlushTime = fs.Duration(time.Minute) // flush the cached buffers after this long
|
||||||
|
memoryPoolUseMmap = false
|
||||||
)
|
)
|
||||||
|
|
||||||
// Globals
|
// Globals
|
||||||
@@ -114,6 +119,16 @@ Files above this size will be uploaded in chunks of "--b2-chunk-size".
|
|||||||
This value should be set no larger than 4.657GiB (== 5GB).`,
|
This value should be set no larger than 4.657GiB (== 5GB).`,
|
||||||
Default: defaultUploadCutoff,
|
Default: defaultUploadCutoff,
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: "copy_cutoff",
|
||||||
|
Help: `Cutoff for switching to multipart copy
|
||||||
|
|
||||||
|
Any files larger than this that need to be server-side copied will be
|
||||||
|
copied in chunks of this size.
|
||||||
|
|
||||||
|
The minimum is 0 and the maximum is 4.6GB.`,
|
||||||
|
Default: largeFileCopyCutoff,
|
||||||
|
Advanced: true,
|
||||||
}, {
|
}, {
|
||||||
Name: "chunk_size",
|
Name: "chunk_size",
|
||||||
Help: `Upload chunk size. Must fit in memory.
|
Help: `Upload chunk size. Must fit in memory.
|
||||||
@@ -125,8 +140,13 @@ minimum size.`,
|
|||||||
Default: defaultChunkSize,
|
Default: defaultChunkSize,
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
}, {
|
}, {
|
||||||
Name: "disable_checksum",
|
Name: "disable_checksum",
|
||||||
Help: `Disable checksums for large (> upload cutoff) files`,
|
Help: `Disable checksums for large (> upload cutoff) files
|
||||||
|
|
||||||
|
Normally rclone will calculate the SHA1 checksum of the input before
|
||||||
|
uploading it so it can add it to metadata on the object. This is great
|
||||||
|
for data integrity checking but can cause long delays for large files
|
||||||
|
to start uploading.`,
|
||||||
Default: false,
|
Default: false,
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
}, {
|
}, {
|
||||||
@@ -135,7 +155,9 @@ minimum size.`,
|
|||||||
|
|
||||||
This is usually set to a Cloudflare CDN URL as Backblaze offers
|
This is usually set to a Cloudflare CDN URL as Backblaze offers
|
||||||
free egress for data downloaded through the Cloudflare network.
|
free egress for data downloaded through the Cloudflare network.
|
||||||
This is probably only useful for a public bucket.
|
Rclone works with private buckets by sending an "Authorization" header.
|
||||||
|
If the custom endpoint rewrites the requests for authentication,
|
||||||
|
e.g., in Cloudflare Workers, this header needs to be handled properly.
|
||||||
Leave blank if you want to use the endpoint provided by Backblaze.`,
|
Leave blank if you want to use the endpoint provided by Backblaze.`,
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
}, {
|
}, {
|
||||||
@@ -146,23 +168,49 @@ The duration before the download authorization token will expire.
|
|||||||
The minimum value is 1 second. The maximum value is one week.`,
|
The minimum value is 1 second. The maximum value is one week.`,
|
||||||
Default: fs.Duration(7 * 24 * time.Hour),
|
Default: fs.Duration(7 * 24 * time.Hour),
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: "memory_pool_flush_time",
|
||||||
|
Default: memoryPoolFlushTime,
|
||||||
|
Advanced: true,
|
||||||
|
Help: `How often internal memory buffer pools will be flushed.
|
||||||
|
Uploads which requires additional buffers (f.e multipart) will use memory pool for allocations.
|
||||||
|
This option controls how often unused buffers will be removed from the pool.`,
|
||||||
|
}, {
|
||||||
|
Name: "memory_pool_use_mmap",
|
||||||
|
Default: memoryPoolUseMmap,
|
||||||
|
Advanced: true,
|
||||||
|
Help: `Whether to use mmap buffers in internal memory pool.`,
|
||||||
|
}, {
|
||||||
|
Name: config.ConfigEncoding,
|
||||||
|
Help: config.ConfigEncodingHelp,
|
||||||
|
Advanced: true,
|
||||||
|
// See: https://www.backblaze.com/b2/docs/files.html
|
||||||
|
// Encode invalid UTF-8 bytes as json doesn't handle them properly.
|
||||||
|
// FIXME: allow /, but not leading, trailing or double
|
||||||
|
Default: (encoder.Display |
|
||||||
|
encoder.EncodeBackSlash |
|
||||||
|
encoder.EncodeInvalidUtf8),
|
||||||
}},
|
}},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Options defines the configuration for this backend
|
// Options defines the configuration for this backend
|
||||||
type Options struct {
|
type Options struct {
|
||||||
Account string `config:"account"`
|
Account string `config:"account"`
|
||||||
Key string `config:"key"`
|
Key string `config:"key"`
|
||||||
Endpoint string `config:"endpoint"`
|
Endpoint string `config:"endpoint"`
|
||||||
TestMode string `config:"test_mode"`
|
TestMode string `config:"test_mode"`
|
||||||
Versions bool `config:"versions"`
|
Versions bool `config:"versions"`
|
||||||
HardDelete bool `config:"hard_delete"`
|
HardDelete bool `config:"hard_delete"`
|
||||||
UploadCutoff fs.SizeSuffix `config:"upload_cutoff"`
|
UploadCutoff fs.SizeSuffix `config:"upload_cutoff"`
|
||||||
ChunkSize fs.SizeSuffix `config:"chunk_size"`
|
CopyCutoff fs.SizeSuffix `config:"copy_cutoff"`
|
||||||
DisableCheckSum bool `config:"disable_checksum"`
|
ChunkSize fs.SizeSuffix `config:"chunk_size"`
|
||||||
DownloadURL string `config:"download_url"`
|
DisableCheckSum bool `config:"disable_checksum"`
|
||||||
DownloadAuthorizationDuration fs.Duration `config:"download_auth_duration"`
|
DownloadURL string `config:"download_url"`
|
||||||
|
DownloadAuthorizationDuration fs.Duration `config:"download_auth_duration"`
|
||||||
|
MemoryPoolFlushTime fs.Duration `config:"memory_pool_flush_time"`
|
||||||
|
MemoryPoolUseMmap bool `config:"memory_pool_use_mmap"`
|
||||||
|
Enc encoder.MultiEncoder `config:"encoding"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fs represents a remote b2 server
|
// Fs represents a remote b2 server
|
||||||
@@ -170,6 +218,7 @@ type Fs struct {
|
|||||||
name string // name of this remote
|
name string // name of this remote
|
||||||
root string // the path we are working on if any
|
root string // the path we are working on if any
|
||||||
opt Options // parsed config options
|
opt Options // parsed config options
|
||||||
|
ci *fs.ConfigInfo // global config
|
||||||
features *fs.Features // optional features
|
features *fs.Features // optional features
|
||||||
srv *rest.Client // the connection to the b2 server
|
srv *rest.Client // the connection to the b2 server
|
||||||
rootBucket string // bucket part of root (if any)
|
rootBucket string // bucket part of root (if any)
|
||||||
@@ -184,7 +233,8 @@ type Fs struct {
|
|||||||
uploads map[string][]*api.GetUploadURLResponse // Upload URLs by buckedID
|
uploads map[string][]*api.GetUploadURLResponse // Upload URLs by buckedID
|
||||||
authMu sync.Mutex // lock for authorizing the account
|
authMu sync.Mutex // lock for authorizing the account
|
||||||
pacer *fs.Pacer // To pace and retry the API calls
|
pacer *fs.Pacer // To pace and retry the API calls
|
||||||
bufferTokens chan []byte // control concurrency of multipart uploads
|
uploadToken *pacer.TokenDispenser // control concurrency
|
||||||
|
pool *pool.Pool // memory pool
|
||||||
}
|
}
|
||||||
|
|
||||||
// Object describes a b2 object
|
// Object describes a b2 object
|
||||||
@@ -245,7 +295,7 @@ func (o *Object) split() (bucket, bucketPath string) {
|
|||||||
|
|
||||||
// retryErrorCodes is a slice of error codes that we will retry
|
// retryErrorCodes is a slice of error codes that we will retry
|
||||||
var retryErrorCodes = []int{
|
var retryErrorCodes = []int{
|
||||||
401, // Unauthorized (eg "Token has expired")
|
401, // Unauthorized (e.g. "Token has expired")
|
||||||
408, // Request Timeout
|
408, // Request Timeout
|
||||||
429, // Rate exceeded.
|
429, // Rate exceeded.
|
||||||
500, // Get occasional 500 Internal Server Error
|
500, // Get occasional 500 Internal Server Error
|
||||||
@@ -320,7 +370,6 @@ func (f *Fs) setUploadChunkSize(cs fs.SizeSuffix) (old fs.SizeSuffix, err error)
|
|||||||
err = checkUploadChunkSize(cs)
|
err = checkUploadChunkSize(cs)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
old, f.opt.ChunkSize = f.opt.ChunkSize, cs
|
old, f.opt.ChunkSize = f.opt.ChunkSize, cs
|
||||||
f.fillBufferTokens() // reset the buffer tokens
|
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -347,14 +396,17 @@ func (f *Fs) setRoot(root string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// NewFs constructs an Fs from the path, bucket:path
|
// NewFs constructs an Fs from the path, bucket:path
|
||||||
func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {
|
||||||
ctx := context.Background()
|
|
||||||
// Parse config into Options struct
|
// Parse config into Options struct
|
||||||
opt := new(Options)
|
opt := new(Options)
|
||||||
err := configstruct.Set(m, opt)
|
err := configstruct.Set(m, opt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if opt.UploadCutoff < opt.ChunkSize {
|
||||||
|
opt.UploadCutoff = opt.ChunkSize
|
||||||
|
fs.Infof(nil, "b2: raising upload cutoff to chunk size: %v", opt.UploadCutoff)
|
||||||
|
}
|
||||||
err = checkUploadCutoff(opt, opt.UploadCutoff)
|
err = checkUploadCutoff(opt, opt.UploadCutoff)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "b2: upload cutoff")
|
return nil, errors.Wrap(err, "b2: upload cutoff")
|
||||||
@@ -372,15 +424,24 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
if opt.Endpoint == "" {
|
if opt.Endpoint == "" {
|
||||||
opt.Endpoint = defaultEndpoint
|
opt.Endpoint = defaultEndpoint
|
||||||
}
|
}
|
||||||
|
ci := fs.GetConfig(ctx)
|
||||||
f := &Fs{
|
f := &Fs{
|
||||||
name: name,
|
name: name,
|
||||||
opt: *opt,
|
opt: *opt,
|
||||||
srv: rest.NewClient(fshttp.NewClient(fs.Config)).SetErrorHandler(errorHandler),
|
ci: ci,
|
||||||
|
srv: rest.NewClient(fshttp.NewClient(ctx)).SetErrorHandler(errorHandler),
|
||||||
cache: bucket.NewCache(),
|
cache: bucket.NewCache(),
|
||||||
_bucketID: make(map[string]string, 1),
|
_bucketID: make(map[string]string, 1),
|
||||||
_bucketType: make(map[string]string, 1),
|
_bucketType: make(map[string]string, 1),
|
||||||
uploads: make(map[string][]*api.GetUploadURLResponse),
|
uploads: make(map[string][]*api.GetUploadURLResponse),
|
||||||
pacer: fs.NewPacer(pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
|
pacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
|
||||||
|
uploadToken: pacer.NewTokenDispenser(ci.Transfers),
|
||||||
|
pool: pool.New(
|
||||||
|
time.Duration(opt.MemoryPoolFlushTime),
|
||||||
|
int(opt.ChunkSize),
|
||||||
|
ci.Transfers,
|
||||||
|
opt.MemoryPoolUseMmap,
|
||||||
|
),
|
||||||
}
|
}
|
||||||
f.setRoot(root)
|
f.setRoot(root)
|
||||||
f.features = (&fs.Features{
|
f.features = (&fs.Features{
|
||||||
@@ -388,21 +449,20 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
WriteMimeType: true,
|
WriteMimeType: true,
|
||||||
BucketBased: true,
|
BucketBased: true,
|
||||||
BucketBasedRootOK: true,
|
BucketBasedRootOK: true,
|
||||||
}).Fill(f)
|
}).Fill(ctx, f)
|
||||||
// Set the test flag if required
|
// Set the test flag if required
|
||||||
if opt.TestMode != "" {
|
if opt.TestMode != "" {
|
||||||
testMode := strings.TrimSpace(opt.TestMode)
|
testMode := strings.TrimSpace(opt.TestMode)
|
||||||
f.srv.SetHeader(testModeHeader, testMode)
|
f.srv.SetHeader(testModeHeader, testMode)
|
||||||
fs.Debugf(f, "Setting test header \"%s: %s\"", testModeHeader, testMode)
|
fs.Debugf(f, "Setting test header \"%s: %s\"", testModeHeader, testMode)
|
||||||
}
|
}
|
||||||
f.fillBufferTokens()
|
|
||||||
err = f.authorizeAccount(ctx)
|
err = f.authorizeAccount(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "failed to authorize account")
|
return nil, errors.Wrap(err, "failed to authorize account")
|
||||||
}
|
}
|
||||||
// If this is a key limited to a single bucket, it must exist already
|
// If this is a key limited to a single bucket, it must exist already
|
||||||
if f.rootBucket != "" && f.info.Allowed.BucketID != "" {
|
if f.rootBucket != "" && f.info.Allowed.BucketID != "" {
|
||||||
allowedBucket := enc.ToStandardName(f.info.Allowed.BucketName)
|
allowedBucket := f.opt.Enc.ToStandardName(f.info.Allowed.BucketName)
|
||||||
if allowedBucket == "" {
|
if allowedBucket == "" {
|
||||||
return nil, errors.New("bucket that application key is restricted to no longer exists")
|
return nil, errors.New("bucket that application key is restricted to no longer exists")
|
||||||
}
|
}
|
||||||
@@ -518,32 +578,25 @@ func (f *Fs) clearUploadURL(bucketID string) {
|
|||||||
f.uploadMu.Unlock()
|
f.uploadMu.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fill up (or reset) the buffer tokens
|
// getBuf gets a buffer of f.opt.ChunkSize and an upload token
|
||||||
func (f *Fs) fillBufferTokens() {
|
//
|
||||||
f.bufferTokens = make(chan []byte, fs.Config.Transfers)
|
// If noBuf is set then it just gets an upload token
|
||||||
for i := 0; i < fs.Config.Transfers; i++ {
|
func (f *Fs) getBuf(noBuf bool) (buf []byte) {
|
||||||
f.bufferTokens <- nil
|
f.uploadToken.Get()
|
||||||
|
if !noBuf {
|
||||||
|
buf = f.pool.Get()
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// getUploadBlock gets a block from the pool of size chunkSize
|
|
||||||
func (f *Fs) getUploadBlock() []byte {
|
|
||||||
buf := <-f.bufferTokens
|
|
||||||
if buf == nil {
|
|
||||||
buf = make([]byte, f.opt.ChunkSize)
|
|
||||||
}
|
|
||||||
// fs.Debugf(f, "Getting upload block %p", buf)
|
|
||||||
return buf
|
return buf
|
||||||
}
|
}
|
||||||
|
|
||||||
// putUploadBlock returns a block to the pool of size chunkSize
|
// putBuf returns a buffer to the memory pool and an upload token
|
||||||
func (f *Fs) putUploadBlock(buf []byte) {
|
//
|
||||||
buf = buf[:cap(buf)]
|
// If noBuf is set then it just returns the upload token
|
||||||
if len(buf) != int(f.opt.ChunkSize) {
|
func (f *Fs) putBuf(buf []byte, noBuf bool) {
|
||||||
panic("bad blocksize returned to pool")
|
if !noBuf {
|
||||||
|
f.pool.Put(buf)
|
||||||
}
|
}
|
||||||
// fs.Debugf(f, "Returning upload block %p", buf)
|
f.uploadToken.Put()
|
||||||
f.bufferTokens <- buf
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Return an Object from a path
|
// Return an Object from a path
|
||||||
@@ -623,11 +676,11 @@ func (f *Fs) list(ctx context.Context, bucket, directory, prefix string, addBuck
|
|||||||
var request = api.ListFileNamesRequest{
|
var request = api.ListFileNamesRequest{
|
||||||
BucketID: bucketID,
|
BucketID: bucketID,
|
||||||
MaxFileCount: chunkSize,
|
MaxFileCount: chunkSize,
|
||||||
Prefix: enc.FromStandardPath(directory),
|
Prefix: f.opt.Enc.FromStandardPath(directory),
|
||||||
Delimiter: delimiter,
|
Delimiter: delimiter,
|
||||||
}
|
}
|
||||||
if directory != "" {
|
if directory != "" {
|
||||||
request.StartFileName = enc.FromStandardPath(directory)
|
request.StartFileName = f.opt.Enc.FromStandardPath(directory)
|
||||||
}
|
}
|
||||||
opts := rest.Opts{
|
opts := rest.Opts{
|
||||||
Method: "POST",
|
Method: "POST",
|
||||||
@@ -647,7 +700,7 @@ func (f *Fs) list(ctx context.Context, bucket, directory, prefix string, addBuck
|
|||||||
}
|
}
|
||||||
for i := range response.Files {
|
for i := range response.Files {
|
||||||
file := &response.Files[i]
|
file := &response.Files[i]
|
||||||
file.Name = enc.ToStandardPath(file.Name)
|
file.Name = f.opt.Enc.ToStandardPath(file.Name)
|
||||||
// Finish if file name no longer has prefix
|
// Finish if file name no longer has prefix
|
||||||
if prefix != "" && !strings.HasPrefix(file.Name, prefix) {
|
if prefix != "" && !strings.HasPrefix(file.Name, prefix) {
|
||||||
return nil
|
return nil
|
||||||
@@ -658,8 +711,8 @@ func (f *Fs) list(ctx context.Context, bucket, directory, prefix string, addBuck
|
|||||||
}
|
}
|
||||||
remote := file.Name[len(prefix):]
|
remote := file.Name[len(prefix):]
|
||||||
// Check for directory
|
// Check for directory
|
||||||
isDirectory := strings.HasSuffix(remote, "/")
|
isDirectory := remote == "" || strings.HasSuffix(remote, "/")
|
||||||
if isDirectory {
|
if isDirectory && len(remote) > 1 {
|
||||||
remote = remote[:len(remote)-1]
|
remote = remote[:len(remote)-1]
|
||||||
}
|
}
|
||||||
if addBucket {
|
if addBucket {
|
||||||
@@ -848,7 +901,7 @@ func (f *Fs) listBucketsToFn(ctx context.Context, fn listBucketFn) error {
|
|||||||
f._bucketType = make(map[string]string, 1)
|
f._bucketType = make(map[string]string, 1)
|
||||||
for i := range response.Buckets {
|
for i := range response.Buckets {
|
||||||
bucket := &response.Buckets[i]
|
bucket := &response.Buckets[i]
|
||||||
bucket.Name = enc.ToStandardName(bucket.Name)
|
bucket.Name = f.opt.Enc.ToStandardName(bucket.Name)
|
||||||
f.cache.MarkOK(bucket.Name)
|
f.cache.MarkOK(bucket.Name)
|
||||||
f._bucketID[bucket.Name] = bucket.ID
|
f._bucketID[bucket.Name] = bucket.ID
|
||||||
f._bucketType[bucket.Name] = bucket.Type
|
f._bucketType[bucket.Name] = bucket.Type
|
||||||
@@ -970,7 +1023,7 @@ func (f *Fs) makeBucket(ctx context.Context, bucket string) error {
|
|||||||
}
|
}
|
||||||
var request = api.CreateBucketRequest{
|
var request = api.CreateBucketRequest{
|
||||||
AccountID: f.info.AccountID,
|
AccountID: f.info.AccountID,
|
||||||
Name: enc.FromStandardName(bucket),
|
Name: f.opt.Enc.FromStandardName(bucket),
|
||||||
Type: "allPrivate",
|
Type: "allPrivate",
|
||||||
}
|
}
|
||||||
var response api.Bucket
|
var response api.Bucket
|
||||||
@@ -1054,7 +1107,7 @@ func (f *Fs) hide(ctx context.Context, bucket, bucketPath string) error {
|
|||||||
}
|
}
|
||||||
var request = api.HideFileRequest{
|
var request = api.HideFileRequest{
|
||||||
BucketID: bucketID,
|
BucketID: bucketID,
|
||||||
Name: enc.FromStandardPath(bucketPath),
|
Name: f.opt.Enc.FromStandardPath(bucketPath),
|
||||||
}
|
}
|
||||||
var response api.File
|
var response api.File
|
||||||
err = f.pacer.Call(func() (bool, error) {
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
@@ -1082,7 +1135,7 @@ func (f *Fs) deleteByID(ctx context.Context, ID, Name string) error {
|
|||||||
}
|
}
|
||||||
var request = api.DeleteFileRequest{
|
var request = api.DeleteFileRequest{
|
||||||
ID: ID,
|
ID: ID,
|
||||||
Name: enc.FromStandardPath(Name),
|
Name: f.opt.Enc.FromStandardPath(Name),
|
||||||
}
|
}
|
||||||
var response api.File
|
var response api.File
|
||||||
err := f.pacer.Call(func() (bool, error) {
|
err := f.pacer.Call(func() (bool, error) {
|
||||||
@@ -1100,7 +1153,8 @@ func (f *Fs) deleteByID(ctx context.Context, ID, Name string) error {
|
|||||||
// if oldOnly is true then it deletes only non current files.
|
// if oldOnly is true then it deletes only non current files.
|
||||||
//
|
//
|
||||||
// Implemented here so we can make sure we delete old versions.
|
// Implemented here so we can make sure we delete old versions.
|
||||||
func (f *Fs) purge(ctx context.Context, bucket, directory string, oldOnly bool) error {
|
func (f *Fs) purge(ctx context.Context, dir string, oldOnly bool) error {
|
||||||
|
bucket, directory := f.split(dir)
|
||||||
if bucket == "" {
|
if bucket == "" {
|
||||||
return errors.New("can't purge from root")
|
return errors.New("can't purge from root")
|
||||||
}
|
}
|
||||||
@@ -1124,10 +1178,10 @@ func (f *Fs) purge(ctx context.Context, bucket, directory string, oldOnly bool)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Delete Config.Transfers in parallel
|
// Delete Config.Transfers in parallel
|
||||||
toBeDeleted := make(chan *api.File, fs.Config.Transfers)
|
toBeDeleted := make(chan *api.File, f.ci.Transfers)
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
wg.Add(fs.Config.Transfers)
|
wg.Add(f.ci.Transfers)
|
||||||
for i := 0; i < fs.Config.Transfers; i++ {
|
for i := 0; i < f.ci.Transfers; i++ {
|
||||||
go func() {
|
go func() {
|
||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
for object := range toBeDeleted {
|
for object := range toBeDeleted {
|
||||||
@@ -1139,7 +1193,7 @@ func (f *Fs) purge(ctx context.Context, bucket, directory string, oldOnly bool)
|
|||||||
tr := accounting.Stats(ctx).NewCheckingTransfer(oi)
|
tr := accounting.Stats(ctx).NewCheckingTransfer(oi)
|
||||||
err = f.deleteByID(ctx, object.ID, object.Name)
|
err = f.deleteByID(ctx, object.ID, object.Name)
|
||||||
checkErr(err)
|
checkErr(err)
|
||||||
tr.Done(err)
|
tr.Done(ctx, err)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
@@ -1167,7 +1221,7 @@ func (f *Fs) purge(ctx context.Context, bucket, directory string, oldOnly bool)
|
|||||||
toBeDeleted <- object
|
toBeDeleted <- object
|
||||||
}
|
}
|
||||||
last = remote
|
last = remote
|
||||||
tr.Done(nil)
|
tr.Done(ctx, nil)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}))
|
}))
|
||||||
@@ -1175,22 +1229,79 @@ func (f *Fs) purge(ctx context.Context, bucket, directory string, oldOnly bool)
|
|||||||
wg.Wait()
|
wg.Wait()
|
||||||
|
|
||||||
if !oldOnly {
|
if !oldOnly {
|
||||||
checkErr(f.Rmdir(ctx, ""))
|
checkErr(f.Rmdir(ctx, dir))
|
||||||
}
|
}
|
||||||
return errReturn
|
return errReturn
|
||||||
}
|
}
|
||||||
|
|
||||||
// Purge deletes all the files and directories including the old versions.
|
// Purge deletes all the files and directories including the old versions.
|
||||||
func (f *Fs) Purge(ctx context.Context) error {
|
func (f *Fs) Purge(ctx context.Context, dir string) error {
|
||||||
return f.purge(ctx, f.rootBucket, f.rootDirectory, false)
|
return f.purge(ctx, dir, false)
|
||||||
}
|
}
|
||||||
|
|
||||||
// CleanUp deletes all the hidden files.
|
// CleanUp deletes all the hidden files.
|
||||||
func (f *Fs) CleanUp(ctx context.Context) error {
|
func (f *Fs) CleanUp(ctx context.Context) error {
|
||||||
return f.purge(ctx, f.rootBucket, f.rootDirectory, true)
|
return f.purge(ctx, "", true)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Copy src to this remote using server side copy operations.
|
// copy does a server-side copy from dstObj <- srcObj
|
||||||
|
//
|
||||||
|
// If newInfo is nil then the metadata will be copied otherwise it
|
||||||
|
// will be replaced with newInfo
|
||||||
|
func (f *Fs) copy(ctx context.Context, dstObj *Object, srcObj *Object, newInfo *api.File) (err error) {
|
||||||
|
if srcObj.size >= int64(f.opt.CopyCutoff) {
|
||||||
|
if newInfo == nil {
|
||||||
|
newInfo, err = srcObj.getMetaData(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
up, err := f.newLargeUpload(ctx, dstObj, nil, srcObj, f.opt.CopyCutoff, true, newInfo)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return up.Upload(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
dstBucket, dstPath := dstObj.split()
|
||||||
|
err = f.makeBucket(ctx, dstBucket)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
destBucketID, err := f.getBucketID(ctx, dstBucket)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
opts := rest.Opts{
|
||||||
|
Method: "POST",
|
||||||
|
Path: "/b2_copy_file",
|
||||||
|
}
|
||||||
|
var request = api.CopyFileRequest{
|
||||||
|
SourceID: srcObj.id,
|
||||||
|
Name: f.opt.Enc.FromStandardPath(dstPath),
|
||||||
|
DestBucketID: destBucketID,
|
||||||
|
}
|
||||||
|
if newInfo == nil {
|
||||||
|
request.MetadataDirective = "COPY"
|
||||||
|
} else {
|
||||||
|
request.MetadataDirective = "REPLACE"
|
||||||
|
request.ContentType = newInfo.ContentType
|
||||||
|
request.Info = newInfo.Info
|
||||||
|
}
|
||||||
|
var response api.FileInfo
|
||||||
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
|
resp, err := f.srv.CallJSON(ctx, &opts, &request, &response)
|
||||||
|
return f.shouldRetry(ctx, resp, err)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return dstObj.decodeMetaDataFileInfo(&response)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Copy src to this remote using server-side copy operations.
|
||||||
//
|
//
|
||||||
// This is stored with the remote path given
|
// This is stored with the remote path given
|
||||||
//
|
//
|
||||||
@@ -1200,47 +1311,21 @@ func (f *Fs) CleanUp(ctx context.Context) error {
|
|||||||
//
|
//
|
||||||
// If it isn't possible then return fs.ErrorCantCopy
|
// If it isn't possible then return fs.ErrorCantCopy
|
||||||
func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object, error) {
|
func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object, error) {
|
||||||
dstBucket, dstPath := f.split(remote)
|
|
||||||
err := f.makeBucket(ctx, dstBucket)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
srcObj, ok := src.(*Object)
|
srcObj, ok := src.(*Object)
|
||||||
if !ok {
|
if !ok {
|
||||||
fs.Debugf(src, "Can't copy - not same remote type")
|
fs.Debugf(src, "Can't copy - not same remote type")
|
||||||
return nil, fs.ErrorCantCopy
|
return nil, fs.ErrorCantCopy
|
||||||
}
|
}
|
||||||
destBucketID, err := f.getBucketID(ctx, dstBucket)
|
// Temporary Object under construction
|
||||||
if err != nil {
|
dstObj := &Object{
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
opts := rest.Opts{
|
|
||||||
Method: "POST",
|
|
||||||
Path: "/b2_copy_file",
|
|
||||||
}
|
|
||||||
var request = api.CopyFileRequest{
|
|
||||||
SourceID: srcObj.id,
|
|
||||||
Name: enc.FromStandardPath(dstPath),
|
|
||||||
MetadataDirective: "COPY",
|
|
||||||
DestBucketID: destBucketID,
|
|
||||||
}
|
|
||||||
var response api.FileInfo
|
|
||||||
err = f.pacer.Call(func() (bool, error) {
|
|
||||||
resp, err := f.srv.CallJSON(ctx, &opts, &request, &response)
|
|
||||||
return f.shouldRetry(ctx, resp, err)
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
o := &Object{
|
|
||||||
fs: f,
|
fs: f,
|
||||||
remote: remote,
|
remote: remote,
|
||||||
}
|
}
|
||||||
err = o.decodeMetaDataFileInfo(&response)
|
err := f.copy(ctx, dstObj, srcObj, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return o, nil
|
return dstObj, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Hashes returns the supported hash sets.
|
// Hashes returns the supported hash sets.
|
||||||
@@ -1268,7 +1353,7 @@ func (f *Fs) getDownloadAuthorization(ctx context.Context, bucket, remote string
|
|||||||
}
|
}
|
||||||
var request = api.GetDownloadAuthorizationRequest{
|
var request = api.GetDownloadAuthorizationRequest{
|
||||||
BucketID: bucketID,
|
BucketID: bucketID,
|
||||||
FileNamePrefix: enc.FromStandardPath(path.Join(f.root, remote)),
|
FileNamePrefix: f.opt.Enc.FromStandardPath(path.Join(f.root, remote)),
|
||||||
ValidDurationInSeconds: validDurationInSeconds,
|
ValidDurationInSeconds: validDurationInSeconds,
|
||||||
}
|
}
|
||||||
var response api.GetDownloadAuthorizationResponse
|
var response api.GetDownloadAuthorizationResponse
|
||||||
@@ -1283,7 +1368,7 @@ func (f *Fs) getDownloadAuthorization(ctx context.Context, bucket, remote string
|
|||||||
}
|
}
|
||||||
|
|
||||||
// PublicLink returns a link for downloading without account
|
// PublicLink returns a link for downloading without account
|
||||||
func (f *Fs) PublicLink(ctx context.Context, remote string) (link string, err error) {
|
func (f *Fs) PublicLink(ctx context.Context, remote string, expire fs.Duration, unlink bool) (link string, err error) {
|
||||||
bucket, bucketPath := f.split(remote)
|
bucket, bucketPath := f.split(remote)
|
||||||
var RootURL string
|
var RootURL string
|
||||||
if f.opt.DownloadURL == "" {
|
if f.opt.DownloadURL == "" {
|
||||||
@@ -1360,6 +1445,21 @@ func (o *Object) Size() int64 {
|
|||||||
return o.size
|
return o.size
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Clean the SHA1
|
||||||
|
//
|
||||||
|
// Make sure it is lower case
|
||||||
|
//
|
||||||
|
// Remove unverified prefix - see https://www.backblaze.com/b2/docs/uploading.html
|
||||||
|
// Some tools (e.g. Cyberduck) use this
|
||||||
|
func cleanSHA1(sha1 string) (out string) {
|
||||||
|
out = strings.ToLower(sha1)
|
||||||
|
const unverified = "unverified:"
|
||||||
|
if strings.HasPrefix(out, unverified) {
|
||||||
|
out = out[len(unverified):]
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
// decodeMetaDataRaw sets the metadata from the data passed in
|
// decodeMetaDataRaw sets the metadata from the data passed in
|
||||||
//
|
//
|
||||||
// Sets
|
// Sets
|
||||||
@@ -1375,12 +1475,7 @@ func (o *Object) decodeMetaDataRaw(ID, SHA1 string, Size int64, UploadTimestamp
|
|||||||
if o.sha1 == "" || o.sha1 == "none" {
|
if o.sha1 == "" || o.sha1 == "none" {
|
||||||
o.sha1 = Info[sha1Key]
|
o.sha1 = Info[sha1Key]
|
||||||
}
|
}
|
||||||
// Remove unverified prefix - see https://www.backblaze.com/b2/docs/uploading.html
|
o.sha1 = cleanSHA1(o.sha1)
|
||||||
// Some tools (eg Cyberduck) use this
|
|
||||||
const unverified = "unverified:"
|
|
||||||
if strings.HasPrefix(o.sha1, unverified) {
|
|
||||||
o.sha1 = o.sha1[len(unverified):]
|
|
||||||
}
|
|
||||||
o.size = Size
|
o.size = Size
|
||||||
// Use the UploadTimestamp if can't get file info
|
// Use the UploadTimestamp if can't get file info
|
||||||
o.modTime = time.Time(UploadTimestamp)
|
o.modTime = time.Time(UploadTimestamp)
|
||||||
@@ -1409,8 +1504,11 @@ func (o *Object) decodeMetaDataFileInfo(info *api.FileInfo) (err error) {
|
|||||||
return o.decodeMetaDataRaw(info.ID, info.SHA1, info.Size, info.UploadTimestamp, info.Info, info.ContentType)
|
return o.decodeMetaDataRaw(info.ID, info.SHA1, info.Size, info.UploadTimestamp, info.Info, info.ContentType)
|
||||||
}
|
}
|
||||||
|
|
||||||
// getMetaData gets the metadata from the object unconditionally
|
// getMetaDataListing gets the metadata from the object unconditionally from the listing
|
||||||
func (o *Object) getMetaData(ctx context.Context) (info *api.File, err error) {
|
//
|
||||||
|
// Note that listing is a class C transaction which costs more than
|
||||||
|
// the B transaction used in getMetaData
|
||||||
|
func (o *Object) getMetaDataListing(ctx context.Context) (info *api.File, err error) {
|
||||||
bucket, bucketPath := o.split()
|
bucket, bucketPath := o.split()
|
||||||
maxSearched := 1
|
maxSearched := 1
|
||||||
var timestamp api.Timestamp
|
var timestamp api.Timestamp
|
||||||
@@ -1443,6 +1541,19 @@ func (o *Object) getMetaData(ctx context.Context) (info *api.File, err error) {
|
|||||||
return info, nil
|
return info, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// getMetaData gets the metadata from the object unconditionally
|
||||||
|
func (o *Object) getMetaData(ctx context.Context) (info *api.File, err error) {
|
||||||
|
// If using versions and have a version suffix, need to list the directory to find the correct versions
|
||||||
|
if o.fs.opt.Versions {
|
||||||
|
timestamp, _ := api.RemoveVersion(o.remote)
|
||||||
|
if !timestamp.IsZero() {
|
||||||
|
return o.getMetaDataListing(ctx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_, info, err = o.getOrHead(ctx, "HEAD", nil)
|
||||||
|
return info, err
|
||||||
|
}
|
||||||
|
|
||||||
// readMetaData gets the metadata if it hasn't already been fetched
|
// readMetaData gets the metadata if it hasn't already been fetched
|
||||||
//
|
//
|
||||||
// Sets
|
// Sets
|
||||||
@@ -1501,28 +1612,10 @@ func (o *Object) SetModTime(ctx context.Context, modTime time.Time) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
_, bucketPath := o.split()
|
|
||||||
info.Info[timeKey] = timeString(modTime)
|
info.Info[timeKey] = timeString(modTime)
|
||||||
opts := rest.Opts{
|
|
||||||
Method: "POST",
|
// Copy to the same name, overwriting the metadata only
|
||||||
Path: "/b2_copy_file",
|
return o.fs.copy(ctx, o, o, info)
|
||||||
}
|
|
||||||
var request = api.CopyFileRequest{
|
|
||||||
SourceID: o.id,
|
|
||||||
Name: enc.FromStandardPath(bucketPath), // copy to same name
|
|
||||||
MetadataDirective: "REPLACE",
|
|
||||||
ContentType: info.ContentType,
|
|
||||||
Info: info.Info,
|
|
||||||
}
|
|
||||||
var response api.FileInfo
|
|
||||||
err = o.fs.pacer.Call(func() (bool, error) {
|
|
||||||
resp, err := o.fs.srv.CallJSON(ctx, &opts, &request, &response)
|
|
||||||
return o.fs.shouldRetry(ctx, resp, err)
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return o.decodeMetaDataFileInfo(&response)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Storable returns if this object is storable
|
// Storable returns if this object is storable
|
||||||
@@ -1590,12 +1683,11 @@ func (file *openFile) Close() (err error) {
|
|||||||
// Check it satisfies the interfaces
|
// Check it satisfies the interfaces
|
||||||
var _ io.ReadCloser = &openFile{}
|
var _ io.ReadCloser = &openFile{}
|
||||||
|
|
||||||
// Open an object for read
|
func (o *Object) getOrHead(ctx context.Context, method string, options []fs.OpenOption) (resp *http.Response, info *api.File, err error) {
|
||||||
func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.ReadCloser, err error) {
|
|
||||||
fs.FixRangeOption(options, o.size)
|
|
||||||
opts := rest.Opts{
|
opts := rest.Opts{
|
||||||
Method: "GET",
|
Method: method,
|
||||||
Options: options,
|
Options: options,
|
||||||
|
NoResponse: method == "HEAD",
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use downloadUrl from backblaze if downloadUrl is not set
|
// Use downloadUrl from backblaze if downloadUrl is not set
|
||||||
@@ -1606,43 +1698,74 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.Read
|
|||||||
opts.RootURL = o.fs.opt.DownloadURL
|
opts.RootURL = o.fs.opt.DownloadURL
|
||||||
}
|
}
|
||||||
|
|
||||||
// Download by id if set otherwise by name
|
// Download by id if set and not using DownloadURL otherwise by name
|
||||||
if o.id != "" {
|
if o.id != "" && o.fs.opt.DownloadURL == "" {
|
||||||
opts.Path += "/b2api/v1/b2_download_file_by_id?fileId=" + urlEncode(o.id)
|
opts.Path += "/b2api/v1/b2_download_file_by_id?fileId=" + urlEncode(o.id)
|
||||||
} else {
|
} else {
|
||||||
bucket, bucketPath := o.split()
|
bucket, bucketPath := o.split()
|
||||||
opts.Path += "/file/" + urlEncode(enc.FromStandardName(bucket)) + "/" + urlEncode(enc.FromStandardPath(bucketPath))
|
opts.Path += "/file/" + urlEncode(o.fs.opt.Enc.FromStandardName(bucket)) + "/" + urlEncode(o.fs.opt.Enc.FromStandardPath(bucketPath))
|
||||||
}
|
}
|
||||||
var resp *http.Response
|
|
||||||
err = o.fs.pacer.Call(func() (bool, error) {
|
err = o.fs.pacer.Call(func() (bool, error) {
|
||||||
resp, err = o.fs.srv.Call(ctx, &opts)
|
resp, err = o.fs.srv.Call(ctx, &opts)
|
||||||
return o.fs.shouldRetry(ctx, resp, err)
|
return o.fs.shouldRetry(ctx, resp, err)
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "failed to open for download")
|
// 404 for files, 400 for directories
|
||||||
|
if resp != nil && (resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusBadRequest) {
|
||||||
|
return nil, nil, fs.ErrorObjectNotFound
|
||||||
|
}
|
||||||
|
return nil, nil, errors.Wrapf(err, "failed to %s for download", method)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse the time out of the headers if possible
|
// NB resp may be Open here - don't return err != nil without closing
|
||||||
err = o.parseTimeString(resp.Header.Get(timeHeader))
|
|
||||||
|
// Convert the Headers into an api.File
|
||||||
|
var uploadTimestamp api.Timestamp
|
||||||
|
err = uploadTimestamp.UnmarshalJSON([]byte(resp.Header.Get(timestampHeader)))
|
||||||
|
if err != nil {
|
||||||
|
fs.Debugf(o, "Bad "+timestampHeader+" header: %v", err)
|
||||||
|
}
|
||||||
|
var Info = make(map[string]string)
|
||||||
|
for k, vs := range resp.Header {
|
||||||
|
k = strings.ToLower(k)
|
||||||
|
for _, v := range vs {
|
||||||
|
if strings.HasPrefix(k, headerPrefix) {
|
||||||
|
Info[k[len(headerPrefix):]] = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
info = &api.File{
|
||||||
|
ID: resp.Header.Get(idHeader),
|
||||||
|
Name: resp.Header.Get(nameHeader),
|
||||||
|
Action: "upload",
|
||||||
|
Size: resp.ContentLength,
|
||||||
|
UploadTimestamp: uploadTimestamp,
|
||||||
|
SHA1: resp.Header.Get(sha1Header),
|
||||||
|
ContentType: resp.Header.Get("Content-Type"),
|
||||||
|
Info: Info,
|
||||||
|
}
|
||||||
|
return resp, info, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Open an object for read
|
||||||
|
func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.ReadCloser, err error) {
|
||||||
|
fs.FixRangeOption(options, o.size)
|
||||||
|
|
||||||
|
resp, info, err := o.getOrHead(ctx, "GET", options)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Don't check length or hash or metadata on partial content
|
||||||
|
if resp.StatusCode == http.StatusPartialContent {
|
||||||
|
return resp.Body, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
err = o.decodeMetaData(info)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = resp.Body.Close()
|
_ = resp.Body.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
// Read sha1 from header if it isn't set
|
|
||||||
if o.sha1 == "" {
|
|
||||||
o.sha1 = resp.Header.Get(sha1Header)
|
|
||||||
fs.Debugf(o, "Reading sha1 from header - %q", o.sha1)
|
|
||||||
// if sha1 header is "none" (in big files), then need
|
|
||||||
// to read it from the metadata
|
|
||||||
if o.sha1 == "none" {
|
|
||||||
o.sha1 = resp.Header.Get(sha1InfoHeader)
|
|
||||||
fs.Debugf(o, "Reading sha1 from info - %q", o.sha1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Don't check length or hash on partial content
|
|
||||||
if resp.StatusCode == http.StatusPartialContent {
|
|
||||||
return resp.Body, nil
|
|
||||||
}
|
|
||||||
return newOpenFile(o, resp), nil
|
return newOpenFile(o, resp), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1697,7 +1820,8 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
}
|
}
|
||||||
if size == -1 {
|
if size == -1 {
|
||||||
// Check if the file is large enough for a chunked upload (needs to be at least two chunks)
|
// Check if the file is large enough for a chunked upload (needs to be at least two chunks)
|
||||||
buf := o.fs.getUploadBlock()
|
buf := o.fs.getBuf(false)
|
||||||
|
|
||||||
n, err := io.ReadFull(in, buf)
|
n, err := io.ReadFull(in, buf)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
bufReader := bufio.NewReader(in)
|
bufReader := bufio.NewReader(in)
|
||||||
@@ -1707,22 +1831,24 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
fs.Debugf(o, "File is big enough for chunked streaming")
|
fs.Debugf(o, "File is big enough for chunked streaming")
|
||||||
up, err := o.fs.newLargeUpload(ctx, o, in, src)
|
up, err := o.fs.newLargeUpload(ctx, o, in, src, o.fs.opt.ChunkSize, false, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
o.fs.putUploadBlock(buf)
|
o.fs.putBuf(buf, false)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
// NB Stream returns the buffer and token
|
||||||
return up.Stream(ctx, buf)
|
return up.Stream(ctx, buf)
|
||||||
} else if err == io.EOF || err == io.ErrUnexpectedEOF {
|
} else if err == io.EOF || err == io.ErrUnexpectedEOF {
|
||||||
fs.Debugf(o, "File has %d bytes, which makes only one chunk. Using direct upload.", n)
|
fs.Debugf(o, "File has %d bytes, which makes only one chunk. Using direct upload.", n)
|
||||||
defer o.fs.putUploadBlock(buf)
|
defer o.fs.putBuf(buf, false)
|
||||||
size = int64(n)
|
size = int64(n)
|
||||||
in = bytes.NewReader(buf[:n])
|
in = bytes.NewReader(buf[:n])
|
||||||
} else {
|
} else {
|
||||||
|
o.fs.putBuf(buf, false)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
} else if size > int64(o.fs.opt.UploadCutoff) {
|
} else if size > int64(o.fs.opt.UploadCutoff) {
|
||||||
up, err := o.fs.newLargeUpload(ctx, o, in, src)
|
up, err := o.fs.newLargeUpload(ctx, o, in, src, o.fs.opt.ChunkSize, false, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -1806,9 +1932,10 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
Method: "POST",
|
Method: "POST",
|
||||||
RootURL: upload.UploadURL,
|
RootURL: upload.UploadURL,
|
||||||
Body: in,
|
Body: in,
|
||||||
|
Options: options,
|
||||||
ExtraHeaders: map[string]string{
|
ExtraHeaders: map[string]string{
|
||||||
"Authorization": upload.AuthorizationToken,
|
"Authorization": upload.AuthorizationToken,
|
||||||
"X-Bz-File-Name": urlEncode(enc.FromStandardPath(bucketPath)),
|
"X-Bz-File-Name": urlEncode(o.fs.opt.Enc.FromStandardPath(bucketPath)),
|
||||||
"Content-Type": fs.MimeType(ctx, src),
|
"Content-Type": fs.MimeType(ctx, src),
|
||||||
sha1Header: calculatedSha1,
|
sha1Header: calculatedSha1,
|
||||||
timeHeader: timeString(modTime),
|
timeHeader: timeString(modTime),
|
||||||
|
|||||||
+203
-158
@@ -20,7 +20,9 @@ import (
|
|||||||
"github.com/rclone/rclone/fs"
|
"github.com/rclone/rclone/fs"
|
||||||
"github.com/rclone/rclone/fs/accounting"
|
"github.com/rclone/rclone/fs/accounting"
|
||||||
"github.com/rclone/rclone/fs/hash"
|
"github.com/rclone/rclone/fs/hash"
|
||||||
|
"github.com/rclone/rclone/lib/atexit"
|
||||||
"github.com/rclone/rclone/lib/rest"
|
"github.com/rclone/rclone/lib/rest"
|
||||||
|
"golang.org/x/sync/errgroup"
|
||||||
)
|
)
|
||||||
|
|
||||||
type hashAppendingReader struct {
|
type hashAppendingReader struct {
|
||||||
@@ -68,20 +70,26 @@ func newHashAppendingReader(in io.Reader, h gohash.Hash) *hashAppendingReader {
|
|||||||
|
|
||||||
// largeUpload is used to control the upload of large files which need chunking
|
// largeUpload is used to control the upload of large files which need chunking
|
||||||
type largeUpload struct {
|
type largeUpload struct {
|
||||||
f *Fs // parent Fs
|
f *Fs // parent Fs
|
||||||
o *Object // object being uploaded
|
o *Object // object being uploaded
|
||||||
in io.Reader // read the data from here
|
doCopy bool // doing copy rather than upload
|
||||||
wrap accounting.WrapFn // account parts being transferred
|
what string // text name of operation for logs
|
||||||
id string // ID of the file being uploaded
|
in io.Reader // read the data from here
|
||||||
size int64 // total size
|
wrap accounting.WrapFn // account parts being transferred
|
||||||
parts int64 // calculated number of parts, if known
|
id string // ID of the file being uploaded
|
||||||
sha1s []string // slice of SHA1s for each part
|
size int64 // total size
|
||||||
uploadMu sync.Mutex // lock for upload variable
|
parts int64 // calculated number of parts, if known
|
||||||
uploads []*api.GetUploadPartURLResponse // result of get upload URL calls
|
sha1s []string // slice of SHA1s for each part
|
||||||
|
uploadMu sync.Mutex // lock for upload variable
|
||||||
|
uploads []*api.GetUploadPartURLResponse // result of get upload URL calls
|
||||||
|
chunkSize int64 // chunk size to use
|
||||||
|
src *Object // if copying, object we are reading from
|
||||||
}
|
}
|
||||||
|
|
||||||
// newLargeUpload starts an upload of object o from in with metadata in src
|
// newLargeUpload starts an upload of object o from in with metadata in src
|
||||||
func (f *Fs) newLargeUpload(ctx context.Context, o *Object, in io.Reader, src fs.ObjectInfo) (up *largeUpload, err error) {
|
//
|
||||||
|
// If newInfo is set then metadata from that will be used instead of reading it from src
|
||||||
|
func (f *Fs) newLargeUpload(ctx context.Context, o *Object, in io.Reader, src fs.ObjectInfo, chunkSize fs.SizeSuffix, doCopy bool, newInfo *api.File) (up *largeUpload, err error) {
|
||||||
remote := o.remote
|
remote := o.remote
|
||||||
size := src.Size()
|
size := src.Size()
|
||||||
parts := int64(0)
|
parts := int64(0)
|
||||||
@@ -89,8 +97,8 @@ func (f *Fs) newLargeUpload(ctx context.Context, o *Object, in io.Reader, src fs
|
|||||||
if size == -1 {
|
if size == -1 {
|
||||||
fs.Debugf(o, "Streaming upload with --b2-chunk-size %s allows uploads of up to %s and will fail only when that limit is reached.", f.opt.ChunkSize, maxParts*f.opt.ChunkSize)
|
fs.Debugf(o, "Streaming upload with --b2-chunk-size %s allows uploads of up to %s and will fail only when that limit is reached.", f.opt.ChunkSize, maxParts*f.opt.ChunkSize)
|
||||||
} else {
|
} else {
|
||||||
parts = size / int64(o.fs.opt.ChunkSize)
|
parts = size / int64(chunkSize)
|
||||||
if size%int64(o.fs.opt.ChunkSize) != 0 {
|
if size%int64(chunkSize) != 0 {
|
||||||
parts++
|
parts++
|
||||||
}
|
}
|
||||||
if parts > maxParts {
|
if parts > maxParts {
|
||||||
@@ -99,7 +107,6 @@ func (f *Fs) newLargeUpload(ctx context.Context, o *Object, in io.Reader, src fs
|
|||||||
sha1SliceSize = parts
|
sha1SliceSize = parts
|
||||||
}
|
}
|
||||||
|
|
||||||
modTime := src.ModTime(ctx)
|
|
||||||
opts := rest.Opts{
|
opts := rest.Opts{
|
||||||
Method: "POST",
|
Method: "POST",
|
||||||
Path: "/b2_start_large_file",
|
Path: "/b2_start_large_file",
|
||||||
@@ -110,18 +117,24 @@ func (f *Fs) newLargeUpload(ctx context.Context, o *Object, in io.Reader, src fs
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
var request = api.StartLargeFileRequest{
|
var request = api.StartLargeFileRequest{
|
||||||
BucketID: bucketID,
|
BucketID: bucketID,
|
||||||
Name: enc.FromStandardPath(bucketPath),
|
Name: f.opt.Enc.FromStandardPath(bucketPath),
|
||||||
ContentType: fs.MimeType(ctx, src),
|
|
||||||
Info: map[string]string{
|
|
||||||
timeKey: timeString(modTime),
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
// Set the SHA1 if known
|
if newInfo == nil {
|
||||||
if !o.fs.opt.DisableCheckSum {
|
modTime := src.ModTime(ctx)
|
||||||
if calculatedSha1, err := src.Hash(ctx, hash.SHA1); err == nil && calculatedSha1 != "" {
|
request.ContentType = fs.MimeType(ctx, src)
|
||||||
request.Info[sha1Key] = calculatedSha1
|
request.Info = map[string]string{
|
||||||
|
timeKey: timeString(modTime),
|
||||||
}
|
}
|
||||||
|
// Set the SHA1 if known
|
||||||
|
if !o.fs.opt.DisableCheckSum || doCopy {
|
||||||
|
if calculatedSha1, err := src.Hash(ctx, hash.SHA1); err == nil && calculatedSha1 != "" {
|
||||||
|
request.Info[sha1Key] = calculatedSha1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
request.ContentType = newInfo.ContentType
|
||||||
|
request.Info = newInfo.Info
|
||||||
}
|
}
|
||||||
var response api.StartLargeFileResponse
|
var response api.StartLargeFileResponse
|
||||||
err = f.pacer.Call(func() (bool, error) {
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
@@ -131,18 +144,24 @@ func (f *Fs) newLargeUpload(ctx context.Context, o *Object, in io.Reader, src fs
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
up = &largeUpload{
|
||||||
|
f: f,
|
||||||
|
o: o,
|
||||||
|
doCopy: doCopy,
|
||||||
|
what: "upload",
|
||||||
|
id: response.ID,
|
||||||
|
size: size,
|
||||||
|
parts: parts,
|
||||||
|
sha1s: make([]string, sha1SliceSize),
|
||||||
|
chunkSize: int64(chunkSize),
|
||||||
|
}
|
||||||
// unwrap the accounting from the input, we use wrap to put it
|
// unwrap the accounting from the input, we use wrap to put it
|
||||||
// back on after the buffering
|
// back on after the buffering
|
||||||
in, wrap := accounting.UnWrap(in)
|
if doCopy {
|
||||||
up = &largeUpload{
|
up.what = "copy"
|
||||||
f: f,
|
up.src = src.(*Object)
|
||||||
o: o,
|
} else {
|
||||||
in: in,
|
up.in, up.wrap = accounting.UnWrap(in)
|
||||||
wrap: wrap,
|
|
||||||
id: response.ID,
|
|
||||||
size: size,
|
|
||||||
parts: parts,
|
|
||||||
sha1s: make([]string, sha1SliceSize),
|
|
||||||
}
|
}
|
||||||
return up, nil
|
return up, nil
|
||||||
}
|
}
|
||||||
@@ -184,13 +203,6 @@ func (up *largeUpload) returnUploadURL(upload *api.GetUploadPartURLResponse) {
|
|||||||
up.uploadMu.Unlock()
|
up.uploadMu.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
// clearUploadURL clears the current UploadURL and the AuthorizationToken
|
|
||||||
func (up *largeUpload) clearUploadURL() {
|
|
||||||
up.uploadMu.Lock()
|
|
||||||
up.uploads = nil
|
|
||||||
up.uploadMu.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Transfer a chunk
|
// Transfer a chunk
|
||||||
func (up *largeUpload) transferChunk(ctx context.Context, part int64, body []byte) error {
|
func (up *largeUpload) transferChunk(ctx context.Context, part int64, body []byte) error {
|
||||||
err := up.f.pacer.Call(func() (bool, error) {
|
err := up.f.pacer.Call(func() (bool, error) {
|
||||||
@@ -263,9 +275,41 @@ func (up *largeUpload) transferChunk(ctx context.Context, part int64, body []byt
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Copy a chunk
|
||||||
|
func (up *largeUpload) copyChunk(ctx context.Context, part int64, partSize int64) error {
|
||||||
|
err := up.f.pacer.Call(func() (bool, error) {
|
||||||
|
fs.Debugf(up.o, "Copying chunk %d length %d", part, partSize)
|
||||||
|
opts := rest.Opts{
|
||||||
|
Method: "POST",
|
||||||
|
Path: "/b2_copy_part",
|
||||||
|
}
|
||||||
|
offset := (part - 1) * up.chunkSize // where we are in the source file
|
||||||
|
var request = api.CopyPartRequest{
|
||||||
|
SourceID: up.src.id,
|
||||||
|
LargeFileID: up.id,
|
||||||
|
PartNumber: part,
|
||||||
|
Range: fmt.Sprintf("bytes=%d-%d", offset, offset+partSize-1),
|
||||||
|
}
|
||||||
|
var response api.UploadPartResponse
|
||||||
|
resp, err := up.f.srv.CallJSON(ctx, &opts, &request, &response)
|
||||||
|
retry, err := up.f.shouldRetry(ctx, resp, err)
|
||||||
|
if err != nil {
|
||||||
|
fs.Debugf(up.o, "Error copying chunk %d (retry=%v): %v: %#v", part, retry, err, err)
|
||||||
|
}
|
||||||
|
up.sha1s[part-1] = response.SHA1
|
||||||
|
return retry, err
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
fs.Debugf(up.o, "Error copying chunk %d: %v", part, err)
|
||||||
|
} else {
|
||||||
|
fs.Debugf(up.o, "Done copying chunk %d", part)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
// finish closes off the large upload
|
// finish closes off the large upload
|
||||||
func (up *largeUpload) finish(ctx context.Context) error {
|
func (up *largeUpload) finish(ctx context.Context) error {
|
||||||
fs.Debugf(up.o, "Finishing large file upload with %d parts", up.parts)
|
fs.Debugf(up.o, "Finishing large file %s with %d parts", up.what, up.parts)
|
||||||
opts := rest.Opts{
|
opts := rest.Opts{
|
||||||
Method: "POST",
|
Method: "POST",
|
||||||
Path: "/b2_finish_large_file",
|
Path: "/b2_finish_large_file",
|
||||||
@@ -287,6 +331,7 @@ func (up *largeUpload) finish(ctx context.Context) error {
|
|||||||
|
|
||||||
// cancel aborts the large upload
|
// cancel aborts the large upload
|
||||||
func (up *largeUpload) cancel(ctx context.Context) error {
|
func (up *largeUpload) cancel(ctx context.Context) error {
|
||||||
|
fs.Debugf(up.o, "Cancelling large file %s", up.what)
|
||||||
opts := rest.Opts{
|
opts := rest.Opts{
|
||||||
Method: "POST",
|
Method: "POST",
|
||||||
Path: "/b2_cancel_large_file",
|
Path: "/b2_cancel_large_file",
|
||||||
@@ -299,139 +344,139 @@ func (up *largeUpload) cancel(ctx context.Context) error {
|
|||||||
resp, err := up.f.srv.CallJSON(ctx, &opts, &request, &response)
|
resp, err := up.f.srv.CallJSON(ctx, &opts, &request, &response)
|
||||||
return up.f.shouldRetry(ctx, resp, err)
|
return up.f.shouldRetry(ctx, resp, err)
|
||||||
})
|
})
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (up *largeUpload) managedTransferChunk(ctx context.Context, wg *sync.WaitGroup, errs chan error, part int64, buf []byte) {
|
|
||||||
wg.Add(1)
|
|
||||||
go func(part int64, buf []byte) {
|
|
||||||
defer wg.Done()
|
|
||||||
defer up.f.putUploadBlock(buf)
|
|
||||||
err := up.transferChunk(ctx, part, buf)
|
|
||||||
if err != nil {
|
|
||||||
select {
|
|
||||||
case errs <- err:
|
|
||||||
default:
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}(part, buf)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (up *largeUpload) finishOrCancelOnError(ctx context.Context, err error, errs chan error) error {
|
|
||||||
if err == nil {
|
|
||||||
select {
|
|
||||||
case err = <-errs:
|
|
||||||
default:
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fs.Debugf(up.o, "Cancelling large file upload due to error: %v", err)
|
fs.Errorf(up.o, "Failed to cancel large file %s: %v", up.what, err)
|
||||||
cancelErr := up.cancel(ctx)
|
|
||||||
if cancelErr != nil {
|
|
||||||
fs.Errorf(up.o, "Failed to cancel large file upload: %v", cancelErr)
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
}
|
||||||
return up.finish(ctx)
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stream uploads the chunks from the input, starting with a required initial
|
// Stream uploads the chunks from the input, starting with a required initial
|
||||||
// chunk. Assumes the file size is unknown and will upload until the input
|
// chunk. Assumes the file size is unknown and will upload until the input
|
||||||
// reaches EOF.
|
// reaches EOF.
|
||||||
|
//
|
||||||
|
// Note that initialUploadBlock must be returned to f.putBuf()
|
||||||
func (up *largeUpload) Stream(ctx context.Context, initialUploadBlock []byte) (err error) {
|
func (up *largeUpload) Stream(ctx context.Context, initialUploadBlock []byte) (err error) {
|
||||||
|
defer atexit.OnError(&err, func() { _ = up.cancel(ctx) })()
|
||||||
fs.Debugf(up.o, "Starting streaming of large file (id %q)", up.id)
|
fs.Debugf(up.o, "Starting streaming of large file (id %q)", up.id)
|
||||||
errs := make(chan error, 1)
|
var (
|
||||||
hasMoreParts := true
|
g, gCtx = errgroup.WithContext(ctx)
|
||||||
var wg sync.WaitGroup
|
hasMoreParts = true
|
||||||
|
)
|
||||||
// Transfer initial chunk
|
|
||||||
up.size = int64(len(initialUploadBlock))
|
up.size = int64(len(initialUploadBlock))
|
||||||
up.managedTransferChunk(ctx, &wg, errs, 1, initialUploadBlock)
|
g.Go(func() error {
|
||||||
|
for part := int64(1); hasMoreParts; part++ {
|
||||||
|
// Get a block of memory from the pool and token which limits concurrency.
|
||||||
|
var buf []byte
|
||||||
|
if part == 1 {
|
||||||
|
buf = initialUploadBlock
|
||||||
|
} else {
|
||||||
|
buf = up.f.getBuf(false)
|
||||||
|
}
|
||||||
|
|
||||||
outer:
|
// Fail fast, in case an errgroup managed function returns an error
|
||||||
for part := int64(2); hasMoreParts; part++ {
|
// gCtx is cancelled. There is no point in uploading all the other parts.
|
||||||
// Check any errors
|
if gCtx.Err() != nil {
|
||||||
select {
|
up.f.putBuf(buf, false)
|
||||||
case err = <-errs:
|
return nil
|
||||||
break outer
|
}
|
||||||
default:
|
|
||||||
|
// Read the chunk
|
||||||
|
var n int
|
||||||
|
if part == 1 {
|
||||||
|
n = len(buf)
|
||||||
|
} else {
|
||||||
|
n, err = io.ReadFull(up.in, buf)
|
||||||
|
if err == io.ErrUnexpectedEOF {
|
||||||
|
fs.Debugf(up.o, "Read less than a full chunk, making this the last one.")
|
||||||
|
buf = buf[:n]
|
||||||
|
hasMoreParts = false
|
||||||
|
} else if err == io.EOF {
|
||||||
|
fs.Debugf(up.o, "Could not read any more bytes, previous chunk was the last.")
|
||||||
|
up.f.putBuf(buf, false)
|
||||||
|
return nil
|
||||||
|
} else if err != nil {
|
||||||
|
// other kinds of errors indicate failure
|
||||||
|
up.f.putBuf(buf, false)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keep stats up to date
|
||||||
|
up.parts = part
|
||||||
|
up.size += int64(n)
|
||||||
|
if part > maxParts {
|
||||||
|
up.f.putBuf(buf, false)
|
||||||
|
return errors.Errorf("%q too big (%d bytes so far) makes too many parts %d > %d - increase --b2-chunk-size", up.o, up.size, up.parts, maxParts)
|
||||||
|
}
|
||||||
|
|
||||||
|
part := part // for the closure
|
||||||
|
g.Go(func() (err error) {
|
||||||
|
defer up.f.putBuf(buf, false)
|
||||||
|
return up.transferChunk(gCtx, part, buf)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
return nil
|
||||||
// Get a block of memory
|
})
|
||||||
buf := up.f.getUploadBlock()
|
err = g.Wait()
|
||||||
|
if err != nil {
|
||||||
// Read the chunk
|
return err
|
||||||
var n int
|
|
||||||
n, err = io.ReadFull(up.in, buf)
|
|
||||||
if err == io.ErrUnexpectedEOF {
|
|
||||||
fs.Debugf(up.o, "Read less than a full chunk, making this the last one.")
|
|
||||||
buf = buf[:n]
|
|
||||||
hasMoreParts = false
|
|
||||||
err = nil
|
|
||||||
} else if err == io.EOF {
|
|
||||||
fs.Debugf(up.o, "Could not read any more bytes, previous chunk was the last.")
|
|
||||||
up.f.putUploadBlock(buf)
|
|
||||||
err = nil
|
|
||||||
break outer
|
|
||||||
} else if err != nil {
|
|
||||||
// other kinds of errors indicate failure
|
|
||||||
up.f.putUploadBlock(buf)
|
|
||||||
break outer
|
|
||||||
}
|
|
||||||
|
|
||||||
// Keep stats up to date
|
|
||||||
up.parts = part
|
|
||||||
up.size += int64(n)
|
|
||||||
if part > maxParts {
|
|
||||||
err = errors.Errorf("%q too big (%d bytes so far) makes too many parts %d > %d - increase --b2-chunk-size", up.o, up.size, up.parts, maxParts)
|
|
||||||
break outer
|
|
||||||
}
|
|
||||||
|
|
||||||
// Transfer the chunk
|
|
||||||
up.managedTransferChunk(ctx, &wg, errs, part, buf)
|
|
||||||
}
|
}
|
||||||
wg.Wait()
|
|
||||||
up.sha1s = up.sha1s[:up.parts]
|
up.sha1s = up.sha1s[:up.parts]
|
||||||
|
return up.finish(ctx)
|
||||||
return up.finishOrCancelOnError(ctx, err, errs)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Upload uploads the chunks from the input
|
// Upload uploads the chunks from the input
|
||||||
func (up *largeUpload) Upload(ctx context.Context) error {
|
func (up *largeUpload) Upload(ctx context.Context) (err error) {
|
||||||
fs.Debugf(up.o, "Starting upload of large file in %d chunks (id %q)", up.parts, up.id)
|
defer atexit.OnError(&err, func() { _ = up.cancel(ctx) })()
|
||||||
remaining := up.size
|
fs.Debugf(up.o, "Starting %s of large file in %d chunks (id %q)", up.what, up.parts, up.id)
|
||||||
errs := make(chan error, 1)
|
var (
|
||||||
var wg sync.WaitGroup
|
g, gCtx = errgroup.WithContext(ctx)
|
||||||
var err error
|
remaining = up.size
|
||||||
outer:
|
)
|
||||||
for part := int64(1); part <= up.parts; part++ {
|
g.Go(func() error {
|
||||||
// Check any errors
|
for part := int64(1); part <= up.parts; part++ {
|
||||||
select {
|
// Get a block of memory from the pool and token which limits concurrency.
|
||||||
case err = <-errs:
|
buf := up.f.getBuf(up.doCopy)
|
||||||
break outer
|
|
||||||
default:
|
// Fail fast, in case an errgroup managed function returns an error
|
||||||
|
// gCtx is cancelled. There is no point in uploading all the other parts.
|
||||||
|
if gCtx.Err() != nil {
|
||||||
|
up.f.putBuf(buf, up.doCopy)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
reqSize := remaining
|
||||||
|
if reqSize >= up.chunkSize {
|
||||||
|
reqSize = up.chunkSize
|
||||||
|
}
|
||||||
|
|
||||||
|
if !up.doCopy {
|
||||||
|
// Read the chunk
|
||||||
|
buf = buf[:reqSize]
|
||||||
|
_, err = io.ReadFull(up.in, buf)
|
||||||
|
if err != nil {
|
||||||
|
up.f.putBuf(buf, up.doCopy)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
part := part // for the closure
|
||||||
|
g.Go(func() (err error) {
|
||||||
|
defer up.f.putBuf(buf, up.doCopy)
|
||||||
|
if !up.doCopy {
|
||||||
|
err = up.transferChunk(gCtx, part, buf)
|
||||||
|
} else {
|
||||||
|
err = up.copyChunk(gCtx, part, reqSize)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
remaining -= reqSize
|
||||||
}
|
}
|
||||||
|
return nil
|
||||||
reqSize := remaining
|
})
|
||||||
if reqSize >= int64(up.f.opt.ChunkSize) {
|
err = g.Wait()
|
||||||
reqSize = int64(up.f.opt.ChunkSize)
|
if err != nil {
|
||||||
}
|
return err
|
||||||
|
|
||||||
// Get a block of memory
|
|
||||||
buf := up.f.getUploadBlock()[:reqSize]
|
|
||||||
|
|
||||||
// Read the chunk
|
|
||||||
_, err = io.ReadFull(up.in, buf)
|
|
||||||
if err != nil {
|
|
||||||
up.f.putUploadBlock(buf)
|
|
||||||
break outer
|
|
||||||
}
|
|
||||||
|
|
||||||
// Transfer the chunk
|
|
||||||
up.managedTransferChunk(ctx, &wg, errs, part, buf)
|
|
||||||
remaining -= reqSize
|
|
||||||
}
|
}
|
||||||
wg.Wait()
|
return up.finish(ctx)
|
||||||
|
|
||||||
return up.finishOrCancelOnError(ctx, err, errs)
|
|
||||||
}
|
}
|
||||||
@@ -222,3 +222,23 @@ type AppAuth struct {
|
|||||||
PrivateKey string `json:"privateKey"`
|
PrivateKey string `json:"privateKey"`
|
||||||
Passphrase string `json:"passphrase"`
|
Passphrase string `json:"passphrase"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// User is returned from /users/me
|
||||||
|
type User struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Login string `json:"login"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
ModifiedAt time.Time `json:"modified_at"`
|
||||||
|
Language string `json:"language"`
|
||||||
|
Timezone string `json:"timezone"`
|
||||||
|
SpaceAmount int64 `json:"space_amount"`
|
||||||
|
SpaceUsed int64 `json:"space_used"`
|
||||||
|
MaxUploadSize int64 `json:"max_upload_size"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
JobTitle string `json:"job_title"`
|
||||||
|
Phone string `json:"phone"`
|
||||||
|
Address string `json:"address"`
|
||||||
|
AvatarURL string `json:"avatar_url"`
|
||||||
|
}
|
||||||
+218
-140
@@ -25,6 +25,8 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/rclone/rclone/lib/encoder"
|
||||||
|
"github.com/rclone/rclone/lib/env"
|
||||||
"github.com/rclone/rclone/lib/jwtutil"
|
"github.com/rclone/rclone/lib/jwtutil"
|
||||||
|
|
||||||
"github.com/youmark/pkcs8"
|
"github.com/youmark/pkcs8"
|
||||||
@@ -36,7 +38,6 @@ import (
|
|||||||
"github.com/rclone/rclone/fs/config/configmap"
|
"github.com/rclone/rclone/fs/config/configmap"
|
||||||
"github.com/rclone/rclone/fs/config/configstruct"
|
"github.com/rclone/rclone/fs/config/configstruct"
|
||||||
"github.com/rclone/rclone/fs/config/obscure"
|
"github.com/rclone/rclone/fs/config/obscure"
|
||||||
"github.com/rclone/rclone/fs/encodings"
|
|
||||||
"github.com/rclone/rclone/fs/fserrors"
|
"github.com/rclone/rclone/fs/fserrors"
|
||||||
"github.com/rclone/rclone/fs/fshttp"
|
"github.com/rclone/rclone/fs/fshttp"
|
||||||
"github.com/rclone/rclone/fs/hash"
|
"github.com/rclone/rclone/fs/hash"
|
||||||
@@ -48,15 +49,12 @@ import (
|
|||||||
"golang.org/x/oauth2/jws"
|
"golang.org/x/oauth2/jws"
|
||||||
)
|
)
|
||||||
|
|
||||||
const enc = encodings.Box
|
|
||||||
|
|
||||||
const (
|
const (
|
||||||
rcloneClientID = "d0374ba6pgmaguie02ge15sv1mllndho"
|
rcloneClientID = "d0374ba6pgmaguie02ge15sv1mllndho"
|
||||||
rcloneEncryptedClientSecret = "sYbJYm99WB8jzeaLPU0OPDMJKIkZvD2qOn3SyEMfiJr03RdtDt3xcZEIudRhbIDL"
|
rcloneEncryptedClientSecret = "sYbJYm99WB8jzeaLPU0OPDMJKIkZvD2qOn3SyEMfiJr03RdtDt3xcZEIudRhbIDL"
|
||||||
minSleep = 10 * time.Millisecond
|
minSleep = 10 * time.Millisecond
|
||||||
maxSleep = 2 * time.Second
|
maxSleep = 2 * time.Second
|
||||||
decayConstant = 2 // bigger for slower decay, exponential
|
decayConstant = 2 // bigger for slower decay, exponential
|
||||||
rootID = "0" // ID of root folder is always this
|
|
||||||
rootURL = "https://api.box.com/2.0"
|
rootURL = "https://api.box.com/2.0"
|
||||||
uploadURL = "https://upload.box.com/api/2.0"
|
uploadURL = "https://upload.box.com/api/2.0"
|
||||||
listChunks = 1000 // chunk size to read directory listings
|
listChunks = 1000 // chunk size to read directory listings
|
||||||
@@ -86,46 +84,36 @@ func init() {
|
|||||||
Name: "box",
|
Name: "box",
|
||||||
Description: "Box",
|
Description: "Box",
|
||||||
NewFs: NewFs,
|
NewFs: NewFs,
|
||||||
Config: func(name string, m configmap.Mapper) {
|
Config: func(ctx context.Context, name string, m configmap.Mapper) {
|
||||||
jsonFile, ok := m.Get("box_config_file")
|
jsonFile, ok := m.Get("box_config_file")
|
||||||
boxSubType, boxSubTypeOk := m.Get("box_sub_type")
|
boxSubType, boxSubTypeOk := m.Get("box_sub_type")
|
||||||
|
boxAccessToken, boxAccessTokenOk := m.Get("access_token")
|
||||||
var err error
|
var err error
|
||||||
|
// If using box config.json, use JWT auth
|
||||||
if ok && boxSubTypeOk && jsonFile != "" && boxSubType != "" {
|
if ok && boxSubTypeOk && jsonFile != "" && boxSubType != "" {
|
||||||
boxConfig, err := getBoxConfig(jsonFile)
|
err = refreshJWTToken(ctx, jsonFile, boxSubType, name, m)
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("Failed to configure token: %v", err)
|
|
||||||
}
|
|
||||||
privateKey, err := getDecryptedPrivateKey(boxConfig)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("Failed to configure token: %v", err)
|
|
||||||
}
|
|
||||||
claims, err := getClaims(boxConfig, boxSubType)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("Failed to configure token: %v", err)
|
|
||||||
}
|
|
||||||
signingHeaders := getSigningHeaders(boxConfig)
|
|
||||||
queryParams := getQueryParams(boxConfig)
|
|
||||||
client := fshttp.NewClient(fs.Config)
|
|
||||||
err = jwtutil.Config("box", name, claims, signingHeaders, queryParams, privateKey, m, client)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Failed to configure token with jwt authentication: %v", err)
|
log.Fatalf("Failed to configure token with jwt authentication: %v", err)
|
||||||
}
|
}
|
||||||
} else {
|
// Else, if not using an access token, use oauth2
|
||||||
err = oauthutil.Config("box", name, m, oauthConfig)
|
} else if boxAccessToken == "" || !boxAccessTokenOk {
|
||||||
|
err = oauthutil.Config(ctx, "box", name, m, oauthConfig, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Failed to configure token with oauth authentication: %v", err)
|
log.Fatalf("Failed to configure token with oauth authentication: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
Options: []fs.Option{{
|
Options: append(oauthutil.SharedOptions, []fs.Option{{
|
||||||
Name: config.ConfigClientID,
|
Name: "root_folder_id",
|
||||||
Help: "Box App Client Id.\nLeave blank normally.",
|
Help: "Fill in for rclone to use a non root folder as its starting point.",
|
||||||
}, {
|
Default: "0",
|
||||||
Name: config.ConfigClientSecret,
|
Advanced: true,
|
||||||
Help: "Box App Client Secret\nLeave blank normally.",
|
|
||||||
}, {
|
}, {
|
||||||
Name: "box_config_file",
|
Name: "box_config_file",
|
||||||
Help: "Box App config.json location\nLeave blank normally.",
|
Help: "Box App config.json location\nLeave blank normally." + env.ShellExpandHelp,
|
||||||
|
}, {
|
||||||
|
Name: "access_token",
|
||||||
|
Help: "Box App Primary Access Token\nLeave blank normally.",
|
||||||
}, {
|
}, {
|
||||||
Name: "box_sub_type",
|
Name: "box_sub_type",
|
||||||
Default: "user",
|
Default: "user",
|
||||||
@@ -146,10 +134,46 @@ func init() {
|
|||||||
Help: "Max number of times to try committing a multipart file.",
|
Help: "Max number of times to try committing a multipart file.",
|
||||||
Default: 100,
|
Default: 100,
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
}},
|
}, {
|
||||||
|
Name: config.ConfigEncoding,
|
||||||
|
Help: config.ConfigEncodingHelp,
|
||||||
|
Advanced: true,
|
||||||
|
// From https://developer.box.com/docs/error-codes#section-400-bad-request :
|
||||||
|
// > Box only supports file or folder names that are 255 characters or less.
|
||||||
|
// > File names containing non-printable ascii, "/" or "\", names with leading
|
||||||
|
// > or trailing spaces, and the special names “.” and “..” are also unsupported.
|
||||||
|
//
|
||||||
|
// Testing revealed names with leading spaces work fine.
|
||||||
|
// Also encode invalid UTF-8 bytes as json doesn't handle them properly.
|
||||||
|
Default: (encoder.Display |
|
||||||
|
encoder.EncodeBackSlash |
|
||||||
|
encoder.EncodeRightSpace |
|
||||||
|
encoder.EncodeInvalidUtf8),
|
||||||
|
}}...),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func refreshJWTToken(ctx context.Context, jsonFile string, boxSubType string, name string, m configmap.Mapper) error {
|
||||||
|
jsonFile = env.ShellExpand(jsonFile)
|
||||||
|
boxConfig, err := getBoxConfig(jsonFile)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to configure token: %v", err)
|
||||||
|
}
|
||||||
|
privateKey, err := getDecryptedPrivateKey(boxConfig)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to configure token: %v", err)
|
||||||
|
}
|
||||||
|
claims, err := getClaims(boxConfig, boxSubType)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to configure token: %v", err)
|
||||||
|
}
|
||||||
|
signingHeaders := getSigningHeaders(boxConfig)
|
||||||
|
queryParams := getQueryParams(boxConfig)
|
||||||
|
client := fshttp.NewClient(ctx)
|
||||||
|
err = jwtutil.Config("box", name, claims, signingHeaders, queryParams, privateKey, m, client)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
func getBoxConfig(configFile string) (boxConfig *api.ConfigJSON, err error) {
|
func getBoxConfig(configFile string) (boxConfig *api.ConfigJSON, err error) {
|
||||||
file, err := ioutil.ReadFile(configFile)
|
file, err := ioutil.ReadFile(configFile)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -172,7 +196,6 @@ func getClaims(boxConfig *api.ConfigJSON, boxSubType string) (claims *jws.ClaimS
|
|||||||
Iss: boxConfig.BoxAppSettings.ClientID,
|
Iss: boxConfig.BoxAppSettings.ClientID,
|
||||||
Sub: boxConfig.EnterpriseID,
|
Sub: boxConfig.EnterpriseID,
|
||||||
Aud: tokenURL,
|
Aud: tokenURL,
|
||||||
Iat: time.Now().Unix(),
|
|
||||||
Exp: time.Now().Add(time.Second * 45).Unix(),
|
Exp: time.Now().Add(time.Second * 45).Unix(),
|
||||||
PrivateClaims: map[string]interface{}{
|
PrivateClaims: map[string]interface{}{
|
||||||
"box_sub_type": boxSubType,
|
"box_sub_type": boxSubType,
|
||||||
@@ -220,8 +243,11 @@ func getDecryptedPrivateKey(boxConfig *api.ConfigJSON) (key *rsa.PrivateKey, err
|
|||||||
|
|
||||||
// Options defines the configuration for this backend
|
// Options defines the configuration for this backend
|
||||||
type Options struct {
|
type Options struct {
|
||||||
UploadCutoff fs.SizeSuffix `config:"upload_cutoff"`
|
UploadCutoff fs.SizeSuffix `config:"upload_cutoff"`
|
||||||
CommitRetries int `config:"commit_retries"`
|
CommitRetries int `config:"commit_retries"`
|
||||||
|
Enc encoder.MultiEncoder `config:"encoding"`
|
||||||
|
RootFolderID string `config:"root_folder_id"`
|
||||||
|
AccessToken string `config:"access_token"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fs represents a remote box
|
// Fs represents a remote box
|
||||||
@@ -273,7 +299,7 @@ func (f *Fs) Features() *fs.Features {
|
|||||||
return f.features
|
return f.features
|
||||||
}
|
}
|
||||||
|
|
||||||
// parsePath parses an box 'url'
|
// parsePath parses a box 'url'
|
||||||
func parsePath(path string) (root string) {
|
func parsePath(path string) (root string) {
|
||||||
root = strings.Trim(path, "/")
|
root = strings.Trim(path, "/")
|
||||||
return
|
return
|
||||||
@@ -304,7 +330,7 @@ func shouldRetry(resp *http.Response, err error) (bool, error) {
|
|||||||
// readMetaDataForPath reads the metadata from the path
|
// readMetaDataForPath reads the metadata from the path
|
||||||
func (f *Fs) readMetaDataForPath(ctx context.Context, path string) (info *api.Item, err error) {
|
func (f *Fs) readMetaDataForPath(ctx context.Context, path string) (info *api.Item, err error) {
|
||||||
// defer fs.Trace(f, "path=%q", path)("info=%+v, err=%v", &info, &err)
|
// defer fs.Trace(f, "path=%q", path)("info=%+v, err=%v", &info, &err)
|
||||||
leaf, directoryID, err := f.dirCache.FindRootAndPath(ctx, path, false)
|
leaf, directoryID, err := f.dirCache.FindPath(ctx, path, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err == fs.ErrorDirNotFound {
|
if err == fs.ErrorDirNotFound {
|
||||||
return nil, fs.ErrorObjectNotFound
|
return nil, fs.ErrorObjectNotFound
|
||||||
@@ -313,7 +339,7 @@ func (f *Fs) readMetaDataForPath(ctx context.Context, path string) (info *api.It
|
|||||||
}
|
}
|
||||||
|
|
||||||
found, err := f.listAll(ctx, directoryID, false, true, func(item *api.Item) bool {
|
found, err := f.listAll(ctx, directoryID, false, true, func(item *api.Item) bool {
|
||||||
if item.Name == leaf {
|
if strings.EqualFold(item.Name, leaf) {
|
||||||
info = item
|
info = item
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@@ -346,8 +372,7 @@ func errorHandler(resp *http.Response) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// NewFs constructs an Fs from the path, container:path
|
// NewFs constructs an Fs from the path, container:path
|
||||||
func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {
|
||||||
ctx := context.Background()
|
|
||||||
// Parse config into Options struct
|
// Parse config into Options struct
|
||||||
opt := new(Options)
|
opt := new(Options)
|
||||||
err := configstruct.Set(m, opt)
|
err := configstruct.Set(m, opt)
|
||||||
@@ -360,32 +385,60 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
root = parsePath(root)
|
root = parsePath(root)
|
||||||
oAuthClient, ts, err := oauthutil.NewClient(name, m, oauthConfig)
|
|
||||||
if err != nil {
|
client := fshttp.NewClient(ctx)
|
||||||
return nil, errors.Wrap(err, "failed to configure Box")
|
var ts *oauthutil.TokenSource
|
||||||
|
// If not using an accessToken, create an oauth client and tokensource
|
||||||
|
if opt.AccessToken == "" {
|
||||||
|
client, ts, err = oauthutil.NewClient(ctx, name, m, oauthConfig)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "failed to configure Box")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ci := fs.GetConfig(ctx)
|
||||||
f := &Fs{
|
f := &Fs{
|
||||||
name: name,
|
name: name,
|
||||||
root: root,
|
root: root,
|
||||||
opt: *opt,
|
opt: *opt,
|
||||||
srv: rest.NewClient(oAuthClient).SetRoot(rootURL),
|
srv: rest.NewClient(client).SetRoot(rootURL),
|
||||||
pacer: fs.NewPacer(pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
|
pacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
|
||||||
uploadToken: pacer.NewTokenDispenser(fs.Config.Transfers),
|
uploadToken: pacer.NewTokenDispenser(ci.Transfers),
|
||||||
}
|
}
|
||||||
f.features = (&fs.Features{
|
f.features = (&fs.Features{
|
||||||
CaseInsensitive: true,
|
CaseInsensitive: true,
|
||||||
CanHaveEmptyDirectories: true,
|
CanHaveEmptyDirectories: true,
|
||||||
}).Fill(f)
|
}).Fill(ctx, f)
|
||||||
f.srv.SetErrorHandler(errorHandler)
|
f.srv.SetErrorHandler(errorHandler)
|
||||||
|
|
||||||
// Renew the token in the background
|
// If using an accessToken, set the Authorization header
|
||||||
f.tokenRenewer = oauthutil.NewRenew(f.String(), ts, func() error {
|
if f.opt.AccessToken != "" {
|
||||||
_, err := f.readMetaDataForPath(ctx, "")
|
f.srv.SetHeader("Authorization", "Bearer "+f.opt.AccessToken)
|
||||||
return err
|
}
|
||||||
})
|
|
||||||
|
|
||||||
// Get rootID
|
jsonFile, ok := m.Get("box_config_file")
|
||||||
|
boxSubType, boxSubTypeOk := m.Get("box_sub_type")
|
||||||
|
|
||||||
|
if ts != nil {
|
||||||
|
// If using box config.json and JWT, renewing should just refresh the token and
|
||||||
|
// should do so whether there are uploads pending or not.
|
||||||
|
if ok && boxSubTypeOk && jsonFile != "" && boxSubType != "" {
|
||||||
|
f.tokenRenewer = oauthutil.NewRenew(f.String(), ts, func() error {
|
||||||
|
err := refreshJWTToken(ctx, jsonFile, boxSubType, name, m)
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
f.tokenRenewer.Start()
|
||||||
|
} else {
|
||||||
|
// Renew the token in the background
|
||||||
|
f.tokenRenewer = oauthutil.NewRenew(f.String(), ts, func() error {
|
||||||
|
_, err := f.readMetaDataForPath(ctx, "")
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get rootFolderID
|
||||||
|
rootID := f.opt.RootFolderID
|
||||||
f.dirCache = dircache.New(root, rootID, f)
|
f.dirCache = dircache.New(root, rootID, f)
|
||||||
|
|
||||||
// Find the current root
|
// Find the current root
|
||||||
@@ -410,7 +463,7 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
}
|
}
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
f.features.Fill(&tempF)
|
f.features.Fill(ctx, &tempF)
|
||||||
// XXX: update the old f here instead of returning tempF, since
|
// XXX: update the old f here instead of returning tempF, since
|
||||||
// `features` were already filled with functions having *f as a receiver.
|
// `features` were already filled with functions having *f as a receiver.
|
||||||
// See https://github.com/rclone/rclone/issues/2182
|
// See https://github.com/rclone/rclone/issues/2182
|
||||||
@@ -461,7 +514,7 @@ func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) {
|
|||||||
func (f *Fs) FindLeaf(ctx context.Context, pathID, leaf string) (pathIDOut string, found bool, err error) {
|
func (f *Fs) FindLeaf(ctx context.Context, pathID, leaf string) (pathIDOut string, found bool, err error) {
|
||||||
// Find the leaf in pathID
|
// Find the leaf in pathID
|
||||||
found, err = f.listAll(ctx, pathID, true, false, func(item *api.Item) bool {
|
found, err = f.listAll(ctx, pathID, true, false, func(item *api.Item) bool {
|
||||||
if item.Name == leaf {
|
if strings.EqualFold(item.Name, leaf) {
|
||||||
pathIDOut = item.ID
|
pathIDOut = item.ID
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@@ -488,7 +541,7 @@ func (f *Fs) CreateDir(ctx context.Context, pathID, leaf string) (newID string,
|
|||||||
Parameters: fieldsValue(),
|
Parameters: fieldsValue(),
|
||||||
}
|
}
|
||||||
mkdir := api.CreateFolder{
|
mkdir := api.CreateFolder{
|
||||||
Name: enc.FromStandardName(leaf),
|
Name: f.opt.Enc.FromStandardName(leaf),
|
||||||
Parent: api.Parent{
|
Parent: api.Parent{
|
||||||
ID: pathID,
|
ID: pathID,
|
||||||
},
|
},
|
||||||
@@ -554,7 +607,7 @@ OUTER:
|
|||||||
if item.ItemStatus != api.ItemStatusActive {
|
if item.ItemStatus != api.ItemStatusActive {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
item.Name = enc.ToStandardName(item.Name)
|
item.Name = f.opt.Enc.ToStandardName(item.Name)
|
||||||
if fn(item) {
|
if fn(item) {
|
||||||
found = true
|
found = true
|
||||||
break OUTER
|
break OUTER
|
||||||
@@ -578,10 +631,6 @@ OUTER:
|
|||||||
// This should return ErrDirNotFound if the directory isn't
|
// This should return ErrDirNotFound if the directory isn't
|
||||||
// found.
|
// found.
|
||||||
func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) {
|
func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) {
|
||||||
err = f.dirCache.FindRoot(ctx, false)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
directoryID, err := f.dirCache.FindDir(ctx, dir, false)
|
directoryID, err := f.dirCache.FindDir(ctx, dir, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -622,7 +671,7 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
|
|||||||
// Used to create new objects
|
// Used to create new objects
|
||||||
func (f *Fs) createObject(ctx context.Context, remote string, modTime time.Time, size int64) (o *Object, leaf string, directoryID string, err error) {
|
func (f *Fs) createObject(ctx context.Context, remote string, modTime time.Time, size int64) (o *Object, leaf string, directoryID string, err error) {
|
||||||
// Create the directory for the object if it doesn't exist
|
// Create the directory for the object if it doesn't exist
|
||||||
leaf, directoryID, err = f.dirCache.FindRootAndPath(ctx, remote, true)
|
leaf, directoryID, err = f.dirCache.FindPath(ctx, remote, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -678,13 +727,7 @@ func (f *Fs) PutUnchecked(ctx context.Context, in io.Reader, src fs.ObjectInfo,
|
|||||||
|
|
||||||
// Mkdir creates the container if it doesn't exist
|
// Mkdir creates the container if it doesn't exist
|
||||||
func (f *Fs) Mkdir(ctx context.Context, dir string) error {
|
func (f *Fs) Mkdir(ctx context.Context, dir string) error {
|
||||||
err := f.dirCache.FindRoot(ctx, true)
|
_, err := f.dirCache.FindDir(ctx, dir, true)
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if dir != "" {
|
|
||||||
_, err = f.dirCache.FindDir(ctx, dir, true)
|
|
||||||
}
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -709,10 +752,6 @@ func (f *Fs) purgeCheck(ctx context.Context, dir string, check bool) error {
|
|||||||
return errors.New("can't purge root directory")
|
return errors.New("can't purge root directory")
|
||||||
}
|
}
|
||||||
dc := f.dirCache
|
dc := f.dirCache
|
||||||
err := dc.FindRoot(ctx, false)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
rootID, err := dc.FindDir(ctx, dir, false)
|
rootID, err := dc.FindDir(ctx, dir, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -752,7 +791,7 @@ func (f *Fs) Precision() time.Duration {
|
|||||||
return time.Second
|
return time.Second
|
||||||
}
|
}
|
||||||
|
|
||||||
// Copy src to this remote using server side copy operations.
|
// Copy src to this remote using server-side copy operations.
|
||||||
//
|
//
|
||||||
// This is stored with the remote path given
|
// This is stored with the remote path given
|
||||||
//
|
//
|
||||||
@@ -791,7 +830,7 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
Parameters: fieldsValue(),
|
Parameters: fieldsValue(),
|
||||||
}
|
}
|
||||||
copyFile := api.CopyFile{
|
copyFile := api.CopyFile{
|
||||||
Name: enc.FromStandardName(leaf),
|
Name: f.opt.Enc.FromStandardName(leaf),
|
||||||
Parent: api.Parent{
|
Parent: api.Parent{
|
||||||
ID: directoryID,
|
ID: directoryID,
|
||||||
},
|
},
|
||||||
@@ -817,8 +856,8 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
// Optional interface: Only implement this if you have a way of
|
// Optional interface: Only implement this if you have a way of
|
||||||
// deleting all the files quicker than just running Remove() on the
|
// deleting all the files quicker than just running Remove() on the
|
||||||
// result of List()
|
// result of List()
|
||||||
func (f *Fs) Purge(ctx context.Context) error {
|
func (f *Fs) Purge(ctx context.Context, dir string) error {
|
||||||
return f.purgeCheck(ctx, "", false)
|
return f.purgeCheck(ctx, dir, false)
|
||||||
}
|
}
|
||||||
|
|
||||||
// move a file or folder
|
// move a file or folder
|
||||||
@@ -830,7 +869,7 @@ func (f *Fs) move(ctx context.Context, endpoint, id, leaf, directoryID string) (
|
|||||||
Parameters: fieldsValue(),
|
Parameters: fieldsValue(),
|
||||||
}
|
}
|
||||||
move := api.UpdateFileMove{
|
move := api.UpdateFileMove{
|
||||||
Name: enc.FromStandardName(leaf),
|
Name: f.opt.Enc.FromStandardName(leaf),
|
||||||
Parent: api.Parent{
|
Parent: api.Parent{
|
||||||
ID: directoryID,
|
ID: directoryID,
|
||||||
},
|
},
|
||||||
@@ -846,7 +885,31 @@ func (f *Fs) move(ctx context.Context, endpoint, id, leaf, directoryID string) (
|
|||||||
return info, nil
|
return info, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Move src to this remote using server side move operations.
|
// About gets quota information
|
||||||
|
func (f *Fs) About(ctx context.Context) (usage *fs.Usage, err error) {
|
||||||
|
opts := rest.Opts{
|
||||||
|
Method: "GET",
|
||||||
|
Path: "/users/me",
|
||||||
|
}
|
||||||
|
var user api.User
|
||||||
|
var resp *http.Response
|
||||||
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
|
resp, err = f.srv.CallJSON(ctx, &opts, nil, &user)
|
||||||
|
return shouldRetry(resp, err)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "failed to read user info")
|
||||||
|
}
|
||||||
|
// FIXME max upload size would be useful to use in Update
|
||||||
|
usage = &fs.Usage{
|
||||||
|
Used: fs.NewUsageValue(user.SpaceUsed), // bytes in use
|
||||||
|
Total: fs.NewUsageValue(user.SpaceAmount), // bytes total
|
||||||
|
Free: fs.NewUsageValue(user.SpaceAmount - user.SpaceUsed), // bytes free
|
||||||
|
}
|
||||||
|
return usage, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Move src to this remote using server-side move operations.
|
||||||
//
|
//
|
||||||
// This is stored with the remote path given
|
// This is stored with the remote path given
|
||||||
//
|
//
|
||||||
@@ -882,7 +945,7 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DirMove moves src, srcRemote to this remote at dstRemote
|
// DirMove moves src, srcRemote to this remote at dstRemote
|
||||||
// using server side move operations.
|
// using server-side move operations.
|
||||||
//
|
//
|
||||||
// Will only be called if src.Fs().Name() == f.Name()
|
// Will only be called if src.Fs().Name() == f.Name()
|
||||||
//
|
//
|
||||||
@@ -895,64 +958,14 @@ func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string
|
|||||||
fs.Debugf(srcFs, "Can't move directory - not same remote type")
|
fs.Debugf(srcFs, "Can't move directory - not same remote type")
|
||||||
return fs.ErrorCantDirMove
|
return fs.ErrorCantDirMove
|
||||||
}
|
}
|
||||||
srcPath := path.Join(srcFs.root, srcRemote)
|
|
||||||
dstPath := path.Join(f.root, dstRemote)
|
|
||||||
|
|
||||||
// Refuse to move to or from the root
|
srcID, _, _, dstDirectoryID, dstLeaf, err := f.dirCache.DirMove(ctx, srcFs.dirCache, srcFs.root, srcRemote, f.root, dstRemote)
|
||||||
if srcPath == "" || dstPath == "" {
|
|
||||||
fs.Debugf(src, "DirMove error: Can't move root")
|
|
||||||
return errors.New("can't move root directory")
|
|
||||||
}
|
|
||||||
|
|
||||||
// find the root src directory
|
|
||||||
err := srcFs.dirCache.FindRoot(ctx, false)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// find the root dst directory
|
|
||||||
if dstRemote != "" {
|
|
||||||
err = f.dirCache.FindRoot(ctx, true)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if f.dirCache.FoundRoot() {
|
|
||||||
return fs.ErrorDirExists
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Find ID of dst parent, creating subdirs if necessary
|
|
||||||
var leaf, directoryID string
|
|
||||||
findPath := dstRemote
|
|
||||||
if dstRemote == "" {
|
|
||||||
findPath = f.root
|
|
||||||
}
|
|
||||||
leaf, directoryID, err = f.dirCache.FindPath(ctx, findPath, true)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check destination does not exist
|
|
||||||
if dstRemote != "" {
|
|
||||||
_, err = f.dirCache.FindDir(ctx, dstRemote, false)
|
|
||||||
if err == fs.ErrorDirNotFound {
|
|
||||||
// OK
|
|
||||||
} else if err != nil {
|
|
||||||
return err
|
|
||||||
} else {
|
|
||||||
return fs.ErrorDirExists
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Find ID of src
|
|
||||||
srcID, err := srcFs.dirCache.FindDir(ctx, srcRemote, false)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Do the move
|
// Do the move
|
||||||
_, err = f.move(ctx, "/folders/", srcID, leaf, directoryID)
|
_, err = f.move(ctx, "/folders/", srcID, dstLeaf, dstDirectoryID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -961,7 +974,7 @@ func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string
|
|||||||
}
|
}
|
||||||
|
|
||||||
// PublicLink adds a "readable by anyone with link" permission on the given file or folder.
|
// PublicLink adds a "readable by anyone with link" permission on the given file or folder.
|
||||||
func (f *Fs) PublicLink(ctx context.Context, remote string) (string, error) {
|
func (f *Fs) PublicLink(ctx context.Context, remote string, expire fs.Duration, unlink bool) (string, error) {
|
||||||
id, err := f.dirCache.FindDir(ctx, remote, false)
|
id, err := f.dirCache.FindDir(ctx, remote, false)
|
||||||
var opts rest.Opts
|
var opts rest.Opts
|
||||||
if err == nil {
|
if err == nil {
|
||||||
@@ -1000,6 +1013,66 @@ func (f *Fs) PublicLink(ctx context.Context, remote string) (string, error) {
|
|||||||
return info.SharedLink.URL, err
|
return info.SharedLink.URL, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// deletePermanently permanently deletes a trashed file
|
||||||
|
func (f *Fs) deletePermanently(ctx context.Context, itemType, id string) error {
|
||||||
|
opts := rest.Opts{
|
||||||
|
Method: "DELETE",
|
||||||
|
NoResponse: true,
|
||||||
|
}
|
||||||
|
if itemType == api.ItemTypeFile {
|
||||||
|
opts.Path = "/files/" + id + "/trash"
|
||||||
|
} else {
|
||||||
|
opts.Path = "/folders/" + id + "/trash"
|
||||||
|
}
|
||||||
|
return f.pacer.Call(func() (bool, error) {
|
||||||
|
resp, err := f.srv.Call(ctx, &opts)
|
||||||
|
return shouldRetry(resp, err)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// CleanUp empties the trash
|
||||||
|
func (f *Fs) CleanUp(ctx context.Context) (err error) {
|
||||||
|
opts := rest.Opts{
|
||||||
|
Method: "GET",
|
||||||
|
Path: "/folders/trash/items",
|
||||||
|
Parameters: url.Values{
|
||||||
|
"fields": []string{"type", "id"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
opts.Parameters.Set("limit", strconv.Itoa(listChunks))
|
||||||
|
offset := 0
|
||||||
|
for {
|
||||||
|
opts.Parameters.Set("offset", strconv.Itoa(offset))
|
||||||
|
|
||||||
|
var result api.FolderItems
|
||||||
|
var resp *http.Response
|
||||||
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
|
resp, err = f.srv.CallJSON(ctx, &opts, nil, &result)
|
||||||
|
return shouldRetry(resp, err)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "couldn't list trash")
|
||||||
|
}
|
||||||
|
for i := range result.Entries {
|
||||||
|
item := &result.Entries[i]
|
||||||
|
if item.Type == api.ItemTypeFolder || item.Type == api.ItemTypeFile {
|
||||||
|
err := f.deletePermanently(ctx, item.Type, item.ID)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "failed to delete file")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
fs.Debugf(f, "Ignoring %q - unknown type %q", item.Name, item.Type)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
offset += result.Limit
|
||||||
|
if offset >= result.TotalCount {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// DirCacheFlush resets the directory cache - used in testing as an
|
// DirCacheFlush resets the directory cache - used in testing as an
|
||||||
// optional interface
|
// optional interface
|
||||||
func (f *Fs) DirCacheFlush() {
|
func (f *Fs) DirCacheFlush() {
|
||||||
@@ -1153,9 +1226,9 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.Read
|
|||||||
// upload does a single non-multipart upload
|
// upload does a single non-multipart upload
|
||||||
//
|
//
|
||||||
// This is recommended for less than 50 MB of content
|
// This is recommended for less than 50 MB of content
|
||||||
func (o *Object) upload(ctx context.Context, in io.Reader, leaf, directoryID string, modTime time.Time) (err error) {
|
func (o *Object) upload(ctx context.Context, in io.Reader, leaf, directoryID string, modTime time.Time, options ...fs.OpenOption) (err error) {
|
||||||
upload := api.UploadFile{
|
upload := api.UploadFile{
|
||||||
Name: enc.FromStandardName(leaf),
|
Name: o.fs.opt.Enc.FromStandardName(leaf),
|
||||||
ContentModifiedAt: api.Time(modTime),
|
ContentModifiedAt: api.Time(modTime),
|
||||||
ContentCreatedAt: api.Time(modTime),
|
ContentCreatedAt: api.Time(modTime),
|
||||||
Parent: api.Parent{
|
Parent: api.Parent{
|
||||||
@@ -1172,6 +1245,7 @@ func (o *Object) upload(ctx context.Context, in io.Reader, leaf, directoryID str
|
|||||||
MultipartContentName: "contents",
|
MultipartContentName: "contents",
|
||||||
MultipartFileName: upload.Name,
|
MultipartFileName: upload.Name,
|
||||||
RootURL: uploadURL,
|
RootURL: uploadURL,
|
||||||
|
Options: options,
|
||||||
}
|
}
|
||||||
// If object has an ID then it is existing so create a new version
|
// If object has an ID then it is existing so create a new version
|
||||||
if o.id != "" {
|
if o.id != "" {
|
||||||
@@ -1198,24 +1272,26 @@ func (o *Object) upload(ctx context.Context, in io.Reader, leaf, directoryID str
|
|||||||
//
|
//
|
||||||
// The new object may have been created if an error is returned
|
// The new object may have been created if an error is returned
|
||||||
func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (err error) {
|
func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (err error) {
|
||||||
o.fs.tokenRenewer.Start()
|
if o.fs.tokenRenewer != nil {
|
||||||
defer o.fs.tokenRenewer.Stop()
|
o.fs.tokenRenewer.Start()
|
||||||
|
defer o.fs.tokenRenewer.Stop()
|
||||||
|
}
|
||||||
|
|
||||||
size := src.Size()
|
size := src.Size()
|
||||||
modTime := src.ModTime(ctx)
|
modTime := src.ModTime(ctx)
|
||||||
remote := o.Remote()
|
remote := o.Remote()
|
||||||
|
|
||||||
// Create the directory for the object if it doesn't exist
|
// Create the directory for the object if it doesn't exist
|
||||||
leaf, directoryID, err := o.fs.dirCache.FindRootAndPath(ctx, remote, true)
|
leaf, directoryID, err := o.fs.dirCache.FindPath(ctx, remote, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Upload with simple or multipart
|
// Upload with simple or multipart
|
||||||
if size <= int64(o.fs.opt.UploadCutoff) {
|
if size <= int64(o.fs.opt.UploadCutoff) {
|
||||||
err = o.upload(ctx, in, leaf, directoryID, modTime)
|
err = o.upload(ctx, in, leaf, directoryID, modTime, options...)
|
||||||
} else {
|
} else {
|
||||||
err = o.uploadMultipart(ctx, in, leaf, directoryID, size, modTime)
|
err = o.uploadMultipart(ctx, in, leaf, directoryID, size, modTime, options...)
|
||||||
}
|
}
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -1236,10 +1312,12 @@ var (
|
|||||||
_ fs.Purger = (*Fs)(nil)
|
_ fs.Purger = (*Fs)(nil)
|
||||||
_ fs.PutStreamer = (*Fs)(nil)
|
_ fs.PutStreamer = (*Fs)(nil)
|
||||||
_ fs.Copier = (*Fs)(nil)
|
_ fs.Copier = (*Fs)(nil)
|
||||||
|
_ fs.Abouter = (*Fs)(nil)
|
||||||
_ fs.Mover = (*Fs)(nil)
|
_ fs.Mover = (*Fs)(nil)
|
||||||
_ fs.DirMover = (*Fs)(nil)
|
_ fs.DirMover = (*Fs)(nil)
|
||||||
_ fs.DirCacheFlusher = (*Fs)(nil)
|
_ fs.DirCacheFlusher = (*Fs)(nil)
|
||||||
_ fs.PublicLinker = (*Fs)(nil)
|
_ fs.PublicLinker = (*Fs)(nil)
|
||||||
|
_ fs.CleanUpper = (*Fs)(nil)
|
||||||
_ fs.Object = (*Object)(nil)
|
_ fs.Object = (*Object)(nil)
|
||||||
_ fs.IDer = (*Object)(nil)
|
_ fs.IDer = (*Object)(nil)
|
||||||
)
|
)
|
||||||
+13
-13
@@ -1,4 +1,4 @@
|
|||||||
// multpart upload for box
|
// multipart upload for box
|
||||||
|
|
||||||
package box
|
package box
|
||||||
|
|
||||||
@@ -19,6 +19,7 @@ import (
|
|||||||
"github.com/rclone/rclone/backend/box/api"
|
"github.com/rclone/rclone/backend/box/api"
|
||||||
"github.com/rclone/rclone/fs"
|
"github.com/rclone/rclone/fs"
|
||||||
"github.com/rclone/rclone/fs/accounting"
|
"github.com/rclone/rclone/fs/accounting"
|
||||||
|
"github.com/rclone/rclone/lib/atexit"
|
||||||
"github.com/rclone/rclone/lib/rest"
|
"github.com/rclone/rclone/lib/rest"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -38,7 +39,7 @@ func (o *Object) createUploadSession(ctx context.Context, leaf, directoryID stri
|
|||||||
} else {
|
} else {
|
||||||
opts.Path = "/files/upload_sessions"
|
opts.Path = "/files/upload_sessions"
|
||||||
request.FolderID = directoryID
|
request.FolderID = directoryID
|
||||||
request.FileName = enc.FromStandardName(leaf)
|
request.FileName = o.fs.opt.Enc.FromStandardName(leaf)
|
||||||
}
|
}
|
||||||
var resp *http.Response
|
var resp *http.Response
|
||||||
err = o.fs.pacer.Call(func() (bool, error) {
|
err = o.fs.pacer.Call(func() (bool, error) {
|
||||||
@@ -54,7 +55,7 @@ func sha1Digest(digest []byte) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// uploadPart uploads a part in an upload session
|
// uploadPart uploads a part in an upload session
|
||||||
func (o *Object) uploadPart(ctx context.Context, SessionID string, offset, totalSize int64, chunk []byte, wrap accounting.WrapFn) (response *api.UploadPartResponse, err error) {
|
func (o *Object) uploadPart(ctx context.Context, SessionID string, offset, totalSize int64, chunk []byte, wrap accounting.WrapFn, options ...fs.OpenOption) (response *api.UploadPartResponse, err error) {
|
||||||
chunkSize := int64(len(chunk))
|
chunkSize := int64(len(chunk))
|
||||||
sha1sum := sha1.Sum(chunk)
|
sha1sum := sha1.Sum(chunk)
|
||||||
opts := rest.Opts{
|
opts := rest.Opts{
|
||||||
@@ -64,6 +65,7 @@ func (o *Object) uploadPart(ctx context.Context, SessionID string, offset, total
|
|||||||
ContentType: "application/octet-stream",
|
ContentType: "application/octet-stream",
|
||||||
ContentLength: &chunkSize,
|
ContentLength: &chunkSize,
|
||||||
ContentRange: fmt.Sprintf("bytes %d-%d/%d", offset, offset+chunkSize-1, totalSize),
|
ContentRange: fmt.Sprintf("bytes %d-%d/%d", offset, offset+chunkSize-1, totalSize),
|
||||||
|
Options: options,
|
||||||
ExtraHeaders: map[string]string{
|
ExtraHeaders: map[string]string{
|
||||||
"Digest": sha1Digest(sha1sum[:]),
|
"Digest": sha1Digest(sha1sum[:]),
|
||||||
},
|
},
|
||||||
@@ -171,7 +173,7 @@ func (o *Object) abortUpload(ctx context.Context, SessionID string) (err error)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// uploadMultipart uploads a file using multipart upload
|
// uploadMultipart uploads a file using multipart upload
|
||||||
func (o *Object) uploadMultipart(ctx context.Context, in io.Reader, leaf, directoryID string, size int64, modTime time.Time) (err error) {
|
func (o *Object) uploadMultipart(ctx context.Context, in io.Reader, leaf, directoryID string, size int64, modTime time.Time, options ...fs.OpenOption) (err error) {
|
||||||
// Create upload session
|
// Create upload session
|
||||||
session, err := o.createUploadSession(ctx, leaf, directoryID, size)
|
session, err := o.createUploadSession(ctx, leaf, directoryID, size)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -181,15 +183,13 @@ func (o *Object) uploadMultipart(ctx context.Context, in io.Reader, leaf, direct
|
|||||||
fs.Debugf(o, "Multipart upload session started for %d parts of size %v", session.TotalParts, fs.SizeSuffix(chunkSize))
|
fs.Debugf(o, "Multipart upload session started for %d parts of size %v", session.TotalParts, fs.SizeSuffix(chunkSize))
|
||||||
|
|
||||||
// Cancel the session if something went wrong
|
// Cancel the session if something went wrong
|
||||||
defer func() {
|
defer atexit.OnError(&err, func() {
|
||||||
if err != nil {
|
fs.Debugf(o, "Cancelling multipart upload: %v", err)
|
||||||
fs.Debugf(o, "Cancelling multipart upload: %v", err)
|
cancelErr := o.abortUpload(ctx, session.ID)
|
||||||
cancelErr := o.abortUpload(ctx, session.ID)
|
if cancelErr != nil {
|
||||||
if cancelErr != nil {
|
fs.Logf(o, "Failed to cancel multipart upload: %v", cancelErr)
|
||||||
fs.Logf(o, "Failed to cancel multipart upload: %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}()
|
})()
|
||||||
|
|
||||||
// unwrap the accounting from the input, we use wrap to put it
|
// unwrap the accounting from the input, we use wrap to put it
|
||||||
// back on after the buffering
|
// back on after the buffering
|
||||||
@@ -236,7 +236,7 @@ outer:
|
|||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
defer o.fs.uploadToken.Put()
|
defer o.fs.uploadToken.Put()
|
||||||
fs.Debugf(o, "Uploading part %d/%d offset %v/%v part size %v", part+1, session.TotalParts, fs.SizeSuffix(position), fs.SizeSuffix(size), fs.SizeSuffix(chunkSize))
|
fs.Debugf(o, "Uploading part %d/%d offset %v/%v part size %v", part+1, session.TotalParts, fs.SizeSuffix(position), fs.SizeSuffix(size), fs.SizeSuffix(chunkSize))
|
||||||
partResponse, err := o.uploadPart(ctx, session.ID, position, size, buf, wrap)
|
partResponse, err := o.uploadPart(ctx, session.ID, position, size, buf, wrap, options...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
err = errors.Wrap(err, "multipart upload failed to upload part")
|
err = errors.Wrap(err, "multipart upload failed to upload part")
|
||||||
select {
|
select {
|
||||||
|
|||||||
Vendored
+81
-30
@@ -1,4 +1,4 @@
|
|||||||
// +build !plan9
|
// +build !plan9,!js
|
||||||
|
|
||||||
package cache
|
package cache
|
||||||
|
|
||||||
@@ -65,9 +65,10 @@ func init() {
|
|||||||
Name: "cache",
|
Name: "cache",
|
||||||
Description: "Cache a remote",
|
Description: "Cache a remote",
|
||||||
NewFs: NewFs,
|
NewFs: NewFs,
|
||||||
|
CommandHelp: commandHelp,
|
||||||
Options: []fs.Option{{
|
Options: []fs.Option{{
|
||||||
Name: "remote",
|
Name: "remote",
|
||||||
Help: "Remote to cache.\nNormally should contain a ':' and a path, eg \"myremote:path/to/dir\",\n\"myremote:bucket\" or maybe \"myremote:\" (not recommended).",
|
Help: "Remote to cache.\nNormally should contain a ':' and a path, e.g. \"myremote:path/to/dir\",\n\"myremote:bucket\" or maybe \"myremote:\" (not recommended).",
|
||||||
Required: true,
|
Required: true,
|
||||||
}, {
|
}, {
|
||||||
Name: "plex_url",
|
Name: "plex_url",
|
||||||
@@ -86,7 +87,7 @@ func init() {
|
|||||||
Advanced: true,
|
Advanced: true,
|
||||||
}, {
|
}, {
|
||||||
Name: "plex_insecure",
|
Name: "plex_insecure",
|
||||||
Help: "Skip all certificate verifications when connecting to the Plex server",
|
Help: "Skip all certificate verification when connecting to the Plex server",
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
}, {
|
}, {
|
||||||
Name: "chunk_size",
|
Name: "chunk_size",
|
||||||
@@ -108,7 +109,7 @@ will need to be cleared or unexpected EOF errors will occur.`,
|
|||||||
}},
|
}},
|
||||||
}, {
|
}, {
|
||||||
Name: "info_age",
|
Name: "info_age",
|
||||||
Help: `How long to cache file structure information (directory listings, file size, times etc).
|
Help: `How long to cache file structure information (directory listings, file size, times, etc.).
|
||||||
If all write operations are done through the cache then you can safely make
|
If all write operations are done through the cache then you can safely make
|
||||||
this value very large as the cache store will also be updated in real time.`,
|
this value very large as the cache store will also be updated in real time.`,
|
||||||
Default: DefCacheInfoAge,
|
Default: DefCacheInfoAge,
|
||||||
@@ -338,8 +339,8 @@ func parseRootPath(path string) (string, error) {
|
|||||||
return strings.Trim(path, "/"), nil
|
return strings.Trim(path, "/"), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewFs constructs a Fs from the path, container:path
|
// NewFs constructs an Fs from the path, container:path
|
||||||
func NewFs(name, rootPath string, m configmap.Mapper) (fs.Fs, error) {
|
func NewFs(ctx context.Context, name, rootPath string, m configmap.Mapper) (fs.Fs, error) {
|
||||||
// Parse config into Options struct
|
// Parse config into Options struct
|
||||||
opt := new(Options)
|
opt := new(Options)
|
||||||
err := configstruct.Set(m, opt)
|
err := configstruct.Set(m, opt)
|
||||||
@@ -360,15 +361,10 @@ func NewFs(name, rootPath string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
return nil, errors.Wrapf(err, "failed to clean root path %q", rootPath)
|
return nil, errors.Wrapf(err, "failed to clean root path %q", rootPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
wInfo, wName, wPath, wConfig, err := fs.ConfigFs(opt.Remote)
|
remotePath := fspath.JoinRootPath(opt.Remote, rootPath)
|
||||||
if err != nil {
|
wrappedFs, wrapErr := cache.Get(ctx, remotePath)
|
||||||
return nil, errors.Wrapf(err, "failed to parse remote %q to wrap", opt.Remote)
|
|
||||||
}
|
|
||||||
|
|
||||||
remotePath := fspath.JoinRootPath(wPath, rootPath)
|
|
||||||
wrappedFs, wrapErr := wInfo.NewFs(wName, remotePath, wConfig)
|
|
||||||
if wrapErr != nil && wrapErr != fs.ErrorIsFile {
|
if wrapErr != nil && wrapErr != fs.ErrorIsFile {
|
||||||
return nil, errors.Wrapf(wrapErr, "failed to make remote %s:%s to wrap", wName, remotePath)
|
return nil, errors.Wrapf(wrapErr, "failed to make remote %q to wrap", remotePath)
|
||||||
}
|
}
|
||||||
var fsErr error
|
var fsErr error
|
||||||
fs.Debugf(name, "wrapped %v:%v at root %v", wrappedFs.Name(), wrappedFs.Root(), rpath)
|
fs.Debugf(name, "wrapped %v:%v at root %v", wrappedFs.Name(), wrappedFs.Root(), rpath)
|
||||||
@@ -389,6 +385,7 @@ func NewFs(name, rootPath string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
cleanupChan: make(chan bool, 1),
|
cleanupChan: make(chan bool, 1),
|
||||||
notifiedRemotes: make(map[string]bool),
|
notifiedRemotes: make(map[string]bool),
|
||||||
}
|
}
|
||||||
|
cache.PinUntilFinalized(f.Fs, f)
|
||||||
f.rateLimiter = rate.NewLimiter(rate.Limit(float64(opt.Rps)), opt.TotalWorkers)
|
f.rateLimiter = rate.NewLimiter(rate.Limit(float64(opt.Rps)), opt.TotalWorkers)
|
||||||
|
|
||||||
f.plexConnector = &plexConnector{}
|
f.plexConnector = &plexConnector{}
|
||||||
@@ -482,7 +479,7 @@ func NewFs(name, rootPath string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
return nil, errors.Wrapf(err, "failed to create cache directory %v", f.opt.TempWritePath)
|
return nil, errors.Wrapf(err, "failed to create cache directory %v", f.opt.TempWritePath)
|
||||||
}
|
}
|
||||||
f.opt.TempWritePath = filepath.ToSlash(f.opt.TempWritePath)
|
f.opt.TempWritePath = filepath.ToSlash(f.opt.TempWritePath)
|
||||||
f.tempFs, err = cache.Get(f.opt.TempWritePath)
|
f.tempFs, err = cache.Get(ctx, f.opt.TempWritePath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrapf(err, "failed to create temp fs: %v", err)
|
return nil, errors.Wrapf(err, "failed to create temp fs: %v", err)
|
||||||
}
|
}
|
||||||
@@ -509,19 +506,16 @@ func NewFs(name, rootPath string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
if doChangeNotify := wrappedFs.Features().ChangeNotify; doChangeNotify != nil {
|
if doChangeNotify := wrappedFs.Features().ChangeNotify; doChangeNotify != nil {
|
||||||
pollInterval := make(chan time.Duration, 1)
|
pollInterval := make(chan time.Duration, 1)
|
||||||
pollInterval <- time.Duration(f.opt.ChunkCleanInterval)
|
pollInterval <- time.Duration(f.opt.ChunkCleanInterval)
|
||||||
doChangeNotify(context.Background(), f.receiveChangeNotify, pollInterval)
|
doChangeNotify(ctx, f.receiveChangeNotify, pollInterval)
|
||||||
}
|
}
|
||||||
|
|
||||||
f.features = (&fs.Features{
|
f.features = (&fs.Features{
|
||||||
CanHaveEmptyDirectories: true,
|
CanHaveEmptyDirectories: true,
|
||||||
DuplicateFiles: false, // storage doesn't permit this
|
DuplicateFiles: false, // storage doesn't permit this
|
||||||
}).Fill(f).Mask(wrappedFs).WrapsFs(f, wrappedFs)
|
}).Fill(ctx, f).Mask(ctx, wrappedFs).WrapsFs(f, wrappedFs)
|
||||||
// override only those features that use a temp fs and it doesn't support them
|
// override only those features that use a temp fs and it doesn't support them
|
||||||
//f.features.ChangeNotify = f.ChangeNotify
|
//f.features.ChangeNotify = f.ChangeNotify
|
||||||
if f.opt.TempWritePath != "" {
|
if f.opt.TempWritePath != "" {
|
||||||
if f.tempFs.Features().Copy == nil {
|
|
||||||
f.features.Copy = nil
|
|
||||||
}
|
|
||||||
if f.tempFs.Features().Move == nil {
|
if f.tempFs.Features().Move == nil {
|
||||||
f.features.Move = nil
|
f.features.Move = nil
|
||||||
}
|
}
|
||||||
@@ -587,7 +581,7 @@ Some valid examples are:
|
|||||||
"0:10" -> the first ten chunks
|
"0:10" -> the first ten chunks
|
||||||
|
|
||||||
Any parameter with a key that starts with "file" can be used to
|
Any parameter with a key that starts with "file" can be used to
|
||||||
specify files to fetch, eg
|
specify files to fetch, e.g.
|
||||||
|
|
||||||
rclone rc cache/fetch chunks=0 file=hello file2=home/goodbye
|
rclone rc cache/fetch chunks=0 file=hello file2=home/goodbye
|
||||||
|
|
||||||
@@ -1242,7 +1236,7 @@ func (f *Fs) Rmdir(ctx context.Context, dir string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DirMove moves src, srcRemote to this remote at dstRemote
|
// DirMove moves src, srcRemote to this remote at dstRemote
|
||||||
// using server side move operations.
|
// using server-side move operations.
|
||||||
func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string) error {
|
func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string) error {
|
||||||
fs.Debugf(f, "move dir '%s'/'%s' -> '%s'/'%s'", src.Root(), srcRemote, f.Root(), dstRemote)
|
fs.Debugf(f, "move dir '%s'/'%s' -> '%s'/'%s'", src.Root(), srcRemote, f.Root(), dstRemote)
|
||||||
|
|
||||||
@@ -1523,7 +1517,7 @@ func (f *Fs) PutStream(ctx context.Context, in io.Reader, src fs.ObjectInfo, opt
|
|||||||
return f.put(ctx, in, src, options, do)
|
return f.put(ctx, in, src, options, do)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Copy src to this remote using server side copy operations.
|
// Copy src to this remote using server-side copy operations.
|
||||||
func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object, error) {
|
func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object, error) {
|
||||||
fs.Debugf(f, "copy obj '%s' -> '%s'", src, remote)
|
fs.Debugf(f, "copy obj '%s' -> '%s'", src, remote)
|
||||||
|
|
||||||
@@ -1532,6 +1526,9 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
fs.Errorf(src, "source remote (%v) doesn't support Copy", src.Fs())
|
fs.Errorf(src, "source remote (%v) doesn't support Copy", src.Fs())
|
||||||
return nil, fs.ErrorCantCopy
|
return nil, fs.ErrorCantCopy
|
||||||
}
|
}
|
||||||
|
if f.opt.TempWritePath != "" && src.Fs() == f.tempFs {
|
||||||
|
return nil, fs.ErrorCantCopy
|
||||||
|
}
|
||||||
// the source must be a cached object or we abort
|
// the source must be a cached object or we abort
|
||||||
srcObj, ok := src.(*Object)
|
srcObj, ok := src.(*Object)
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -1597,7 +1594,7 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
return co, nil
|
return co, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Move src to this remote using server side move operations.
|
// Move src to this remote using server-side move operations.
|
||||||
func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object, error) {
|
func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object, error) {
|
||||||
fs.Debugf(f, "moving obj '%s' -> %s", src, remote)
|
fs.Debugf(f, "moving obj '%s' -> %s", src, remote)
|
||||||
|
|
||||||
@@ -1701,17 +1698,20 @@ func (f *Fs) Hashes() hash.Set {
|
|||||||
return f.Fs.Hashes()
|
return f.Fs.Hashes()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Purge all files in the root and the root directory
|
// Purge all files in the directory
|
||||||
func (f *Fs) Purge(ctx context.Context) error {
|
func (f *Fs) Purge(ctx context.Context, dir string) error {
|
||||||
fs.Infof(f, "purging cache")
|
if dir == "" {
|
||||||
f.cache.Purge()
|
// FIXME this isn't quite right as it should purge the dir prefix
|
||||||
|
fs.Infof(f, "purging cache")
|
||||||
|
f.cache.Purge()
|
||||||
|
}
|
||||||
|
|
||||||
do := f.Fs.Features().Purge
|
do := f.Fs.Features().Purge
|
||||||
if do == nil {
|
if do == nil {
|
||||||
return nil
|
return fs.ErrorCantPurge
|
||||||
}
|
}
|
||||||
|
|
||||||
err := do(ctx)
|
err := do(ctx, dir)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -1828,6 +1828,19 @@ func (f *Fs) isRootInPath(p string) bool {
|
|||||||
return strings.HasPrefix(p, f.Root()+"/")
|
return strings.HasPrefix(p, f.Root()+"/")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MergeDirs merges the contents of all the directories passed
|
||||||
|
// in into the first one and rmdirs the other directories.
|
||||||
|
func (f *Fs) MergeDirs(ctx context.Context, dirs []fs.Directory) error {
|
||||||
|
do := f.Fs.Features().MergeDirs
|
||||||
|
if do == nil {
|
||||||
|
return errors.New("MergeDirs not supported")
|
||||||
|
}
|
||||||
|
for _, dir := range dirs {
|
||||||
|
_ = f.cache.RemoveDir(dir.Remote())
|
||||||
|
}
|
||||||
|
return do(ctx, dirs)
|
||||||
|
}
|
||||||
|
|
||||||
// DirCacheFlush flushes the dir cache
|
// DirCacheFlush flushes the dir cache
|
||||||
func (f *Fs) DirCacheFlush() {
|
func (f *Fs) DirCacheFlush() {
|
||||||
_ = f.cache.RemoveDir("")
|
_ = f.cache.RemoveDir("")
|
||||||
@@ -1882,6 +1895,41 @@ func (f *Fs) Disconnect(ctx context.Context) error {
|
|||||||
return do(ctx)
|
return do(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Shutdown the backend, closing any background tasks and any
|
||||||
|
// cached connections.
|
||||||
|
func (f *Fs) Shutdown(ctx context.Context) error {
|
||||||
|
do := f.Fs.Features().Shutdown
|
||||||
|
if do == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return do(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
var commandHelp = []fs.CommandHelp{
|
||||||
|
{
|
||||||
|
Name: "stats",
|
||||||
|
Short: "Print stats on the cache backend in JSON format.",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// Command the backend to run a named command
|
||||||
|
//
|
||||||
|
// The command run is name
|
||||||
|
// args may be used to read arguments from
|
||||||
|
// opts may be used to read optional arguments from
|
||||||
|
//
|
||||||
|
// The result should be capable of being JSON encoded
|
||||||
|
// If it is a string or a []string it will be shown to the user
|
||||||
|
// otherwise it will be JSON encoded and shown to the user like that
|
||||||
|
func (f *Fs) Command(ctx context.Context, name string, arg []string, opt map[string]string) (interface{}, error) {
|
||||||
|
switch name {
|
||||||
|
case "stats":
|
||||||
|
return f.Stats()
|
||||||
|
default:
|
||||||
|
return nil, fs.ErrorCommandNotFound
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Check the interfaces are satisfied
|
// Check the interfaces are satisfied
|
||||||
var (
|
var (
|
||||||
_ fs.Fs = (*Fs)(nil)
|
_ fs.Fs = (*Fs)(nil)
|
||||||
@@ -1899,4 +1947,7 @@ var (
|
|||||||
_ fs.Abouter = (*Fs)(nil)
|
_ fs.Abouter = (*Fs)(nil)
|
||||||
_ fs.UserInfoer = (*Fs)(nil)
|
_ fs.UserInfoer = (*Fs)(nil)
|
||||||
_ fs.Disconnecter = (*Fs)(nil)
|
_ fs.Disconnecter = (*Fs)(nil)
|
||||||
|
_ fs.Commander = (*Fs)(nil)
|
||||||
|
_ fs.MergeDirser = (*Fs)(nil)
|
||||||
|
_ fs.Shutdowner = (*Fs)(nil)
|
||||||
)
|
)
|
||||||
Vendored
+62
-366
@@ -1,4 +1,5 @@
|
|||||||
// +build !plan9
|
// +build !plan9,!js
|
||||||
|
// +build !race
|
||||||
|
|
||||||
package cache_test
|
package cache_test
|
||||||
|
|
||||||
@@ -15,9 +16,7 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"runtime"
|
|
||||||
"runtime/debug"
|
"runtime/debug"
|
||||||
"strconv"
|
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@@ -31,12 +30,10 @@ import (
|
|||||||
"github.com/rclone/rclone/fs/config"
|
"github.com/rclone/rclone/fs/config"
|
||||||
"github.com/rclone/rclone/fs/config/configmap"
|
"github.com/rclone/rclone/fs/config/configmap"
|
||||||
"github.com/rclone/rclone/fs/object"
|
"github.com/rclone/rclone/fs/object"
|
||||||
"github.com/rclone/rclone/fs/rc"
|
|
||||||
"github.com/rclone/rclone/fstest"
|
"github.com/rclone/rclone/fstest"
|
||||||
|
"github.com/rclone/rclone/fstest/testy"
|
||||||
"github.com/rclone/rclone/lib/random"
|
"github.com/rclone/rclone/lib/random"
|
||||||
"github.com/rclone/rclone/vfs"
|
|
||||||
"github.com/rclone/rclone/vfs/vfsflags"
|
"github.com/rclone/rclone/vfs/vfsflags"
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -52,9 +49,7 @@ const (
|
|||||||
|
|
||||||
var (
|
var (
|
||||||
remoteName string
|
remoteName string
|
||||||
mountDir string
|
|
||||||
uploadDir string
|
uploadDir string
|
||||||
useMount bool
|
|
||||||
runInstance *run
|
runInstance *run
|
||||||
errNotSupported = errors.New("not supported")
|
errNotSupported = errors.New("not supported")
|
||||||
decryptedToEncryptedRemotes = map[string]string{
|
decryptedToEncryptedRemotes = map[string]string{
|
||||||
@@ -90,9 +85,7 @@ var (
|
|||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
goflag.StringVar(&remoteName, "remote-internal", "TestInternalCache", "Remote to test with, defaults to local filesystem")
|
goflag.StringVar(&remoteName, "remote-internal", "TestInternalCache", "Remote to test with, defaults to local filesystem")
|
||||||
goflag.StringVar(&mountDir, "mount-dir-internal", "", "")
|
|
||||||
goflag.StringVar(&uploadDir, "upload-dir-internal", "", "")
|
goflag.StringVar(&uploadDir, "upload-dir-internal", "", "")
|
||||||
goflag.BoolVar(&useMount, "cache-use-mount", false, "Test only with mount")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestMain drives the tests
|
// TestMain drives the tests
|
||||||
@@ -100,7 +93,7 @@ func TestMain(m *testing.M) {
|
|||||||
goflag.Parse()
|
goflag.Parse()
|
||||||
var rc int
|
var rc int
|
||||||
|
|
||||||
log.Printf("Running with the following params: \n remote: %v, \n mount: %v", remoteName, useMount)
|
log.Printf("Running with the following params: \n remote: %v", remoteName)
|
||||||
runInstance = newRun()
|
runInstance = newRun()
|
||||||
rc = m.Run()
|
rc = m.Run()
|
||||||
os.Exit(rc)
|
os.Exit(rc)
|
||||||
@@ -273,32 +266,8 @@ func TestInternalObjNotFound(t *testing.T) {
|
|||||||
require.Nil(t, obj)
|
require.Nil(t, obj)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestInternalRemoteWrittenFileFoundInMount(t *testing.T) {
|
|
||||||
if !runInstance.useMount {
|
|
||||||
t.Skip("test needs mount mode")
|
|
||||||
}
|
|
||||||
id := fmt.Sprintf("tirwffim%v", time.Now().Unix())
|
|
||||||
rootFs, boltDb := runInstance.newCacheFs(t, remoteName, id, true, true, nil, nil)
|
|
||||||
defer runInstance.cleanupFs(t, rootFs, boltDb)
|
|
||||||
|
|
||||||
cfs, err := runInstance.getCacheFs(rootFs)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
var testData []byte
|
|
||||||
if runInstance.rootIsCrypt {
|
|
||||||
testData, err = base64.StdEncoding.DecodeString(cryptedTextBase64)
|
|
||||||
require.NoError(t, err)
|
|
||||||
} else {
|
|
||||||
testData = []byte("test content")
|
|
||||||
}
|
|
||||||
|
|
||||||
runInstance.writeObjectBytes(t, cfs.UnWrap(), runInstance.encryptRemoteIfNeeded(t, "test"), testData)
|
|
||||||
data, err := runInstance.readDataFromRemote(t, rootFs, "test", 0, int64(len([]byte("test content"))), false)
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Equal(t, "test content", string(data))
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestInternalCachedWrittenContentMatches(t *testing.T) {
|
func TestInternalCachedWrittenContentMatches(t *testing.T) {
|
||||||
|
testy.SkipUnreliable(t)
|
||||||
id := fmt.Sprintf("ticwcm%v", time.Now().Unix())
|
id := fmt.Sprintf("ticwcm%v", time.Now().Unix())
|
||||||
rootFs, boltDb := runInstance.newCacheFs(t, remoteName, id, false, true, nil, nil)
|
rootFs, boltDb := runInstance.newCacheFs(t, remoteName, id, false, true, nil, nil)
|
||||||
defer runInstance.cleanupFs(t, rootFs, boltDb)
|
defer runInstance.cleanupFs(t, rootFs, boltDb)
|
||||||
@@ -342,6 +311,7 @@ func TestInternalDoubleWrittenContentMatches(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestInternalCachedUpdatedContentMatches(t *testing.T) {
|
func TestInternalCachedUpdatedContentMatches(t *testing.T) {
|
||||||
|
testy.SkipUnreliable(t)
|
||||||
id := fmt.Sprintf("ticucm%v", time.Now().Unix())
|
id := fmt.Sprintf("ticucm%v", time.Now().Unix())
|
||||||
rootFs, boltDb := runInstance.newCacheFs(t, remoteName, id, false, true, nil, nil)
|
rootFs, boltDb := runInstance.newCacheFs(t, remoteName, id, false, true, nil, nil)
|
||||||
defer runInstance.cleanupFs(t, rootFs, boltDb)
|
defer runInstance.cleanupFs(t, rootFs, boltDb)
|
||||||
@@ -691,79 +661,6 @@ func TestInternalChangeSeenAfterDirCacheFlush(t *testing.T) {
|
|||||||
require.Equal(t, wrappedTime.Unix(), co.ModTime(context.Background()).Unix())
|
require.Equal(t, wrappedTime.Unix(), co.ModTime(context.Background()).Unix())
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestInternalChangeSeenAfterRc(t *testing.T) {
|
|
||||||
cacheExpire := rc.Calls.Get("cache/expire")
|
|
||||||
assert.NotNil(t, cacheExpire)
|
|
||||||
|
|
||||||
id := fmt.Sprintf("ticsarc%v", time.Now().Unix())
|
|
||||||
rootFs, boltDb := runInstance.newCacheFs(t, remoteName, id, false, true, nil, nil)
|
|
||||||
defer runInstance.cleanupFs(t, rootFs, boltDb)
|
|
||||||
|
|
||||||
if !runInstance.useMount {
|
|
||||||
t.Skipf("needs mount")
|
|
||||||
}
|
|
||||||
if !runInstance.wrappedIsExternal {
|
|
||||||
t.Skipf("needs drive")
|
|
||||||
}
|
|
||||||
|
|
||||||
cfs, err := runInstance.getCacheFs(rootFs)
|
|
||||||
require.NoError(t, err)
|
|
||||||
chunkSize := cfs.ChunkSize()
|
|
||||||
|
|
||||||
// create some rand test data
|
|
||||||
testData := randStringBytes(int(chunkSize*4 + chunkSize/2))
|
|
||||||
runInstance.writeRemoteBytes(t, rootFs, "data.bin", testData)
|
|
||||||
|
|
||||||
// update in the wrapped fs
|
|
||||||
o, err := cfs.UnWrap().NewObject(context.Background(), runInstance.encryptRemoteIfNeeded(t, "data.bin"))
|
|
||||||
require.NoError(t, err)
|
|
||||||
wrappedTime := time.Now().Add(-1 * time.Hour)
|
|
||||||
err = o.SetModTime(context.Background(), wrappedTime)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
// get a new instance from the cache
|
|
||||||
co, err := rootFs.NewObject(context.Background(), "data.bin")
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.NotEqual(t, o.ModTime(context.Background()).String(), co.ModTime(context.Background()).String())
|
|
||||||
|
|
||||||
// Call the rc function
|
|
||||||
m, err := cacheExpire.Fn(context.Background(), rc.Params{"remote": "data.bin"})
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Contains(t, m, "status")
|
|
||||||
require.Contains(t, m, "message")
|
|
||||||
require.Equal(t, "ok", m["status"])
|
|
||||||
require.Contains(t, m["message"], "cached file cleared")
|
|
||||||
|
|
||||||
// get a new instance from the cache
|
|
||||||
co, err = rootFs.NewObject(context.Background(), "data.bin")
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Equal(t, wrappedTime.Unix(), co.ModTime(context.Background()).Unix())
|
|
||||||
_, err = runInstance.list(t, rootFs, "")
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
// create some rand test data
|
|
||||||
testData2 := randStringBytes(int(chunkSize))
|
|
||||||
runInstance.writeObjectBytes(t, cfs.UnWrap(), runInstance.encryptRemoteIfNeeded(t, "test2"), testData2)
|
|
||||||
|
|
||||||
// list should have 1 item only
|
|
||||||
li1, err := runInstance.list(t, rootFs, "")
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Len(t, li1, 1)
|
|
||||||
|
|
||||||
// Call the rc function
|
|
||||||
m, err = cacheExpire.Fn(context.Background(), rc.Params{"remote": "/"})
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Contains(t, m, "status")
|
|
||||||
require.Contains(t, m, "message")
|
|
||||||
require.Equal(t, "ok", m["status"])
|
|
||||||
require.Contains(t, m["message"], "cached directory cleared")
|
|
||||||
|
|
||||||
// list should have 2 items now
|
|
||||||
li2, err := runInstance.list(t, rootFs, "")
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Len(t, li2, 2)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestInternalCacheWrites(t *testing.T) {
|
func TestInternalCacheWrites(t *testing.T) {
|
||||||
id := "ticw"
|
id := "ticw"
|
||||||
rootFs, boltDb := runInstance.newCacheFs(t, remoteName, id, false, true, nil, map[string]string{"writes": "true"})
|
rootFs, boltDb := runInstance.newCacheFs(t, remoteName, id, false, true, nil, map[string]string{"writes": "true"})
|
||||||
@@ -911,15 +808,9 @@ func TestInternalBug2117(t *testing.T) {
|
|||||||
type run struct {
|
type run struct {
|
||||||
okDiff time.Duration
|
okDiff time.Duration
|
||||||
runDefaultCfgMap configmap.Simple
|
runDefaultCfgMap configmap.Simple
|
||||||
mntDir string
|
|
||||||
tmpUploadDir string
|
tmpUploadDir string
|
||||||
useMount bool
|
|
||||||
isMounted bool
|
|
||||||
rootIsCrypt bool
|
rootIsCrypt bool
|
||||||
wrappedIsExternal bool
|
wrappedIsExternal bool
|
||||||
unmountFn func() error
|
|
||||||
unmountRes chan error
|
|
||||||
vfs *vfs.VFS
|
|
||||||
tempFiles []*os.File
|
tempFiles []*os.File
|
||||||
dbPath string
|
dbPath string
|
||||||
chunkPath string
|
chunkPath string
|
||||||
@@ -929,9 +820,7 @@ type run struct {
|
|||||||
func newRun() *run {
|
func newRun() *run {
|
||||||
var err error
|
var err error
|
||||||
r := &run{
|
r := &run{
|
||||||
okDiff: time.Second * 9, // really big diff here but the build machines seem to be slow. need a different way for this
|
okDiff: time.Second * 9, // really big diff here but the build machines seem to be slow. need a different way for this
|
||||||
useMount: useMount,
|
|
||||||
isMounted: false,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read in all the defaults for all the options
|
// Read in all the defaults for all the options
|
||||||
@@ -944,32 +833,6 @@ func newRun() *run {
|
|||||||
r.runDefaultCfgMap.Set(option.Name, fmt.Sprint(option.Default))
|
r.runDefaultCfgMap.Set(option.Name, fmt.Sprint(option.Default))
|
||||||
}
|
}
|
||||||
|
|
||||||
if mountDir == "" {
|
|
||||||
if runtime.GOOS != "windows" {
|
|
||||||
r.mntDir, err = ioutil.TempDir("", "rclonecache-mount")
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("Failed to create mount dir: %v", err)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Find a free drive letter
|
|
||||||
drive := ""
|
|
||||||
for letter := 'E'; letter <= 'Z'; letter++ {
|
|
||||||
drive = string(letter) + ":"
|
|
||||||
_, err := os.Stat(drive + "\\")
|
|
||||||
if os.IsNotExist(err) {
|
|
||||||
goto found
|
|
||||||
}
|
|
||||||
}
|
|
||||||
log.Print("Couldn't find free drive letter for test")
|
|
||||||
found:
|
|
||||||
r.mntDir = drive
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
r.mntDir = mountDir
|
|
||||||
}
|
|
||||||
log.Printf("Mount Dir: %v", r.mntDir)
|
|
||||||
|
|
||||||
if uploadDir == "" {
|
if uploadDir == "" {
|
||||||
r.tmpUploadDir, err = ioutil.TempDir("", "rclonecache-tmp")
|
r.tmpUploadDir, err = ioutil.TempDir("", "rclonecache-tmp")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -1009,6 +872,15 @@ func (r *run) newCacheFs(t *testing.T, remote, id string, needRemote, purge bool
|
|||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Config to pass to NewFs
|
||||||
|
m := configmap.Simple{}
|
||||||
|
for k, v := range r.runDefaultCfgMap {
|
||||||
|
m.Set(k, v)
|
||||||
|
}
|
||||||
|
for k, v := range flags {
|
||||||
|
m.Set(k, v)
|
||||||
|
}
|
||||||
|
|
||||||
// if the remote doesn't exist, create a new one with a local one for it
|
// if the remote doesn't exist, create a new one with a local one for it
|
||||||
// identify which is the cache remote (it can be wrapped by a crypt too)
|
// identify which is the cache remote (it can be wrapped by a crypt too)
|
||||||
rootIsCrypt := false
|
rootIsCrypt := false
|
||||||
@@ -1017,8 +889,8 @@ func (r *run) newCacheFs(t *testing.T, remote, id string, needRemote, purge bool
|
|||||||
localRemote := remote + "-local"
|
localRemote := remote + "-local"
|
||||||
config.FileSet(localRemote, "type", "local")
|
config.FileSet(localRemote, "type", "local")
|
||||||
config.FileSet(localRemote, "nounc", "true")
|
config.FileSet(localRemote, "nounc", "true")
|
||||||
config.FileSet(remote, "type", "cache")
|
m.Set("type", "cache")
|
||||||
config.FileSet(remote, "remote", localRemote+":/var/tmp/"+localRemote)
|
m.Set("remote", localRemote+":"+filepath.Join(os.TempDir(), localRemote))
|
||||||
} else {
|
} else {
|
||||||
remoteType := config.FileGet(remote, "type", "")
|
remoteType := config.FileGet(remote, "type", "")
|
||||||
if remoteType == "" {
|
if remoteType == "" {
|
||||||
@@ -1028,8 +900,8 @@ func (r *run) newCacheFs(t *testing.T, remote, id string, needRemote, purge bool
|
|||||||
if remoteType != "cache" {
|
if remoteType != "cache" {
|
||||||
if remoteType == "crypt" {
|
if remoteType == "crypt" {
|
||||||
rootIsCrypt = true
|
rootIsCrypt = true
|
||||||
config.FileSet(remote, "password", cryptPassword1)
|
m.Set("password", cryptPassword1)
|
||||||
config.FileSet(remote, "password2", cryptPassword2)
|
m.Set("password2", cryptPassword2)
|
||||||
}
|
}
|
||||||
remoteRemote := config.FileGet(remote, "remote", "")
|
remoteRemote := config.FileGet(remote, "remote", "")
|
||||||
if remoteRemote == "" {
|
if remoteRemote == "" {
|
||||||
@@ -1053,22 +925,15 @@ func (r *run) newCacheFs(t *testing.T, remote, id string, needRemote, purge bool
|
|||||||
boltDb, err := cache.GetPersistent(runInstance.dbPath, runInstance.chunkPath, &cache.Features{PurgeDb: true})
|
boltDb, err := cache.GetPersistent(runInstance.dbPath, runInstance.chunkPath, &cache.Features{PurgeDb: true})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
fs.Config.LowLevelRetries = 1
|
ci := fs.GetConfig(context.Background())
|
||||||
|
ci.LowLevelRetries = 1
|
||||||
m := configmap.Simple{}
|
|
||||||
for k, v := range r.runDefaultCfgMap {
|
|
||||||
m.Set(k, v)
|
|
||||||
}
|
|
||||||
for k, v := range flags {
|
|
||||||
m.Set(k, v)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Instantiate root
|
// Instantiate root
|
||||||
if purge {
|
if purge {
|
||||||
boltDb.PurgeTempUploads()
|
boltDb.PurgeTempUploads()
|
||||||
_ = os.RemoveAll(path.Join(runInstance.tmpUploadDir, id))
|
_ = os.RemoveAll(path.Join(runInstance.tmpUploadDir, id))
|
||||||
}
|
}
|
||||||
f, err := cache.NewFs(remote, id, m)
|
f, err := cache.NewFs(context.Background(), remote, id, m)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
cfs, err := r.getCacheFs(f)
|
cfs, err := r.getCacheFs(f)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
@@ -1082,33 +947,21 @@ func (r *run) newCacheFs(t *testing.T, remote, id string, needRemote, purge bool
|
|||||||
}
|
}
|
||||||
|
|
||||||
if purge {
|
if purge {
|
||||||
_ = f.Features().Purge(context.Background())
|
_ = f.Features().Purge(context.Background(), "")
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
}
|
}
|
||||||
err = f.Mkdir(context.Background(), "")
|
err = f.Mkdir(context.Background(), "")
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
if r.useMount && !r.isMounted {
|
|
||||||
r.mountFs(t, f)
|
|
||||||
}
|
|
||||||
|
|
||||||
return f, boltDb
|
return f, boltDb
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *run) cleanupFs(t *testing.T, f fs.Fs, b *cache.Persistent) {
|
func (r *run) cleanupFs(t *testing.T, f fs.Fs, b *cache.Persistent) {
|
||||||
if r.useMount && r.isMounted {
|
err := f.Features().Purge(context.Background(), "")
|
||||||
r.unmountFs(t, f)
|
|
||||||
}
|
|
||||||
|
|
||||||
err := f.Features().Purge(context.Background())
|
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
cfs, err := r.getCacheFs(f)
|
cfs, err := r.getCacheFs(f)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
cfs.StopBackgroundRunners()
|
cfs.StopBackgroundRunners()
|
||||||
|
|
||||||
if r.useMount && runtime.GOOS != "windows" {
|
|
||||||
err = os.RemoveAll(r.mntDir)
|
|
||||||
require.NoError(t, err)
|
|
||||||
}
|
|
||||||
err = os.RemoveAll(r.tmpUploadDir)
|
err = os.RemoveAll(r.tmpUploadDir)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
@@ -1139,23 +992,6 @@ func (r *run) randomReader(t *testing.T, size int64) io.ReadCloser {
|
|||||||
return f
|
return f
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *run) writeRemoteRandomBytes(t *testing.T, f fs.Fs, p string, size int64) string {
|
|
||||||
remote := path.Join(p, strconv.Itoa(rand.Int())+".bin")
|
|
||||||
// create some rand test data
|
|
||||||
testData := randStringBytes(int(size))
|
|
||||||
|
|
||||||
r.writeRemoteBytes(t, f, remote, testData)
|
|
||||||
return remote
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *run) writeObjectRandomBytes(t *testing.T, f fs.Fs, p string, size int64) fs.Object {
|
|
||||||
remote := path.Join(p, strconv.Itoa(rand.Int())+".bin")
|
|
||||||
// create some rand test data
|
|
||||||
testData := randStringBytes(int(size))
|
|
||||||
|
|
||||||
return r.writeObjectBytes(t, f, remote, testData)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *run) writeRemoteString(t *testing.T, f fs.Fs, remote, content string) {
|
func (r *run) writeRemoteString(t *testing.T, f fs.Fs, remote, content string) {
|
||||||
r.writeRemoteBytes(t, f, remote, []byte(content))
|
r.writeRemoteBytes(t, f, remote, []byte(content))
|
||||||
}
|
}
|
||||||
@@ -1165,37 +1001,11 @@ func (r *run) writeObjectString(t *testing.T, f fs.Fs, remote, content string) f
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *run) writeRemoteBytes(t *testing.T, f fs.Fs, remote string, data []byte) {
|
func (r *run) writeRemoteBytes(t *testing.T, f fs.Fs, remote string, data []byte) {
|
||||||
var err error
|
r.writeObjectBytes(t, f, remote, data)
|
||||||
|
|
||||||
if r.useMount {
|
|
||||||
err = r.retryBlock(func() error {
|
|
||||||
return ioutil.WriteFile(path.Join(r.mntDir, remote), data, 0600)
|
|
||||||
}, 3, time.Second*3)
|
|
||||||
require.NoError(t, err)
|
|
||||||
r.vfs.WaitForWriters(10 * time.Second)
|
|
||||||
} else {
|
|
||||||
r.writeObjectBytes(t, f, remote, data)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *run) writeRemoteReader(t *testing.T, f fs.Fs, remote string, in io.ReadCloser) {
|
func (r *run) writeRemoteReader(t *testing.T, f fs.Fs, remote string, in io.ReadCloser) {
|
||||||
defer func() {
|
r.writeObjectReader(t, f, remote, in)
|
||||||
_ = in.Close()
|
|
||||||
}()
|
|
||||||
|
|
||||||
if r.useMount {
|
|
||||||
out, err := os.Create(path.Join(r.mntDir, remote))
|
|
||||||
require.NoError(t, err)
|
|
||||||
defer func() {
|
|
||||||
_ = out.Close()
|
|
||||||
}()
|
|
||||||
|
|
||||||
_, err = io.Copy(out, in)
|
|
||||||
require.NoError(t, err)
|
|
||||||
r.vfs.WaitForWriters(10 * time.Second)
|
|
||||||
} else {
|
|
||||||
r.writeObjectReader(t, f, remote, in)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *run) writeObjectBytes(t *testing.T, f fs.Fs, remote string, data []byte) fs.Object {
|
func (r *run) writeObjectBytes(t *testing.T, f fs.Fs, remote string, data []byte) fs.Object {
|
||||||
@@ -1212,10 +1022,6 @@ func (r *run) writeObjectReader(t *testing.T, f fs.Fs, remote string, in io.Read
|
|||||||
objInfo := object.NewStaticObjectInfo(remote, modTime, -1, true, nil, f)
|
objInfo := object.NewStaticObjectInfo(remote, modTime, -1, true, nil, f)
|
||||||
obj, err := f.Put(context.Background(), in, objInfo)
|
obj, err := f.Put(context.Background(), in, objInfo)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
if r.useMount {
|
|
||||||
r.vfs.WaitForWriters(10 * time.Second)
|
|
||||||
}
|
|
||||||
|
|
||||||
return obj
|
return obj
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1223,26 +1029,16 @@ func (r *run) updateObjectRemote(t *testing.T, f fs.Fs, remote string, data1 []b
|
|||||||
var err error
|
var err error
|
||||||
var obj fs.Object
|
var obj fs.Object
|
||||||
|
|
||||||
if r.useMount {
|
in1 := bytes.NewReader(data1)
|
||||||
err = ioutil.WriteFile(path.Join(r.mntDir, remote), data1, 0600)
|
in2 := bytes.NewReader(data2)
|
||||||
require.NoError(t, err)
|
objInfo1 := object.NewStaticObjectInfo(remote, time.Now(), int64(len(data1)), true, nil, f)
|
||||||
r.vfs.WaitForWriters(10 * time.Second)
|
objInfo2 := object.NewStaticObjectInfo(remote, time.Now(), int64(len(data2)), true, nil, f)
|
||||||
err = ioutil.WriteFile(path.Join(r.mntDir, remote), data2, 0600)
|
|
||||||
require.NoError(t, err)
|
|
||||||
r.vfs.WaitForWriters(10 * time.Second)
|
|
||||||
obj, err = f.NewObject(context.Background(), remote)
|
|
||||||
} else {
|
|
||||||
in1 := bytes.NewReader(data1)
|
|
||||||
in2 := bytes.NewReader(data2)
|
|
||||||
objInfo1 := object.NewStaticObjectInfo(remote, time.Now(), int64(len(data1)), true, nil, f)
|
|
||||||
objInfo2 := object.NewStaticObjectInfo(remote, time.Now(), int64(len(data2)), true, nil, f)
|
|
||||||
|
|
||||||
obj, err = f.Put(context.Background(), in1, objInfo1)
|
obj, err = f.Put(context.Background(), in1, objInfo1)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
obj, err = f.NewObject(context.Background(), remote)
|
obj, err = f.NewObject(context.Background(), remote)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
err = obj.Update(context.Background(), in2, objInfo2)
|
err = obj.Update(context.Background(), in2, objInfo2)
|
||||||
}
|
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
return obj
|
return obj
|
||||||
@@ -1252,30 +1048,12 @@ func (r *run) readDataFromRemote(t *testing.T, f fs.Fs, remote string, offset, e
|
|||||||
size := end - offset
|
size := end - offset
|
||||||
checkSample := make([]byte, size)
|
checkSample := make([]byte, size)
|
||||||
|
|
||||||
if r.useMount {
|
co, err := f.NewObject(context.Background(), remote)
|
||||||
f, err := os.Open(path.Join(r.mntDir, remote))
|
if err != nil {
|
||||||
defer func() {
|
return checkSample, err
|
||||||
_ = f.Close()
|
|
||||||
}()
|
|
||||||
if err != nil {
|
|
||||||
return checkSample, err
|
|
||||||
}
|
|
||||||
_, _ = f.Seek(offset, io.SeekStart)
|
|
||||||
totalRead, err := io.ReadFull(f, checkSample)
|
|
||||||
checkSample = checkSample[:totalRead]
|
|
||||||
if err == io.EOF || err == io.ErrUnexpectedEOF {
|
|
||||||
err = nil
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return checkSample, err
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
co, err := f.NewObject(context.Background(), remote)
|
|
||||||
if err != nil {
|
|
||||||
return checkSample, err
|
|
||||||
}
|
|
||||||
checkSample = r.readDataFromObj(t, co, offset, end, noLengthCheck)
|
|
||||||
}
|
}
|
||||||
|
checkSample = r.readDataFromObj(t, co, offset, end, noLengthCheck)
|
||||||
|
|
||||||
if !noLengthCheck && size != int64(len(checkSample)) {
|
if !noLengthCheck && size != int64(len(checkSample)) {
|
||||||
return checkSample, errors.Errorf("read size doesn't match expected: %v <> %v", len(checkSample), size)
|
return checkSample, errors.Errorf("read size doesn't match expected: %v <> %v", len(checkSample), size)
|
||||||
}
|
}
|
||||||
@@ -1298,28 +1076,19 @@ func (r *run) readDataFromObj(t *testing.T, o fs.Object, offset, end int64, noLe
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *run) mkdir(t *testing.T, f fs.Fs, remote string) {
|
func (r *run) mkdir(t *testing.T, f fs.Fs, remote string) {
|
||||||
var err error
|
err := f.Mkdir(context.Background(), remote)
|
||||||
if r.useMount {
|
|
||||||
err = os.Mkdir(path.Join(r.mntDir, remote), 0700)
|
|
||||||
} else {
|
|
||||||
err = f.Mkdir(context.Background(), remote)
|
|
||||||
}
|
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *run) rm(t *testing.T, f fs.Fs, remote string) error {
|
func (r *run) rm(t *testing.T, f fs.Fs, remote string) error {
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
if r.useMount {
|
var obj fs.Object
|
||||||
err = os.Remove(path.Join(r.mntDir, remote))
|
obj, err = f.NewObject(context.Background(), remote)
|
||||||
|
if err != nil {
|
||||||
|
err = f.Rmdir(context.Background(), remote)
|
||||||
} else {
|
} else {
|
||||||
var obj fs.Object
|
err = obj.Remove(context.Background())
|
||||||
obj, err = f.NewObject(context.Background(), remote)
|
|
||||||
if err != nil {
|
|
||||||
err = f.Rmdir(context.Background(), remote)
|
|
||||||
} else {
|
|
||||||
err = obj.Remove(context.Background())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return err
|
return err
|
||||||
@@ -1328,42 +1097,14 @@ func (r *run) rm(t *testing.T, f fs.Fs, remote string) error {
|
|||||||
func (r *run) list(t *testing.T, f fs.Fs, remote string) ([]interface{}, error) {
|
func (r *run) list(t *testing.T, f fs.Fs, remote string) ([]interface{}, error) {
|
||||||
var err error
|
var err error
|
||||||
var l []interface{}
|
var l []interface{}
|
||||||
if r.useMount {
|
var list fs.DirEntries
|
||||||
var list []os.FileInfo
|
list, err = f.List(context.Background(), remote)
|
||||||
list, err = ioutil.ReadDir(path.Join(r.mntDir, remote))
|
for _, ll := range list {
|
||||||
for _, ll := range list {
|
l = append(l, ll)
|
||||||
l = append(l, ll)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
var list fs.DirEntries
|
|
||||||
list, err = f.List(context.Background(), remote)
|
|
||||||
for _, ll := range list {
|
|
||||||
l = append(l, ll)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return l, err
|
return l, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *run) listPath(t *testing.T, f fs.Fs, remote string) []string {
|
|
||||||
var err error
|
|
||||||
var l []string
|
|
||||||
if r.useMount {
|
|
||||||
var list []os.FileInfo
|
|
||||||
list, err = ioutil.ReadDir(path.Join(r.mntDir, remote))
|
|
||||||
for _, ll := range list {
|
|
||||||
l = append(l, ll.Name())
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
var list fs.DirEntries
|
|
||||||
list, err = f.List(context.Background(), remote)
|
|
||||||
for _, ll := range list {
|
|
||||||
l = append(l, ll.Remote())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
require.NoError(t, err)
|
|
||||||
return l
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *run) copyFile(t *testing.T, f fs.Fs, src, dst string) error {
|
func (r *run) copyFile(t *testing.T, f fs.Fs, src, dst string) error {
|
||||||
in, err := os.Open(src)
|
in, err := os.Open(src)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -1388,13 +1129,7 @@ func (r *run) copyFile(t *testing.T, f fs.Fs, src, dst string) error {
|
|||||||
func (r *run) dirMove(t *testing.T, rootFs fs.Fs, src, dst string) error {
|
func (r *run) dirMove(t *testing.T, rootFs fs.Fs, src, dst string) error {
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
if runInstance.useMount {
|
if rootFs.Features().DirMove != nil {
|
||||||
err = os.Rename(path.Join(runInstance.mntDir, src), path.Join(runInstance.mntDir, dst))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
r.vfs.WaitForWriters(10 * time.Second)
|
|
||||||
} else if rootFs.Features().DirMove != nil {
|
|
||||||
err = rootFs.Features().DirMove(context.Background(), rootFs, src, dst)
|
err = rootFs.Features().DirMove(context.Background(), rootFs, src, dst)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -1410,13 +1145,7 @@ func (r *run) dirMove(t *testing.T, rootFs fs.Fs, src, dst string) error {
|
|||||||
func (r *run) move(t *testing.T, rootFs fs.Fs, src, dst string) error {
|
func (r *run) move(t *testing.T, rootFs fs.Fs, src, dst string) error {
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
if runInstance.useMount {
|
if rootFs.Features().Move != nil {
|
||||||
err = os.Rename(path.Join(runInstance.mntDir, src), path.Join(runInstance.mntDir, dst))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
r.vfs.WaitForWriters(10 * time.Second)
|
|
||||||
} else if rootFs.Features().Move != nil {
|
|
||||||
obj1, err := rootFs.NewObject(context.Background(), src)
|
obj1, err := rootFs.NewObject(context.Background(), src)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -1436,13 +1165,7 @@ func (r *run) move(t *testing.T, rootFs fs.Fs, src, dst string) error {
|
|||||||
func (r *run) copy(t *testing.T, rootFs fs.Fs, src, dst string) error {
|
func (r *run) copy(t *testing.T, rootFs fs.Fs, src, dst string) error {
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
if r.useMount {
|
if rootFs.Features().Copy != nil {
|
||||||
err = r.copyFile(t, rootFs, path.Join(r.mntDir, src), path.Join(r.mntDir, dst))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
r.vfs.WaitForWriters(10 * time.Second)
|
|
||||||
} else if rootFs.Features().Copy != nil {
|
|
||||||
obj, err := rootFs.NewObject(context.Background(), src)
|
obj, err := rootFs.NewObject(context.Background(), src)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -1462,13 +1185,6 @@ func (r *run) copy(t *testing.T, rootFs fs.Fs, src, dst string) error {
|
|||||||
func (r *run) modTime(t *testing.T, rootFs fs.Fs, src string) (time.Time, error) {
|
func (r *run) modTime(t *testing.T, rootFs fs.Fs, src string) (time.Time, error) {
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
if r.useMount {
|
|
||||||
fi, err := os.Stat(path.Join(runInstance.mntDir, src))
|
|
||||||
if err != nil {
|
|
||||||
return time.Time{}, err
|
|
||||||
}
|
|
||||||
return fi.ModTime(), nil
|
|
||||||
}
|
|
||||||
obj1, err := rootFs.NewObject(context.Background(), src)
|
obj1, err := rootFs.NewObject(context.Background(), src)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return time.Time{}, err
|
return time.Time{}, err
|
||||||
@@ -1479,13 +1195,6 @@ func (r *run) modTime(t *testing.T, rootFs fs.Fs, src string) (time.Time, error)
|
|||||||
func (r *run) size(t *testing.T, rootFs fs.Fs, src string) (int64, error) {
|
func (r *run) size(t *testing.T, rootFs fs.Fs, src string) (int64, error) {
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
if r.useMount {
|
|
||||||
fi, err := os.Stat(path.Join(runInstance.mntDir, src))
|
|
||||||
if err != nil {
|
|
||||||
return int64(0), err
|
|
||||||
}
|
|
||||||
return fi.Size(), nil
|
|
||||||
}
|
|
||||||
obj1, err := rootFs.NewObject(context.Background(), src)
|
obj1, err := rootFs.NewObject(context.Background(), src)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return int64(0), err
|
return int64(0), err
|
||||||
@@ -1496,28 +1205,15 @@ func (r *run) size(t *testing.T, rootFs fs.Fs, src string) (int64, error) {
|
|||||||
func (r *run) updateData(t *testing.T, rootFs fs.Fs, src, data, append string) error {
|
func (r *run) updateData(t *testing.T, rootFs fs.Fs, src, data, append string) error {
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
if r.useMount {
|
var obj1 fs.Object
|
||||||
var f *os.File
|
obj1, err = rootFs.NewObject(context.Background(), src)
|
||||||
f, err = os.OpenFile(path.Join(runInstance.mntDir, src), os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0644)
|
if err != nil {
|
||||||
if err != nil {
|
return err
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer func() {
|
|
||||||
_ = f.Close()
|
|
||||||
r.vfs.WaitForWriters(10 * time.Second)
|
|
||||||
}()
|
|
||||||
_, err = f.WriteString(data + append)
|
|
||||||
} else {
|
|
||||||
var obj1 fs.Object
|
|
||||||
obj1, err = rootFs.NewObject(context.Background(), src)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
data1 := []byte(data + append)
|
|
||||||
r := bytes.NewReader(data1)
|
|
||||||
objInfo1 := object.NewStaticObjectInfo(src, time.Now(), int64(len(data1)), true, nil, rootFs)
|
|
||||||
err = obj1.Update(context.Background(), r, objInfo1)
|
|
||||||
}
|
}
|
||||||
|
data1 := []byte(data + append)
|
||||||
|
reader := bytes.NewReader(data1)
|
||||||
|
objInfo1 := object.NewStaticObjectInfo(src, time.Now(), int64(len(data1)), true, nil, rootFs)
|
||||||
|
err = obj1.Update(context.Background(), reader, objInfo1)
|
||||||
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
-20
@@ -1,20 +0,0 @@
|
|||||||
// +build !linux !go1.11
|
|
||||||
// +build !darwin !go1.11
|
|
||||||
// +build !freebsd !go1.11
|
|
||||||
// +build !windows
|
|
||||||
|
|
||||||
package cache_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/rclone/rclone/fs"
|
|
||||||
)
|
|
||||||
|
|
||||||
func (r *run) mountFs(t *testing.T, f fs.Fs) {
|
|
||||||
panic("mountFs not defined for this platform")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *run) unmountFs(t *testing.T, f fs.Fs) {
|
|
||||||
panic("unmountFs not defined for this platform")
|
|
||||||
}
|
|
||||||
-78
@@ -1,78 +0,0 @@
|
|||||||
// +build linux,go1.11 darwin,go1.11 freebsd,go1.11
|
|
||||||
|
|
||||||
package cache_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"bazil.org/fuse"
|
|
||||||
fusefs "bazil.org/fuse/fs"
|
|
||||||
"github.com/rclone/rclone/cmd/mount"
|
|
||||||
"github.com/rclone/rclone/cmd/mountlib"
|
|
||||||
"github.com/rclone/rclone/fs"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
func (r *run) mountFs(t *testing.T, f fs.Fs) {
|
|
||||||
device := f.Name() + ":" + f.Root()
|
|
||||||
var options = []fuse.MountOption{
|
|
||||||
fuse.MaxReadahead(uint32(mountlib.MaxReadAhead)),
|
|
||||||
fuse.Subtype("rclone"),
|
|
||||||
fuse.FSName(device), fuse.VolumeName(device),
|
|
||||||
fuse.NoAppleDouble(),
|
|
||||||
fuse.NoAppleXattr(),
|
|
||||||
//fuse.AllowOther(),
|
|
||||||
}
|
|
||||||
err := os.MkdirAll(r.mntDir, os.ModePerm)
|
|
||||||
require.NoError(t, err)
|
|
||||||
c, err := fuse.Mount(r.mntDir, options...)
|
|
||||||
require.NoError(t, err)
|
|
||||||
filesys := mount.NewFS(f)
|
|
||||||
server := fusefs.New(c, nil)
|
|
||||||
|
|
||||||
// Serve the mount point in the background returning error to errChan
|
|
||||||
r.unmountRes = make(chan error, 1)
|
|
||||||
go func() {
|
|
||||||
err := server.Serve(filesys)
|
|
||||||
closeErr := c.Close()
|
|
||||||
if err == nil {
|
|
||||||
err = closeErr
|
|
||||||
}
|
|
||||||
r.unmountRes <- err
|
|
||||||
}()
|
|
||||||
|
|
||||||
// check if the mount process has an error to report
|
|
||||||
<-c.Ready
|
|
||||||
require.NoError(t, c.MountError)
|
|
||||||
|
|
||||||
r.unmountFn = func() error {
|
|
||||||
// Shutdown the VFS
|
|
||||||
filesys.VFS.Shutdown()
|
|
||||||
return fuse.Unmount(r.mntDir)
|
|
||||||
}
|
|
||||||
|
|
||||||
r.vfs = filesys.VFS
|
|
||||||
r.isMounted = true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *run) unmountFs(t *testing.T, f fs.Fs) {
|
|
||||||
var err error
|
|
||||||
|
|
||||||
for i := 0; i < 4; i++ {
|
|
||||||
err = r.unmountFn()
|
|
||||||
if err != nil {
|
|
||||||
//log.Printf("signal to umount failed - retrying: %v", err)
|
|
||||||
time.Sleep(3 * time.Second)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
break
|
|
||||||
}
|
|
||||||
require.NoError(t, err)
|
|
||||||
err = <-r.unmountRes
|
|
||||||
require.NoError(t, err)
|
|
||||||
err = r.vfs.CleanUp()
|
|
||||||
require.NoError(t, err)
|
|
||||||
r.isMounted = false
|
|
||||||
}
|
|
||||||
-124
@@ -1,124 +0,0 @@
|
|||||||
// +build windows
|
|
||||||
|
|
||||||
package cache_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/billziss-gh/cgofuse/fuse"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"github.com/rclone/rclone/cmd/cmount"
|
|
||||||
"github.com/rclone/rclone/cmd/mountlib"
|
|
||||||
"github.com/rclone/rclone/fs"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
// waitFor runs fn() until it returns true or the timeout expires
|
|
||||||
func waitFor(fn func() bool) (ok bool) {
|
|
||||||
const totalWait = 10 * time.Second
|
|
||||||
const individualWait = 10 * time.Millisecond
|
|
||||||
for i := 0; i < int(totalWait/individualWait); i++ {
|
|
||||||
ok = fn()
|
|
||||||
if ok {
|
|
||||||
return ok
|
|
||||||
}
|
|
||||||
time.Sleep(individualWait)
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *run) mountFs(t *testing.T, f fs.Fs) {
|
|
||||||
// FIXME implement cmount
|
|
||||||
t.Skip("windows not supported yet")
|
|
||||||
|
|
||||||
device := f.Name() + ":" + f.Root()
|
|
||||||
options := []string{
|
|
||||||
"-o", "fsname=" + device,
|
|
||||||
"-o", "subtype=rclone",
|
|
||||||
"-o", fmt.Sprintf("max_readahead=%d", mountlib.MaxReadAhead),
|
|
||||||
"-o", "uid=-1",
|
|
||||||
"-o", "gid=-1",
|
|
||||||
"-o", "allow_other",
|
|
||||||
// This causes FUSE to supply O_TRUNC with the Open
|
|
||||||
// call which is more efficient for cmount. However
|
|
||||||
// it does not work with cgofuse on Windows with
|
|
||||||
// WinFSP so cmount must work with or without it.
|
|
||||||
"-o", "atomic_o_trunc",
|
|
||||||
"--FileSystemName=rclone",
|
|
||||||
}
|
|
||||||
|
|
||||||
fsys := cmount.NewFS(f)
|
|
||||||
host := fuse.NewFileSystemHost(fsys)
|
|
||||||
|
|
||||||
// Serve the mount point in the background returning error to errChan
|
|
||||||
r.unmountRes = make(chan error, 1)
|
|
||||||
go func() {
|
|
||||||
var err error
|
|
||||||
ok := host.Mount(r.mntDir, options)
|
|
||||||
if !ok {
|
|
||||||
err = errors.New("mount failed")
|
|
||||||
}
|
|
||||||
r.unmountRes <- err
|
|
||||||
}()
|
|
||||||
|
|
||||||
// unmount
|
|
||||||
r.unmountFn = func() error {
|
|
||||||
// Shutdown the VFS
|
|
||||||
fsys.VFS.Shutdown()
|
|
||||||
if host.Unmount() {
|
|
||||||
if !waitFor(func() bool {
|
|
||||||
_, err := os.Stat(r.mntDir)
|
|
||||||
return err != nil
|
|
||||||
}) {
|
|
||||||
t.Fatalf("mountpoint %q didn't disappear after unmount - continuing anyway", r.mntDir)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return errors.New("host unmount failed")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Wait for the filesystem to become ready, checking the file
|
|
||||||
// system didn't blow up before starting
|
|
||||||
select {
|
|
||||||
case err := <-r.unmountRes:
|
|
||||||
require.NoError(t, err)
|
|
||||||
case <-time.After(time.Second * 3):
|
|
||||||
}
|
|
||||||
|
|
||||||
// Wait for the mount point to be available on Windows
|
|
||||||
// On Windows the Init signal comes slightly before the mount is ready
|
|
||||||
if !waitFor(func() bool {
|
|
||||||
_, err := os.Stat(r.mntDir)
|
|
||||||
return err == nil
|
|
||||||
}) {
|
|
||||||
t.Errorf("mountpoint %q didn't became available on mount", r.mntDir)
|
|
||||||
}
|
|
||||||
|
|
||||||
r.vfs = fsys.VFS
|
|
||||||
r.isMounted = true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *run) unmountFs(t *testing.T, f fs.Fs) {
|
|
||||||
// FIXME implement cmount
|
|
||||||
t.Skip("windows not supported yet")
|
|
||||||
var err error
|
|
||||||
|
|
||||||
for i := 0; i < 4; i++ {
|
|
||||||
err = r.unmountFn()
|
|
||||||
if err != nil {
|
|
||||||
//log.Printf("signal to umount failed - retrying: %v", err)
|
|
||||||
time.Sleep(3 * time.Second)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
break
|
|
||||||
}
|
|
||||||
require.NoError(t, err)
|
|
||||||
err = <-r.unmountRes
|
|
||||||
require.NoError(t, err)
|
|
||||||
err = r.vfs.CleanUp()
|
|
||||||
require.NoError(t, err)
|
|
||||||
r.isMounted = false
|
|
||||||
}
|
|
||||||
Vendored
+3
-2
@@ -1,6 +1,7 @@
|
|||||||
// Test Cache filesystem interface
|
// Test Cache filesystem interface
|
||||||
|
|
||||||
// +build !plan9
|
// +build !plan9,!js
|
||||||
|
// +build !race
|
||||||
|
|
||||||
package cache_test
|
package cache_test
|
||||||
|
|
||||||
@@ -17,7 +18,7 @@ func TestIntegration(t *testing.T) {
|
|||||||
fstests.Run(t, &fstests.Opt{
|
fstests.Run(t, &fstests.Opt{
|
||||||
RemoteName: "TestCache:",
|
RemoteName: "TestCache:",
|
||||||
NilObject: (*cache.Object)(nil),
|
NilObject: (*cache.Object)(nil),
|
||||||
UnimplementableFsMethods: []string{"PublicLink", "MergeDirs", "OpenWriterAt"},
|
UnimplementableFsMethods: []string{"PublicLink", "OpenWriterAt"},
|
||||||
UnimplementableObjectMethods: []string{"MimeType", "ID", "GetTier", "SetTier"},
|
UnimplementableObjectMethods: []string{"MimeType", "ID", "GetTier", "SetTier"},
|
||||||
SkipInvalidUTF8: true, // invalid UTF-8 confuses the cache
|
SkipInvalidUTF8: true, // invalid UTF-8 confuses the cache
|
||||||
})
|
})
|
||||||
|
|||||||
Vendored
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
// Build for cache for unsupported platforms to stop go complaining
|
// Build for cache for unsupported platforms to stop go complaining
|
||||||
// about "no buildable Go source files "
|
// about "no buildable Go source files "
|
||||||
|
|
||||||
// +build plan9
|
// +build plan9 js
|
||||||
|
|
||||||
package cache
|
package cache
|
||||||
Vendored
+2
-1
@@ -1,4 +1,5 @@
|
|||||||
// +build !plan9
|
// +build !plan9,!js
|
||||||
|
// +build !race
|
||||||
|
|
||||||
package cache_test
|
package cache_test
|
||||||
|
|
||||||
|
|||||||
Vendored
+1
-10
@@ -1,4 +1,4 @@
|
|||||||
// +build !plan9
|
// +build !plan9,!js
|
||||||
|
|
||||||
package cache
|
package cache
|
||||||
|
|
||||||
@@ -101,15 +101,6 @@ func (d *Directory) abs() string {
|
|||||||
return cleanPath(path.Join(d.Dir, d.Name))
|
return cleanPath(path.Join(d.Dir, d.Name))
|
||||||
}
|
}
|
||||||
|
|
||||||
// parentRemote returns the absolute path parent remote
|
|
||||||
func (d *Directory) parentRemote() string {
|
|
||||||
absPath := d.abs()
|
|
||||||
if absPath == "" {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return cleanPath(path.Dir(absPath))
|
|
||||||
}
|
|
||||||
|
|
||||||
// ModTime returns the cached ModTime
|
// ModTime returns the cached ModTime
|
||||||
func (d *Directory) ModTime(ctx context.Context) time.Time {
|
func (d *Directory) ModTime(ctx context.Context) time.Time {
|
||||||
return time.Unix(0, d.CacheModTime)
|
return time.Unix(0, d.CacheModTime)
|
||||||
|
|||||||
Vendored
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
// +build !plan9
|
// +build !plan9,!js
|
||||||
|
|
||||||
package cache
|
package cache
|
||||||
|
|
||||||
|
|||||||
Vendored
+19
-11
@@ -1,4 +1,4 @@
|
|||||||
// +build !plan9
|
// +build !plan9,!js
|
||||||
|
|
||||||
package cache
|
package cache
|
||||||
|
|
||||||
@@ -24,15 +24,16 @@ const (
|
|||||||
type Object struct {
|
type Object struct {
|
||||||
fs.Object `json:"-"`
|
fs.Object `json:"-"`
|
||||||
|
|
||||||
ParentFs fs.Fs `json:"-"` // parent fs
|
ParentFs fs.Fs `json:"-"` // parent fs
|
||||||
CacheFs *Fs `json:"-"` // cache fs
|
CacheFs *Fs `json:"-"` // cache fs
|
||||||
Name string `json:"name"` // name of the directory
|
Name string `json:"name"` // name of the directory
|
||||||
Dir string `json:"dir"` // abs path of the object
|
Dir string `json:"dir"` // abs path of the object
|
||||||
CacheModTime int64 `json:"modTime"` // modification or creation time - IsZero for unknown
|
CacheModTime int64 `json:"modTime"` // modification or creation time - IsZero for unknown
|
||||||
CacheSize int64 `json:"size"` // size of directory and contents or -1 if unknown
|
CacheSize int64 `json:"size"` // size of directory and contents or -1 if unknown
|
||||||
CacheStorable bool `json:"storable"` // says whether this object can be stored
|
CacheStorable bool `json:"storable"` // says whether this object can be stored
|
||||||
CacheType string `json:"cacheType"`
|
CacheType string `json:"cacheType"`
|
||||||
CacheTs time.Time `json:"cacheTs"`
|
CacheTs time.Time `json:"cacheTs"`
|
||||||
|
cacheHashesMu sync.Mutex
|
||||||
CacheHashes map[hash.Type]string // all supported hashes cached
|
CacheHashes map[hash.Type]string // all supported hashes cached
|
||||||
|
|
||||||
refreshMutex sync.Mutex
|
refreshMutex sync.Mutex
|
||||||
@@ -103,7 +104,9 @@ func (o *Object) updateData(ctx context.Context, source fs.Object) {
|
|||||||
o.CacheSize = source.Size()
|
o.CacheSize = source.Size()
|
||||||
o.CacheStorable = source.Storable()
|
o.CacheStorable = source.Storable()
|
||||||
o.CacheTs = time.Now()
|
o.CacheTs = time.Now()
|
||||||
|
o.cacheHashesMu.Lock()
|
||||||
o.CacheHashes = make(map[hash.Type]string)
|
o.CacheHashes = make(map[hash.Type]string)
|
||||||
|
o.cacheHashesMu.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fs returns its FS info
|
// Fs returns its FS info
|
||||||
@@ -268,7 +271,9 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
|
|
||||||
o.CacheModTime = src.ModTime(ctx).UnixNano()
|
o.CacheModTime = src.ModTime(ctx).UnixNano()
|
||||||
o.CacheSize = src.Size()
|
o.CacheSize = src.Size()
|
||||||
|
o.cacheHashesMu.Lock()
|
||||||
o.CacheHashes = make(map[hash.Type]string)
|
o.CacheHashes = make(map[hash.Type]string)
|
||||||
|
o.cacheHashesMu.Unlock()
|
||||||
o.CacheTs = time.Now()
|
o.CacheTs = time.Now()
|
||||||
o.persist()
|
o.persist()
|
||||||
|
|
||||||
@@ -309,11 +314,12 @@ func (o *Object) Remove(ctx context.Context) error {
|
|||||||
// since it might or might not be called, this is lazy loaded
|
// since it might or might not be called, this is lazy loaded
|
||||||
func (o *Object) Hash(ctx context.Context, ht hash.Type) (string, error) {
|
func (o *Object) Hash(ctx context.Context, ht hash.Type) (string, error) {
|
||||||
_ = o.refresh(ctx)
|
_ = o.refresh(ctx)
|
||||||
|
o.cacheHashesMu.Lock()
|
||||||
if o.CacheHashes == nil {
|
if o.CacheHashes == nil {
|
||||||
o.CacheHashes = make(map[hash.Type]string)
|
o.CacheHashes = make(map[hash.Type]string)
|
||||||
}
|
}
|
||||||
|
|
||||||
cachedHash, found := o.CacheHashes[ht]
|
cachedHash, found := o.CacheHashes[ht]
|
||||||
|
o.cacheHashesMu.Unlock()
|
||||||
if found {
|
if found {
|
||||||
return cachedHash, nil
|
return cachedHash, nil
|
||||||
}
|
}
|
||||||
@@ -324,7 +330,9 @@ func (o *Object) Hash(ctx context.Context, ht hash.Type) (string, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
o.cacheHashesMu.Lock()
|
||||||
o.CacheHashes[ht] = liveHash
|
o.CacheHashes[ht] = liveHash
|
||||||
|
o.cacheHashesMu.Unlock()
|
||||||
|
|
||||||
o.persist()
|
o.persist()
|
||||||
fs.Debugf(o, "object hash cached: %v", liveHash)
|
fs.Debugf(o, "object hash cached: %v", liveHash)
|
||||||
|
|||||||
Vendored
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
// +build !plan9
|
// +build !plan9,!js
|
||||||
|
|
||||||
package cache
|
package cache
|
||||||
|
|
||||||
|
|||||||
Vendored
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
// +build !plan9
|
// +build !plan9,!js
|
||||||
|
|
||||||
package cache
|
package cache
|
||||||
|
|
||||||
|
|||||||
Vendored
+2
-49
@@ -1,4 +1,4 @@
|
|||||||
// +build !plan9
|
// +build !plan9,!js
|
||||||
|
|
||||||
package cache
|
package cache
|
||||||
|
|
||||||
@@ -16,10 +16,10 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
bolt "github.com/etcd-io/bbolt"
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"github.com/rclone/rclone/fs"
|
"github.com/rclone/rclone/fs"
|
||||||
"github.com/rclone/rclone/fs/walk"
|
"github.com/rclone/rclone/fs/walk"
|
||||||
|
bolt "go.etcd.io/bbolt"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Constants
|
// Constants
|
||||||
@@ -767,31 +767,6 @@ func (b *Persistent) iterateBuckets(buk *bolt.Bucket, bucketFn func(name string)
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Persistent) dumpRoot() string {
|
|
||||||
var itBuckets func(buk *bolt.Bucket) map[string]interface{}
|
|
||||||
|
|
||||||
itBuckets = func(buk *bolt.Bucket) map[string]interface{} {
|
|
||||||
m := make(map[string]interface{})
|
|
||||||
c := buk.Cursor()
|
|
||||||
for k, v := c.First(); k != nil; k, v = c.Next() {
|
|
||||||
if v == nil {
|
|
||||||
buk2 := buk.Bucket(k)
|
|
||||||
m[string(k)] = itBuckets(buk2)
|
|
||||||
} else {
|
|
||||||
m[string(k)] = "-"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return m
|
|
||||||
}
|
|
||||||
var mm map[string]interface{}
|
|
||||||
_ = b.db.View(func(tx *bolt.Tx) error {
|
|
||||||
mm = itBuckets(tx.Bucket([]byte(RootBucket)))
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
raw, _ := json.MarshalIndent(mm, "", " ")
|
|
||||||
return string(raw)
|
|
||||||
}
|
|
||||||
|
|
||||||
// addPendingUpload adds a new file to the pending queue of uploads
|
// addPendingUpload adds a new file to the pending queue of uploads
|
||||||
func (b *Persistent) addPendingUpload(destPath string, started bool) error {
|
func (b *Persistent) addPendingUpload(destPath string, started bool) error {
|
||||||
return b.db.Update(func(tx *bolt.Tx) error {
|
return b.db.Update(func(tx *bolt.Tx) error {
|
||||||
@@ -1005,15 +980,6 @@ func (b *Persistent) updatePendingUpload(remote string, fn func(item *tempUpload
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetPendingUploadToStarted is a way to mark an entry as started (even if it's not already)
|
|
||||||
// TO BE USED IN TESTING ONLY
|
|
||||||
func (b *Persistent) SetPendingUploadToStarted(remote string) error {
|
|
||||||
return b.updatePendingUpload(remote, func(item *tempUploadInfo) error {
|
|
||||||
item.Started = true
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// ReconcileTempUploads will recursively look for all the files in the temp directory and add them to the queue
|
// ReconcileTempUploads will recursively look for all the files in the temp directory and add them to the queue
|
||||||
func (b *Persistent) ReconcileTempUploads(ctx context.Context, cacheFs *Fs) error {
|
func (b *Persistent) ReconcileTempUploads(ctx context.Context, cacheFs *Fs) error {
|
||||||
return b.db.Update(func(tx *bolt.Tx) error {
|
return b.db.Update(func(tx *bolt.Tx) error {
|
||||||
@@ -1061,19 +1027,6 @@ func (b *Persistent) ReconcileTempUploads(ctx context.Context, cacheFs *Fs) erro
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// PurgeTempUploads will remove all the pending uploads from the queue
|
|
||||||
// TO BE USED IN TESTING ONLY
|
|
||||||
func (b *Persistent) PurgeTempUploads() {
|
|
||||||
b.tempQueueMux.Lock()
|
|
||||||
defer b.tempQueueMux.Unlock()
|
|
||||||
|
|
||||||
_ = b.db.Update(func(tx *bolt.Tx) error {
|
|
||||||
_ = tx.DeleteBucket([]byte(tempBucket))
|
|
||||||
_, _ = tx.CreateBucketIfNotExists([]byte(tempBucket))
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close should be called when the program ends gracefully
|
// Close should be called when the program ends gracefully
|
||||||
func (b *Persistent) Close() {
|
func (b *Persistent) Close() {
|
||||||
b.cleanupMux.Lock()
|
b.cleanupMux.Lock()
|
||||||
|
|||||||
Vendored
+23
@@ -0,0 +1,23 @@
|
|||||||
|
package cache
|
||||||
|
|
||||||
|
import bolt "go.etcd.io/bbolt"
|
||||||
|
|
||||||
|
// PurgeTempUploads will remove all the pending uploads from the queue
|
||||||
|
func (b *Persistent) PurgeTempUploads() {
|
||||||
|
b.tempQueueMux.Lock()
|
||||||
|
defer b.tempQueueMux.Unlock()
|
||||||
|
|
||||||
|
_ = b.db.Update(func(tx *bolt.Tx) error {
|
||||||
|
_ = tx.DeleteBucket([]byte(tempBucket))
|
||||||
|
_, _ = tx.CreateBucketIfNotExists([]byte(tempBucket))
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetPendingUploadToStarted is a way to mark an entry as started (even if it's not already)
|
||||||
|
func (b *Persistent) SetPendingUploadToStarted(remote string) error {
|
||||||
|
return b.updatePendingUpload(remote, func(item *tempUploadInfo) error {
|
||||||
|
item.Started = true
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
+254
-117
@@ -24,6 +24,7 @@ import (
|
|||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"github.com/rclone/rclone/fs"
|
"github.com/rclone/rclone/fs"
|
||||||
"github.com/rclone/rclone/fs/accounting"
|
"github.com/rclone/rclone/fs/accounting"
|
||||||
|
"github.com/rclone/rclone/fs/cache"
|
||||||
"github.com/rclone/rclone/fs/config/configmap"
|
"github.com/rclone/rclone/fs/config/configmap"
|
||||||
"github.com/rclone/rclone/fs/config/configstruct"
|
"github.com/rclone/rclone/fs/config/configstruct"
|
||||||
"github.com/rclone/rclone/fs/fspath"
|
"github.com/rclone/rclone/fs/fspath"
|
||||||
@@ -41,7 +42,7 @@ import (
|
|||||||
// used mostly for consistency checks (lazily for performance reasons).
|
// used mostly for consistency checks (lazily for performance reasons).
|
||||||
// Other formats can be developed that use an external meta store
|
// Other formats can be developed that use an external meta store
|
||||||
// free of these limitations, but this needs some support from
|
// free of these limitations, but this needs some support from
|
||||||
// rclone core (eg. metadata store interfaces).
|
// rclone core (e.g. metadata store interfaces).
|
||||||
//
|
//
|
||||||
// The following types of chunks are supported:
|
// The following types of chunks are supported:
|
||||||
// data and control, active and temporary.
|
// data and control, active and temporary.
|
||||||
@@ -96,7 +97,8 @@ var (
|
|||||||
//
|
//
|
||||||
// And still chunker's primary function is to chunk large files
|
// And still chunker's primary function is to chunk large files
|
||||||
// rather than serve as a generic metadata container.
|
// rather than serve as a generic metadata container.
|
||||||
const maxMetadataSize = 255
|
const maxMetadataSize = 1023
|
||||||
|
const maxMetadataSizeWritten = 255
|
||||||
|
|
||||||
// Current/highest supported metadata format.
|
// Current/highest supported metadata format.
|
||||||
const metadataVersion = 1
|
const metadataVersion = 1
|
||||||
@@ -120,6 +122,8 @@ const maxTransactionProbes = 100
|
|||||||
// standard chunker errors
|
// standard chunker errors
|
||||||
var (
|
var (
|
||||||
ErrChunkOverflow = errors.New("chunk number overflow")
|
ErrChunkOverflow = errors.New("chunk number overflow")
|
||||||
|
ErrMetaTooBig = errors.New("metadata is too big")
|
||||||
|
ErrMetaUnknown = errors.New("unknown metadata, please upgrade rclone")
|
||||||
)
|
)
|
||||||
|
|
||||||
// variants of baseMove's parameter delMode
|
// variants of baseMove's parameter delMode
|
||||||
@@ -139,7 +143,7 @@ func init() {
|
|||||||
Name: "remote",
|
Name: "remote",
|
||||||
Required: true,
|
Required: true,
|
||||||
Help: `Remote to chunk/unchunk.
|
Help: `Remote to chunk/unchunk.
|
||||||
Normally should contain a ':' and a path, eg "myremote:path/to/dir",
|
Normally should contain a ':' and a path, e.g. "myremote:path/to/dir",
|
||||||
"myremote:bucket" or maybe "myremote:" (not recommended).`,
|
"myremote:bucket" or maybe "myremote:" (not recommended).`,
|
||||||
}, {
|
}, {
|
||||||
Name: "chunk_size",
|
Name: "chunk_size",
|
||||||
@@ -149,6 +153,7 @@ Normally should contain a ':' and a path, eg "myremote:path/to/dir",
|
|||||||
}, {
|
}, {
|
||||||
Name: "name_format",
|
Name: "name_format",
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
|
Hide: fs.OptionHideCommandLine,
|
||||||
Default: `*.rclone_chunk.###`,
|
Default: `*.rclone_chunk.###`,
|
||||||
Help: `String format of chunk file names.
|
Help: `String format of chunk file names.
|
||||||
The two placeholders are: base file name (*) and chunk number (#...).
|
The two placeholders are: base file name (*) and chunk number (#...).
|
||||||
@@ -159,12 +164,14 @@ Possible chunk files are ignored if their name does not match given format.`,
|
|||||||
}, {
|
}, {
|
||||||
Name: "start_from",
|
Name: "start_from",
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
|
Hide: fs.OptionHideCommandLine,
|
||||||
Default: 1,
|
Default: 1,
|
||||||
Help: `Minimum valid chunk number. Usually 0 or 1.
|
Help: `Minimum valid chunk number. Usually 0 or 1.
|
||||||
By default chunk numbers start from 1.`,
|
By default chunk numbers start from 1.`,
|
||||||
}, {
|
}, {
|
||||||
Name: "meta_format",
|
Name: "meta_format",
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
|
Hide: fs.OptionHideCommandLine,
|
||||||
Default: "simplejson",
|
Default: "simplejson",
|
||||||
Help: `Format of the metadata object or "none". By default "simplejson".
|
Help: `Format of the metadata object or "none". By default "simplejson".
|
||||||
Metadata is a small JSON file named after the composite file.`,
|
Metadata is a small JSON file named after the composite file.`,
|
||||||
@@ -222,7 +229,7 @@ It has the following fields: ver, size, nchunks, md5, sha1.`,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// NewFs constructs an Fs from the path, container:path
|
// NewFs constructs an Fs from the path, container:path
|
||||||
func NewFs(name, rpath string, m configmap.Mapper) (fs.Fs, error) {
|
func NewFs(ctx context.Context, name, rpath string, m configmap.Mapper) (fs.Fs, error) {
|
||||||
// Parse config into Options struct
|
// Parse config into Options struct
|
||||||
opt := new(Options)
|
opt := new(Options)
|
||||||
err := configstruct.Set(m, opt)
|
err := configstruct.Set(m, opt)
|
||||||
@@ -238,18 +245,21 @@ func NewFs(name, rpath string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
return nil, errors.New("can't point remote at itself - check the value of the remote setting")
|
return nil, errors.New("can't point remote at itself - check the value of the remote setting")
|
||||||
}
|
}
|
||||||
|
|
||||||
baseInfo, baseName, basePath, baseConfig, err := fs.ConfigFs(remote)
|
baseName, basePath, err := fspath.Parse(remote)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrapf(err, "failed to parse remote %q to wrap", remote)
|
return nil, errors.Wrapf(err, "failed to parse remote %q to wrap", remote)
|
||||||
}
|
}
|
||||||
|
if baseName != "" {
|
||||||
|
baseName += ":"
|
||||||
|
}
|
||||||
// Look for a file first
|
// Look for a file first
|
||||||
remotePath := fspath.JoinRootPath(basePath, rpath)
|
remotePath := fspath.JoinRootPath(basePath, rpath)
|
||||||
baseFs, err := baseInfo.NewFs(baseName, remotePath, baseConfig)
|
baseFs, err := cache.Get(ctx, baseName+remotePath)
|
||||||
if err != fs.ErrorIsFile && err != nil {
|
if err != fs.ErrorIsFile && err != nil {
|
||||||
return nil, errors.Wrapf(err, "failed to make remote %s:%q to wrap", baseName, remotePath)
|
return nil, errors.Wrapf(err, "failed to make remote %q to wrap", baseName+remotePath)
|
||||||
}
|
}
|
||||||
if !operations.CanServerSideMove(baseFs) {
|
if !operations.CanServerSideMove(baseFs) {
|
||||||
return nil, errors.New("can't use chunker on a backend which doesn't support server side move or copy")
|
return nil, errors.New("can't use chunker on a backend which doesn't support server-side move or copy")
|
||||||
}
|
}
|
||||||
|
|
||||||
f := &Fs{
|
f := &Fs{
|
||||||
@@ -258,6 +268,7 @@ func NewFs(name, rpath string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
root: rpath,
|
root: rpath,
|
||||||
opt: *opt,
|
opt: *opt,
|
||||||
}
|
}
|
||||||
|
cache.PinUntilFinalized(f.base, f)
|
||||||
f.dirSort = true // processEntries requires that meta Objects prerun data chunks atm.
|
f.dirSort = true // processEntries requires that meta Objects prerun data chunks atm.
|
||||||
|
|
||||||
if err := f.configure(opt.NameFormat, opt.MetaFormat, opt.HashType); err != nil {
|
if err := f.configure(opt.NameFormat, opt.MetaFormat, opt.HashType); err != nil {
|
||||||
@@ -271,7 +282,7 @@ func NewFs(name, rpath string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
// (yet can't satisfy fstest.CheckListing, will ignore)
|
// (yet can't satisfy fstest.CheckListing, will ignore)
|
||||||
if err == nil && !f.useMeta && strings.Contains(rpath, "/") {
|
if err == nil && !f.useMeta && strings.Contains(rpath, "/") {
|
||||||
firstChunkPath := f.makeChunkName(remotePath, 0, "", "")
|
firstChunkPath := f.makeChunkName(remotePath, 0, "", "")
|
||||||
_, testErr := baseInfo.NewFs(baseName, firstChunkPath, baseConfig)
|
_, testErr := cache.Get(ctx, baseName+firstChunkPath)
|
||||||
if testErr == fs.ErrorIsFile {
|
if testErr == fs.ErrorIsFile {
|
||||||
err = testErr
|
err = testErr
|
||||||
}
|
}
|
||||||
@@ -284,12 +295,14 @@ func NewFs(name, rpath string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
f.features = (&fs.Features{
|
f.features = (&fs.Features{
|
||||||
CaseInsensitive: true,
|
CaseInsensitive: true,
|
||||||
DuplicateFiles: true,
|
DuplicateFiles: true,
|
||||||
ReadMimeType: true,
|
ReadMimeType: false, // Object.MimeType not supported
|
||||||
WriteMimeType: true,
|
WriteMimeType: true,
|
||||||
BucketBased: true,
|
BucketBased: true,
|
||||||
CanHaveEmptyDirectories: true,
|
CanHaveEmptyDirectories: true,
|
||||||
ServerSideAcrossConfigs: true,
|
ServerSideAcrossConfigs: true,
|
||||||
}).Fill(f).Mask(baseFs).WrapsFs(f, baseFs)
|
}).Fill(ctx, f).Mask(ctx, baseFs).WrapsFs(f, baseFs)
|
||||||
|
|
||||||
|
f.features.Disable("ListR") // Recursive listing may cause chunker skip files
|
||||||
|
|
||||||
return f, err
|
return f, err
|
||||||
}
|
}
|
||||||
@@ -457,7 +470,7 @@ func (f *Fs) setChunkNameFormat(pattern string) error {
|
|||||||
// filePath can be name, relative or absolute path of main file.
|
// filePath can be name, relative or absolute path of main file.
|
||||||
//
|
//
|
||||||
// chunkNo must be a zero based index of data chunk.
|
// chunkNo must be a zero based index of data chunk.
|
||||||
// Negative chunkNo eg. -1 indicates a control chunk.
|
// Negative chunkNo e.g. -1 indicates a control chunk.
|
||||||
// ctrlType is type of control chunk (must be valid).
|
// ctrlType is type of control chunk (must be valid).
|
||||||
// ctrlType must be "" for data chunks.
|
// ctrlType must be "" for data chunks.
|
||||||
//
|
//
|
||||||
@@ -686,43 +699,50 @@ func (f *Fs) processEntries(ctx context.Context, origEntries fs.DirEntries, dirP
|
|||||||
switch entry := dirOrObject.(type) {
|
switch entry := dirOrObject.(type) {
|
||||||
case fs.Object:
|
case fs.Object:
|
||||||
remote := entry.Remote()
|
remote := entry.Remote()
|
||||||
if mainRemote, chunkNo, ctrlType, xactID := f.parseChunkName(remote); mainRemote != "" {
|
mainRemote, chunkNo, ctrlType, xactID := f.parseChunkName(remote)
|
||||||
if xactID != "" {
|
if mainRemote == "" {
|
||||||
if revealHidden {
|
// this is meta object or standalone file
|
||||||
fs.Infof(f, "ignore temporary chunk %q", remote)
|
object := f.newObject("", entry, nil)
|
||||||
}
|
byRemote[remote] = object
|
||||||
break
|
tempEntries = append(tempEntries, object)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
// this is some kind of chunk
|
||||||
|
// metobject should have been created above if present
|
||||||
|
isSpecial := xactID != "" || ctrlType != ""
|
||||||
|
mainObject := byRemote[mainRemote]
|
||||||
|
if mainObject == nil && f.useMeta && !isSpecial {
|
||||||
|
fs.Debugf(f, "skip orphan data chunk %q", remote)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if mainObject == nil && !f.useMeta {
|
||||||
|
// this is the "nometa" case
|
||||||
|
// create dummy chunked object without metadata
|
||||||
|
mainObject = f.newObject(mainRemote, nil, nil)
|
||||||
|
byRemote[mainRemote] = mainObject
|
||||||
|
if !badEntry[mainRemote] {
|
||||||
|
tempEntries = append(tempEntries, mainObject)
|
||||||
}
|
}
|
||||||
if ctrlType != "" {
|
}
|
||||||
if revealHidden {
|
if isSpecial {
|
||||||
fs.Infof(f, "ignore control chunk %q", remote)
|
if revealHidden {
|
||||||
}
|
fs.Infof(f, "ignore non-data chunk %q", remote)
|
||||||
break
|
|
||||||
}
|
}
|
||||||
mainObject := byRemote[mainRemote]
|
// need to read metadata to ensure actual object type
|
||||||
if mainObject == nil && f.useMeta {
|
// no need to read if metaobject is too big or absent,
|
||||||
fs.Debugf(f, "skip chunk %q without meta object", remote)
|
// use the fact that before calling validate()
|
||||||
break
|
// the `size` field caches metaobject size, if any
|
||||||
}
|
if f.useMeta && mainObject != nil && mainObject.size <= maxMetadataSize {
|
||||||
if mainObject == nil {
|
mainObject.unsure = true
|
||||||
// useMeta is false - create chunked object without metadata
|
|
||||||
mainObject = f.newObject(mainRemote, nil, nil)
|
|
||||||
byRemote[mainRemote] = mainObject
|
|
||||||
if !badEntry[mainRemote] {
|
|
||||||
tempEntries = append(tempEntries, mainObject)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := mainObject.addChunk(entry, chunkNo); err != nil {
|
|
||||||
if f.opt.FailHard {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
badEntry[mainRemote] = true
|
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
object := f.newObject("", entry, nil)
|
if err := mainObject.addChunk(entry, chunkNo); err != nil {
|
||||||
byRemote[remote] = object
|
if f.opt.FailHard {
|
||||||
tempEntries = append(tempEntries, object)
|
return nil, err
|
||||||
|
}
|
||||||
|
badEntry[mainRemote] = true
|
||||||
|
}
|
||||||
case fs.Directory:
|
case fs.Directory:
|
||||||
isSubdir[entry.Remote()] = true
|
isSubdir[entry.Remote()] = true
|
||||||
wrapDir := fs.NewDirCopy(ctx, entry)
|
wrapDir := fs.NewDirCopy(ctx, entry)
|
||||||
@@ -777,14 +797,22 @@ func (f *Fs) processEntries(ctx context.Context, origEntries fs.DirEntries, dirP
|
|||||||
// but opening even a small file can be slow on some backends.
|
// but opening even a small file can be slow on some backends.
|
||||||
//
|
//
|
||||||
func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) {
|
func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) {
|
||||||
|
return f.scanObject(ctx, remote, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
// scanObject is like NewObject with optional quick scan mode.
|
||||||
|
// The quick mode avoids directory requests other than `List`,
|
||||||
|
// ignores non-chunked objects and skips chunk size checks.
|
||||||
|
func (f *Fs) scanObject(ctx context.Context, remote string, quickScan bool) (fs.Object, error) {
|
||||||
if err := f.forbidChunk(false, remote); err != nil {
|
if err := f.forbidChunk(false, remote); err != nil {
|
||||||
return nil, errors.Wrap(err, "can't access")
|
return nil, errors.Wrap(err, "can't access")
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
o *Object
|
o *Object
|
||||||
baseObj fs.Object
|
baseObj fs.Object
|
||||||
err error
|
err error
|
||||||
|
sameMain bool
|
||||||
)
|
)
|
||||||
|
|
||||||
if f.useMeta {
|
if f.useMeta {
|
||||||
@@ -798,6 +826,7 @@ func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) {
|
|||||||
// as a hard limit. Anything larger than that is treated as a
|
// as a hard limit. Anything larger than that is treated as a
|
||||||
// non-chunked file without even checking its contents, so it's
|
// non-chunked file without even checking its contents, so it's
|
||||||
// paramount to prevent metadata from exceeding the maximum size.
|
// paramount to prevent metadata from exceeding the maximum size.
|
||||||
|
// Anything smaller is additionally checked for format.
|
||||||
o = f.newObject("", baseObj, nil)
|
o = f.newObject("", baseObj, nil)
|
||||||
if o.size > maxMetadataSize {
|
if o.size > maxMetadataSize {
|
||||||
return o, nil
|
return o, nil
|
||||||
@@ -827,18 +856,34 @@ func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) {
|
|||||||
return nil, errors.Wrap(err, "can't detect composite file")
|
return nil, errors.Wrap(err, "can't detect composite file")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
caseInsensitive := f.features.CaseInsensitive
|
||||||
for _, dirOrObject := range entries {
|
for _, dirOrObject := range entries {
|
||||||
entry, ok := dirOrObject.(fs.Object)
|
entry, ok := dirOrObject.(fs.Object)
|
||||||
if !ok {
|
if !ok {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
entryRemote := entry.Remote()
|
entryRemote := entry.Remote()
|
||||||
if !strings.Contains(entryRemote, remote) {
|
if !caseInsensitive && !strings.Contains(entryRemote, remote) {
|
||||||
continue // bypass regexp to save cpu
|
continue // bypass regexp to save cpu
|
||||||
}
|
}
|
||||||
mainRemote, chunkNo, ctrlType, xactID := f.parseChunkName(entryRemote)
|
mainRemote, chunkNo, ctrlType, xactID := f.parseChunkName(entryRemote)
|
||||||
if mainRemote == "" || mainRemote != remote || ctrlType != "" || xactID != "" {
|
if mainRemote == "" {
|
||||||
continue // skip non-conforming, temporary and control chunks
|
continue // skip non-chunks
|
||||||
|
}
|
||||||
|
if caseInsensitive {
|
||||||
|
sameMain = strings.EqualFold(mainRemote, remote)
|
||||||
|
} else {
|
||||||
|
sameMain = mainRemote == remote
|
||||||
|
}
|
||||||
|
if !sameMain {
|
||||||
|
continue // skip alien chunks
|
||||||
|
}
|
||||||
|
if ctrlType != "" || xactID != "" {
|
||||||
|
if f.useMeta {
|
||||||
|
// temporary/control chunk calls for lazy metadata read
|
||||||
|
o.unsure = true
|
||||||
|
}
|
||||||
|
continue
|
||||||
}
|
}
|
||||||
//fs.Debugf(f, "%q belongs to %q as chunk %d", entryRemote, mainRemote, chunkNo)
|
//fs.Debugf(f, "%q belongs to %q as chunk %d", entryRemote, mainRemote, chunkNo)
|
||||||
if err := o.addChunk(entry, chunkNo); err != nil {
|
if err := o.addChunk(entry, chunkNo); err != nil {
|
||||||
@@ -848,7 +893,7 @@ func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) {
|
|||||||
|
|
||||||
if o.main == nil && (o.chunks == nil || len(o.chunks) == 0) {
|
if o.main == nil && (o.chunks == nil || len(o.chunks) == 0) {
|
||||||
// Scanning hasn't found data chunks with conforming names.
|
// Scanning hasn't found data chunks with conforming names.
|
||||||
if f.useMeta {
|
if f.useMeta || quickScan {
|
||||||
// Metadata is required but absent and there are no chunks.
|
// Metadata is required but absent and there are no chunks.
|
||||||
return nil, fs.ErrorObjectNotFound
|
return nil, fs.ErrorObjectNotFound
|
||||||
}
|
}
|
||||||
@@ -871,23 +916,48 @@ func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) {
|
|||||||
// file without metadata. Validate it and update the total data size.
|
// file without metadata. Validate it and update the total data size.
|
||||||
// As an optimization, skip metadata reading here - we will call
|
// As an optimization, skip metadata reading here - we will call
|
||||||
// readMetadata lazily when needed (reading can be expensive).
|
// readMetadata lazily when needed (reading can be expensive).
|
||||||
if err := o.validate(); err != nil {
|
if !quickScan {
|
||||||
return nil, err
|
if err := o.validate(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return o, nil
|
return o, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// readMetadata reads composite object metadata and caches results,
|
||||||
|
// in case of critical errors metadata is not cached.
|
||||||
|
// Returns ErrMetaUnknown if an unsupported metadata format is detected.
|
||||||
|
// If object is not chunked but marked by List or NewObject for recheck,
|
||||||
|
// readMetadata will attempt to parse object as composite with fallback
|
||||||
|
// to non-chunked representation if the attempt fails.
|
||||||
func (o *Object) readMetadata(ctx context.Context) error {
|
func (o *Object) readMetadata(ctx context.Context) error {
|
||||||
|
// return quickly if metadata is absent or has been already cached
|
||||||
|
if !o.f.useMeta {
|
||||||
|
o.isFull = true
|
||||||
|
}
|
||||||
if o.isFull {
|
if o.isFull {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if !o.isComposite() || !o.f.useMeta {
|
if !o.isComposite() && !o.unsure {
|
||||||
|
// this for sure is a non-chunked standalone file
|
||||||
o.isFull = true
|
o.isFull = true
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// validate metadata
|
// validate metadata
|
||||||
metaObject := o.main
|
metaObject := o.main
|
||||||
|
if metaObject.Size() > maxMetadataSize {
|
||||||
|
if o.unsure {
|
||||||
|
// this is not metadata but a foreign object
|
||||||
|
o.unsure = false
|
||||||
|
o.chunks = nil // make isComposite return false
|
||||||
|
o.isFull = true // cache results
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return ErrMetaTooBig
|
||||||
|
}
|
||||||
|
|
||||||
|
// size is within limits, perform consistency checks
|
||||||
reader, err := metaObject.Open(ctx)
|
reader, err := metaObject.Open(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -900,8 +970,22 @@ func (o *Object) readMetadata(ctx context.Context) error {
|
|||||||
|
|
||||||
switch o.f.opt.MetaFormat {
|
switch o.f.opt.MetaFormat {
|
||||||
case "simplejson":
|
case "simplejson":
|
||||||
metaInfo, err := unmarshalSimpleJSON(ctx, metaObject, metadata, true)
|
metaInfo, madeByChunker, err := unmarshalSimpleJSON(ctx, metaObject, metadata)
|
||||||
if err != nil {
|
if o.unsure {
|
||||||
|
o.unsure = false
|
||||||
|
if !madeByChunker {
|
||||||
|
// this is not metadata but a foreign object
|
||||||
|
o.chunks = nil // make isComposite return false
|
||||||
|
o.isFull = true // cache results
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
switch err {
|
||||||
|
case nil:
|
||||||
|
// fall thru
|
||||||
|
case ErrMetaTooBig, ErrMetaUnknown:
|
||||||
|
return err // return these errors unwrapped for unit tests
|
||||||
|
default:
|
||||||
return errors.Wrap(err, "invalid metadata")
|
return errors.Wrap(err, "invalid metadata")
|
||||||
}
|
}
|
||||||
if o.size != metaInfo.Size() || len(o.chunks) != metaInfo.nChunks {
|
if o.size != metaInfo.Size() || len(o.chunks) != metaInfo.nChunks {
|
||||||
@@ -911,12 +995,36 @@ func (o *Object) readMetadata(ctx context.Context) error {
|
|||||||
o.sha1 = metaInfo.sha1
|
o.sha1 = metaInfo.sha1
|
||||||
}
|
}
|
||||||
|
|
||||||
o.isFull = true
|
o.isFull = true // cache results
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// put implements Put, PutStream, PutUnchecked, Update
|
// put implements Put, PutStream, PutUnchecked, Update
|
||||||
func (f *Fs) put(ctx context.Context, in io.Reader, src fs.ObjectInfo, remote string, options []fs.OpenOption, basePut putFn) (obj fs.Object, err error) {
|
func (f *Fs) put(
|
||||||
|
ctx context.Context, in io.Reader, src fs.ObjectInfo, remote string, options []fs.OpenOption,
|
||||||
|
basePut putFn, action string, target fs.Object) (obj fs.Object, err error) {
|
||||||
|
|
||||||
|
// Perform consistency checks
|
||||||
|
if err := f.forbidChunk(src, remote); err != nil {
|
||||||
|
return nil, errors.Wrap(err, action+" refused")
|
||||||
|
}
|
||||||
|
if target == nil {
|
||||||
|
// Get target object with a quick directory scan
|
||||||
|
// skip metadata check if target object does not exist.
|
||||||
|
// ignore not-chunked objects, skip chunk size checks.
|
||||||
|
if obj, err := f.scanObject(ctx, remote, true); err == nil {
|
||||||
|
target = obj
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if target != nil {
|
||||||
|
obj := target.(*Object)
|
||||||
|
if err := obj.readMetadata(ctx); err == ErrMetaUnknown {
|
||||||
|
// refuse to update a file of unsupported format
|
||||||
|
return nil, errors.Wrap(err, "refusing to "+action)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prepare to upload
|
||||||
c := f.newChunkingReader(src)
|
c := f.newChunkingReader(src)
|
||||||
wrapIn := c.wrapStream(ctx, in, src)
|
wrapIn := c.wrapStream(ctx, in, src)
|
||||||
|
|
||||||
@@ -953,6 +1061,8 @@ func (f *Fs) put(ctx context.Context, in io.Reader, src fs.ObjectInfo, remote st
|
|||||||
}
|
}
|
||||||
info := f.wrapInfo(src, chunkRemote, size)
|
info := f.wrapInfo(src, chunkRemote, size)
|
||||||
|
|
||||||
|
// Refill chunkLimit and let basePut repeatedly call chunkingReader.Read()
|
||||||
|
c.chunkLimit = c.chunkSize
|
||||||
// TODO: handle range/limit options
|
// TODO: handle range/limit options
|
||||||
chunk, errChunk := basePut(ctx, wrapIn, info, options...)
|
chunk, errChunk := basePut(ctx, wrapIn, info, options...)
|
||||||
if errChunk != nil {
|
if errChunk != nil {
|
||||||
@@ -985,7 +1095,7 @@ func (f *Fs) put(ctx context.Context, in io.Reader, src fs.ObjectInfo, remote st
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Wrapped remote may or may not have seen EOF from chunking reader,
|
// Wrapped remote may or may not have seen EOF from chunking reader,
|
||||||
// eg. the box multi-uploader reads exactly the chunk size specified
|
// e.g. the box multi-uploader reads exactly the chunk size specified
|
||||||
// and skips the "EOF" read. Hence, switch to next limit here.
|
// and skips the "EOF" read. Hence, switch to next limit here.
|
||||||
if !(c.chunkLimit == 0 || c.chunkLimit == c.chunkSize || c.sizeTotal == -1 || c.done) {
|
if !(c.chunkLimit == 0 || c.chunkLimit == c.chunkSize || c.sizeTotal == -1 || c.done) {
|
||||||
silentlyRemove(ctx, chunk)
|
silentlyRemove(ctx, chunk)
|
||||||
@@ -1004,8 +1114,8 @@ func (f *Fs) put(ctx context.Context, in io.Reader, src fs.ObjectInfo, remote st
|
|||||||
// Check for input that looks like valid metadata
|
// Check for input that looks like valid metadata
|
||||||
needMeta := len(c.chunks) > 1
|
needMeta := len(c.chunks) > 1
|
||||||
if c.readCount <= maxMetadataSize && len(c.chunks) == 1 {
|
if c.readCount <= maxMetadataSize && len(c.chunks) == 1 {
|
||||||
_, err := unmarshalSimpleJSON(ctx, c.chunks[0], c.smallHead, false)
|
_, madeByChunker, _ := unmarshalSimpleJSON(ctx, c.chunks[0], c.smallHead)
|
||||||
needMeta = err == nil
|
needMeta = madeByChunker
|
||||||
}
|
}
|
||||||
|
|
||||||
// Finalize small object as non-chunked.
|
// Finalize small object as non-chunked.
|
||||||
@@ -1121,6 +1231,12 @@ func (c *chunkingReader) wrapStream(ctx context.Context, in io.Reader, src fs.Ob
|
|||||||
|
|
||||||
switch {
|
switch {
|
||||||
case c.fs.useMD5:
|
case c.fs.useMD5:
|
||||||
|
srcObj := fs.UnWrapObjectInfo(src)
|
||||||
|
if srcObj != nil && srcObj.Fs().Features().SlowHash {
|
||||||
|
fs.Debugf(src, "skip slow MD5 on source file, hashing in-transit")
|
||||||
|
c.hasher = md5.New()
|
||||||
|
break
|
||||||
|
}
|
||||||
if c.md5, _ = src.Hash(ctx, hash.MD5); c.md5 == "" {
|
if c.md5, _ = src.Hash(ctx, hash.MD5); c.md5 == "" {
|
||||||
if c.fs.hashFallback {
|
if c.fs.hashFallback {
|
||||||
c.sha1, _ = src.Hash(ctx, hash.SHA1)
|
c.sha1, _ = src.Hash(ctx, hash.SHA1)
|
||||||
@@ -1129,6 +1245,12 @@ func (c *chunkingReader) wrapStream(ctx context.Context, in io.Reader, src fs.Ob
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
case c.fs.useSHA1:
|
case c.fs.useSHA1:
|
||||||
|
srcObj := fs.UnWrapObjectInfo(src)
|
||||||
|
if srcObj != nil && srcObj.Fs().Features().SlowHash {
|
||||||
|
fs.Debugf(src, "skip slow SHA1 on source file, hashing in-transit")
|
||||||
|
c.hasher = sha1.New()
|
||||||
|
break
|
||||||
|
}
|
||||||
if c.sha1, _ = src.Hash(ctx, hash.SHA1); c.sha1 == "" {
|
if c.sha1, _ = src.Hash(ctx, hash.SHA1); c.sha1 == "" {
|
||||||
if c.fs.hashFallback {
|
if c.fs.hashFallback {
|
||||||
c.md5, _ = src.Hash(ctx, hash.MD5)
|
c.md5, _ = src.Hash(ctx, hash.MD5)
|
||||||
@@ -1161,10 +1283,14 @@ func (c *chunkingReader) updateHashes() {
|
|||||||
func (c *chunkingReader) Read(buf []byte) (bytesRead int, err error) {
|
func (c *chunkingReader) Read(buf []byte) (bytesRead int, err error) {
|
||||||
if c.chunkLimit <= 0 {
|
if c.chunkLimit <= 0 {
|
||||||
// Chunk complete - switch to next one.
|
// Chunk complete - switch to next one.
|
||||||
// We might not get here because some remotes (eg. box multi-uploader)
|
// Note #1:
|
||||||
|
// We might not get here because some remotes (e.g. box multi-uploader)
|
||||||
// read the specified size exactly and skip the concluding EOF Read.
|
// read the specified size exactly and skip the concluding EOF Read.
|
||||||
// Then a check in the put loop will kick in.
|
// Then a check in the put loop will kick in.
|
||||||
c.chunkLimit = c.chunkSize
|
// Note #2:
|
||||||
|
// The crypt backend after receiving EOF here will call Read again
|
||||||
|
// and we must insist on returning EOF, so we postpone refilling
|
||||||
|
// chunkLimit to the main loop.
|
||||||
return 0, io.EOF
|
return 0, io.EOF
|
||||||
}
|
}
|
||||||
if int64(len(buf)) > c.chunkLimit {
|
if int64(len(buf)) > c.chunkLimit {
|
||||||
@@ -1197,7 +1323,7 @@ func (c *chunkingReader) accountBytes(bytesRead int64) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// dummyRead updates accounting, hashsums etc by simulating reads
|
// dummyRead updates accounting, hashsums, etc. by simulating reads
|
||||||
func (c *chunkingReader) dummyRead(in io.Reader, size int64) error {
|
func (c *chunkingReader) dummyRead(in io.Reader, size int64) error {
|
||||||
if c.hasher == nil && c.readCount+size > maxMetadataSize {
|
if c.hasher == nil && c.readCount+size > maxMetadataSize {
|
||||||
c.accountBytes(size)
|
c.accountBytes(size)
|
||||||
@@ -1248,29 +1374,16 @@ func (f *Fs) removeOldChunks(ctx context.Context, remote string) {
|
|||||||
// will return the object and the error, otherwise will return
|
// will return the object and the error, otherwise will return
|
||||||
// nil and the error
|
// nil and the error
|
||||||
func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
|
func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
|
||||||
if err := f.forbidChunk(src, src.Remote()); err != nil {
|
return f.put(ctx, in, src, src.Remote(), options, f.base.Put, "put", nil)
|
||||||
return nil, errors.Wrap(err, "refusing to put")
|
|
||||||
}
|
|
||||||
return f.put(ctx, in, src, src.Remote(), options, f.base.Put)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// PutStream uploads to the remote path with the modTime given of indeterminate size
|
// PutStream uploads to the remote path with the modTime given of indeterminate size
|
||||||
func (f *Fs) PutStream(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
|
func (f *Fs) PutStream(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
|
||||||
if err := f.forbidChunk(src, src.Remote()); err != nil {
|
return f.put(ctx, in, src, src.Remote(), options, f.base.Features().PutStream, "upload", nil)
|
||||||
return nil, errors.Wrap(err, "refusing to upload")
|
|
||||||
}
|
|
||||||
return f.put(ctx, in, src, src.Remote(), options, f.base.Features().PutStream)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update in to the object with the modTime given of the given size
|
// Update in to the object with the modTime given of the given size
|
||||||
func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) error {
|
func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) error {
|
||||||
if err := o.f.forbidChunk(o, o.Remote()); err != nil {
|
|
||||||
return errors.Wrap(err, "update refused")
|
|
||||||
}
|
|
||||||
if err := o.readMetadata(ctx); err != nil {
|
|
||||||
// refuse to update a file of unsupported format
|
|
||||||
return errors.Wrap(err, "refusing to update")
|
|
||||||
}
|
|
||||||
basePut := o.f.base.Put
|
basePut := o.f.base.Put
|
||||||
if src.Size() < 0 {
|
if src.Size() < 0 {
|
||||||
basePut = o.f.base.Features().PutStream
|
basePut = o.f.base.Features().PutStream
|
||||||
@@ -1278,7 +1391,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
return errors.New("wrapped file system does not support streaming uploads")
|
return errors.New("wrapped file system does not support streaming uploads")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
oNew, err := o.f.put(ctx, in, src, o.Remote(), options, basePut)
|
oNew, err := o.f.put(ctx, in, src, o.Remote(), options, basePut, "update", o)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
*o = *oNew.(*Object)
|
*o = *oNew.(*Object)
|
||||||
}
|
}
|
||||||
@@ -1333,7 +1446,7 @@ func (f *Fs) Rmdir(ctx context.Context, dir string) error {
|
|||||||
return f.base.Rmdir(ctx, dir)
|
return f.base.Rmdir(ctx, dir)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Purge all files in the root and the root directory
|
// Purge all files in the directory
|
||||||
//
|
//
|
||||||
// Implement this if you have a way of deleting all the files
|
// Implement this if you have a way of deleting all the files
|
||||||
// quicker than just running Remove() on the result of List()
|
// quicker than just running Remove() on the result of List()
|
||||||
@@ -1344,12 +1457,12 @@ func (f *Fs) Rmdir(ctx context.Context, dir string) error {
|
|||||||
// As a result it removes not only composite chunker files with their
|
// As a result it removes not only composite chunker files with their
|
||||||
// active chunks but also all hidden temporary chunks in the directory.
|
// active chunks but also all hidden temporary chunks in the directory.
|
||||||
//
|
//
|
||||||
func (f *Fs) Purge(ctx context.Context) error {
|
func (f *Fs) Purge(ctx context.Context, dir string) error {
|
||||||
do := f.base.Features().Purge
|
do := f.base.Features().Purge
|
||||||
if do == nil {
|
if do == nil {
|
||||||
return fs.ErrorCantPurge
|
return fs.ErrorCantPurge
|
||||||
}
|
}
|
||||||
return do(ctx)
|
return do(ctx, dir)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Remove an object (chunks and metadata, if any)
|
// Remove an object (chunks and metadata, if any)
|
||||||
@@ -1362,7 +1475,7 @@ func (f *Fs) Purge(ctx context.Context) error {
|
|||||||
// However, if rclone dies unexpectedly, it can leave hidden temporary
|
// However, if rclone dies unexpectedly, it can leave hidden temporary
|
||||||
// chunks, which cannot be discovered using the `list` command.
|
// chunks, which cannot be discovered using the `list` command.
|
||||||
// Remove does not try to search for such chunks or to delete them.
|
// Remove does not try to search for such chunks or to delete them.
|
||||||
// Sometimes this can lead to strange results eg. when `list` shows that
|
// Sometimes this can lead to strange results e.g. when `list` shows that
|
||||||
// directory is empty but `rmdir` refuses to remove it because on the
|
// directory is empty but `rmdir` refuses to remove it because on the
|
||||||
// level of wrapped remote it's actually *not* empty.
|
// level of wrapped remote it's actually *not* empty.
|
||||||
// As a workaround users can use `purge` to forcibly remove it.
|
// As a workaround users can use `purge` to forcibly remove it.
|
||||||
@@ -1392,7 +1505,7 @@ func (o *Object) Remove(ctx context.Context) (err error) {
|
|||||||
// to corrupt file in hard mode. Hence, refuse to Remove, too.
|
// to corrupt file in hard mode. Hence, refuse to Remove, too.
|
||||||
return errors.Wrap(err, "refuse to corrupt")
|
return errors.Wrap(err, "refuse to corrupt")
|
||||||
}
|
}
|
||||||
if err := o.readMetadata(ctx); err != nil {
|
if err := o.readMetadata(ctx); err == ErrMetaUnknown {
|
||||||
// Proceed but warn user that unexpected things can happen.
|
// Proceed but warn user that unexpected things can happen.
|
||||||
fs.Errorf(o, "Removing a file with unsupported metadata: %v", err)
|
fs.Errorf(o, "Removing a file with unsupported metadata: %v", err)
|
||||||
}
|
}
|
||||||
@@ -1420,6 +1533,11 @@ func (f *Fs) copyOrMove(ctx context.Context, o *Object, remote string, do copyMo
|
|||||||
if err := f.forbidChunk(o, remote); err != nil {
|
if err := f.forbidChunk(o, remote); err != nil {
|
||||||
return nil, errors.Wrapf(err, "can't %s", opName)
|
return nil, errors.Wrapf(err, "can't %s", opName)
|
||||||
}
|
}
|
||||||
|
if err := o.readMetadata(ctx); err != nil {
|
||||||
|
// Refuse to copy/move composite files with invalid or future
|
||||||
|
// metadata format which might involve unsupported chunk types.
|
||||||
|
return nil, errors.Wrapf(err, "can't %s this file", opName)
|
||||||
|
}
|
||||||
if !o.isComposite() {
|
if !o.isComposite() {
|
||||||
fs.Debugf(o, "%s non-chunked object...", opName)
|
fs.Debugf(o, "%s non-chunked object...", opName)
|
||||||
oResult, err := do(ctx, o.mainChunk(), remote) // chain operation to a single wrapped chunk
|
oResult, err := do(ctx, o.mainChunk(), remote) // chain operation to a single wrapped chunk
|
||||||
@@ -1428,11 +1546,6 @@ func (f *Fs) copyOrMove(ctx context.Context, o *Object, remote string, do copyMo
|
|||||||
}
|
}
|
||||||
return f.newObject("", oResult, nil), nil
|
return f.newObject("", oResult, nil), nil
|
||||||
}
|
}
|
||||||
if err := o.readMetadata(ctx); err != nil {
|
|
||||||
// Refuse to copy/move composite files with invalid or future
|
|
||||||
// metadata format which might involve unsupported chunk types.
|
|
||||||
return nil, errors.Wrapf(err, "can't %s this file", opName)
|
|
||||||
}
|
|
||||||
|
|
||||||
fs.Debugf(o, "%s %d data chunks...", opName, len(o.chunks))
|
fs.Debugf(o, "%s %d data chunks...", opName, len(o.chunks))
|
||||||
mainRemote := o.remote
|
mainRemote := o.remote
|
||||||
@@ -1514,6 +1627,8 @@ func (f *Fs) okForServerSide(ctx context.Context, src fs.Object, opName string)
|
|||||||
diff = "chunk sizes"
|
diff = "chunk sizes"
|
||||||
case f.opt.NameFormat != obj.f.opt.NameFormat:
|
case f.opt.NameFormat != obj.f.opt.NameFormat:
|
||||||
diff = "chunk name formats"
|
diff = "chunk name formats"
|
||||||
|
case f.opt.StartFrom != obj.f.opt.StartFrom:
|
||||||
|
diff = "chunk numbering"
|
||||||
case f.opt.MetaFormat != obj.f.opt.MetaFormat:
|
case f.opt.MetaFormat != obj.f.opt.MetaFormat:
|
||||||
diff = "meta formats"
|
diff = "meta formats"
|
||||||
}
|
}
|
||||||
@@ -1523,6 +1638,10 @@ func (f *Fs) okForServerSide(ctx context.Context, src fs.Object, opName string)
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if obj.unsure {
|
||||||
|
// ensure object is composite if need to re-read metadata
|
||||||
|
_ = obj.readMetadata(ctx)
|
||||||
|
}
|
||||||
requireMetaHash := obj.isComposite() && f.opt.MetaFormat == "simplejson"
|
requireMetaHash := obj.isComposite() && f.opt.MetaFormat == "simplejson"
|
||||||
if !requireMetaHash && !f.hashAll {
|
if !requireMetaHash && !f.hashAll {
|
||||||
ok = true // hash is not required for metadata
|
ok = true // hash is not required for metadata
|
||||||
@@ -1553,7 +1672,7 @@ func (f *Fs) okForServerSide(ctx context.Context, src fs.Object, opName string)
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Copy src to this remote using server side copy operations.
|
// Copy src to this remote using server-side copy operations.
|
||||||
//
|
//
|
||||||
// This is stored with the remote path given
|
// This is stored with the remote path given
|
||||||
//
|
//
|
||||||
@@ -1574,7 +1693,7 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
return f.copyOrMove(ctx, obj, remote, baseCopy, md5, sha1, "copy")
|
return f.copyOrMove(ctx, obj, remote, baseCopy, md5, sha1, "copy")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Move src to this remote using server side move operations.
|
// Move src to this remote using server-side move operations.
|
||||||
//
|
//
|
||||||
// This is stored with the remote path given
|
// This is stored with the remote path given
|
||||||
//
|
//
|
||||||
@@ -1619,7 +1738,7 @@ func (f *Fs) baseMove(ctx context.Context, src fs.Object, remote string, delMode
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DirMove moves src, srcRemote to this remote at dstRemote
|
// DirMove moves src, srcRemote to this remote at dstRemote
|
||||||
// using server side move operations.
|
// using server-side move operations.
|
||||||
//
|
//
|
||||||
// Will only be called if src.Fs().Name() == f.Name()
|
// Will only be called if src.Fs().Name() == f.Name()
|
||||||
//
|
//
|
||||||
@@ -1699,6 +1818,16 @@ func (f *Fs) ChangeNotify(ctx context.Context, notifyFunc func(string, fs.EntryT
|
|||||||
do(ctx, wrappedNotifyFunc, pollIntervalChan)
|
do(ctx, wrappedNotifyFunc, pollIntervalChan)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Shutdown the backend, closing any background tasks and any
|
||||||
|
// cached connections.
|
||||||
|
func (f *Fs) Shutdown(ctx context.Context) error {
|
||||||
|
do := f.base.Features().Shutdown
|
||||||
|
if do == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return do(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
// Object represents a composite file wrapping one or more data chunks
|
// Object represents a composite file wrapping one or more data chunks
|
||||||
type Object struct {
|
type Object struct {
|
||||||
remote string
|
remote string
|
||||||
@@ -1706,6 +1835,7 @@ type Object struct {
|
|||||||
chunks []fs.Object // active data chunks if file is composite, or wrapped file as a single chunk if meta format is 'none'
|
chunks []fs.Object // active data chunks if file is composite, or wrapped file as a single chunk if meta format is 'none'
|
||||||
size int64 // cached total size of chunks in a composite file or -1 for non-chunked files
|
size int64 // cached total size of chunks in a composite file or -1 for non-chunked files
|
||||||
isFull bool // true if metadata has been read
|
isFull bool // true if metadata has been read
|
||||||
|
unsure bool // true if need to read metadata to detect object type
|
||||||
md5 string
|
md5 string
|
||||||
sha1 string
|
sha1 string
|
||||||
f *Fs
|
f *Fs
|
||||||
@@ -1727,6 +1857,9 @@ func (o *Object) addChunk(chunk fs.Object, chunkNo int) error {
|
|||||||
copy(newChunks, o.chunks)
|
copy(newChunks, o.chunks)
|
||||||
o.chunks = newChunks
|
o.chunks = newChunks
|
||||||
}
|
}
|
||||||
|
if o.chunks[chunkNo] != nil {
|
||||||
|
return fmt.Errorf("duplicate chunk number %d", chunkNo+o.f.opt.StartFrom)
|
||||||
|
}
|
||||||
o.chunks[chunkNo] = chunk
|
o.chunks[chunkNo] = chunk
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -1856,15 +1989,16 @@ func (o *Object) SetModTime(ctx context.Context, mtime time.Time) error {
|
|||||||
// on the level of wrapped remote but chunker is unaware of that.
|
// on the level of wrapped remote but chunker is unaware of that.
|
||||||
//
|
//
|
||||||
func (o *Object) Hash(ctx context.Context, hashType hash.Type) (string, error) {
|
func (o *Object) Hash(ctx context.Context, hashType hash.Type) (string, error) {
|
||||||
|
if err := o.readMetadata(ctx); err != nil {
|
||||||
|
return "", err // valid metadata is required to get hash, abort
|
||||||
|
}
|
||||||
if !o.isComposite() {
|
if !o.isComposite() {
|
||||||
// First, chain to the wrapped non-chunked file if possible.
|
// First, chain to the wrapped non-chunked file if possible.
|
||||||
if value, err := o.mainChunk().Hash(ctx, hashType); err == nil && value != "" {
|
if value, err := o.mainChunk().Hash(ctx, hashType); err == nil && value != "" {
|
||||||
return value, nil
|
return value, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if err := o.readMetadata(ctx); err != nil {
|
|
||||||
return "", err // valid metadata is required to get hash, abort
|
|
||||||
}
|
|
||||||
// Try hash from metadata if the file is composite or if wrapped remote fails.
|
// Try hash from metadata if the file is composite or if wrapped remote fails.
|
||||||
switch hashType {
|
switch hashType {
|
||||||
case hash.MD5:
|
case hash.MD5:
|
||||||
@@ -1889,13 +2023,13 @@ func (o *Object) UnWrap() fs.Object {
|
|||||||
|
|
||||||
// Open opens the file for read. Call Close() on the returned io.ReadCloser
|
// Open opens the file for read. Call Close() on the returned io.ReadCloser
|
||||||
func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (rc io.ReadCloser, err error) {
|
func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (rc io.ReadCloser, err error) {
|
||||||
if !o.isComposite() {
|
|
||||||
return o.mainChunk().Open(ctx, options...) // chain to wrapped non-chunked file
|
|
||||||
}
|
|
||||||
if err := o.readMetadata(ctx); err != nil {
|
if err := o.readMetadata(ctx); err != nil {
|
||||||
// refuse to open unsupported format
|
// refuse to open unsupported format
|
||||||
return nil, errors.Wrap(err, "can't open")
|
return nil, errors.Wrap(err, "can't open")
|
||||||
}
|
}
|
||||||
|
if !o.isComposite() {
|
||||||
|
return o.mainChunk().Open(ctx, options...) // chain to wrapped non-chunked file
|
||||||
|
}
|
||||||
|
|
||||||
var openOptions []fs.OpenOption
|
var openOptions []fs.OpenOption
|
||||||
var offset, limit int64 = 0, -1
|
var offset, limit int64 = 0, -1
|
||||||
@@ -2153,72 +2287,74 @@ func marshalSimpleJSON(ctx context.Context, size int64, nChunks int, md5, sha1 s
|
|||||||
SHA1: sha1,
|
SHA1: sha1,
|
||||||
}
|
}
|
||||||
data, err := json.Marshal(&metadata)
|
data, err := json.Marshal(&metadata)
|
||||||
if err == nil && data != nil && len(data) >= maxMetadataSize {
|
if err == nil && data != nil && len(data) >= maxMetadataSizeWritten {
|
||||||
// be a nitpicker, never produce something you can't consume
|
// be a nitpicker, never produce something you can't consume
|
||||||
return nil, errors.New("metadata can't be this big, please report to rclone developers")
|
return nil, errors.New("metadata can't be this big, please report to rclone developers")
|
||||||
}
|
}
|
||||||
return data, err
|
return data, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// unmarshalSimpleJSON
|
// unmarshalSimpleJSON parses metadata.
|
||||||
//
|
//
|
||||||
|
// In case of errors returns a flag telling whether input has been
|
||||||
|
// produced by incompatible version of rclone vs wasn't metadata at all.
|
||||||
// Only metadata format version 1 is supported atm.
|
// Only metadata format version 1 is supported atm.
|
||||||
// Future releases will transparently migrate older metadata objects.
|
// Future releases will transparently migrate older metadata objects.
|
||||||
// New format will have a higher version number and cannot be correctly
|
// New format will have a higher version number and cannot be correctly
|
||||||
// handled by current implementation.
|
// handled by current implementation.
|
||||||
// The version check below will then explicitly ask user to upgrade rclone.
|
// The version check below will then explicitly ask user to upgrade rclone.
|
||||||
//
|
//
|
||||||
func unmarshalSimpleJSON(ctx context.Context, metaObject fs.Object, data []byte, strictChecks bool) (info *ObjectInfo, err error) {
|
func unmarshalSimpleJSON(ctx context.Context, metaObject fs.Object, data []byte) (info *ObjectInfo, madeByChunker bool, err error) {
|
||||||
// Be strict about JSON format
|
// Be strict about JSON format
|
||||||
// to reduce possibility that a random small file resembles metadata.
|
// to reduce possibility that a random small file resembles metadata.
|
||||||
if data != nil && len(data) > maxMetadataSize {
|
if data != nil && len(data) > maxMetadataSizeWritten {
|
||||||
return nil, errors.New("too big")
|
return nil, false, ErrMetaTooBig
|
||||||
}
|
}
|
||||||
if data == nil || len(data) < 2 || data[0] != '{' || data[len(data)-1] != '}' {
|
if data == nil || len(data) < 2 || data[0] != '{' || data[len(data)-1] != '}' {
|
||||||
return nil, errors.New("invalid json")
|
return nil, false, errors.New("invalid json")
|
||||||
}
|
}
|
||||||
var metadata metaSimpleJSON
|
var metadata metaSimpleJSON
|
||||||
err = json.Unmarshal(data, &metadata)
|
err = json.Unmarshal(data, &metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, false, err
|
||||||
}
|
}
|
||||||
// Basic fields are strictly required
|
// Basic fields are strictly required
|
||||||
// to reduce possibility that a random small file resembles metadata.
|
// to reduce possibility that a random small file resembles metadata.
|
||||||
if metadata.Version == nil || metadata.Size == nil || metadata.ChunkNum == nil {
|
if metadata.Version == nil || metadata.Size == nil || metadata.ChunkNum == nil {
|
||||||
return nil, errors.New("missing required field")
|
return nil, false, errors.New("missing required field")
|
||||||
}
|
}
|
||||||
// Perform strict checks, avoid corruption of future metadata formats.
|
// Perform strict checks, avoid corruption of future metadata formats.
|
||||||
if *metadata.Version < 1 {
|
if *metadata.Version < 1 {
|
||||||
return nil, errors.New("wrong version")
|
return nil, false, errors.New("wrong version")
|
||||||
}
|
}
|
||||||
if *metadata.Size < 0 {
|
if *metadata.Size < 0 {
|
||||||
return nil, errors.New("negative file size")
|
return nil, false, errors.New("negative file size")
|
||||||
}
|
}
|
||||||
if *metadata.ChunkNum < 0 {
|
if *metadata.ChunkNum < 0 {
|
||||||
return nil, errors.New("negative number of chunks")
|
return nil, false, errors.New("negative number of chunks")
|
||||||
}
|
}
|
||||||
if *metadata.ChunkNum > maxSafeChunkNumber {
|
if *metadata.ChunkNum > maxSafeChunkNumber {
|
||||||
return nil, ErrChunkOverflow
|
return nil, true, ErrChunkOverflow // produced by incompatible version of rclone
|
||||||
}
|
}
|
||||||
if metadata.MD5 != "" {
|
if metadata.MD5 != "" {
|
||||||
_, err = hex.DecodeString(metadata.MD5)
|
_, err = hex.DecodeString(metadata.MD5)
|
||||||
if len(metadata.MD5) != 32 || err != nil {
|
if len(metadata.MD5) != 32 || err != nil {
|
||||||
return nil, errors.New("wrong md5 hash")
|
return nil, false, errors.New("wrong md5 hash")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if metadata.SHA1 != "" {
|
if metadata.SHA1 != "" {
|
||||||
_, err = hex.DecodeString(metadata.SHA1)
|
_, err = hex.DecodeString(metadata.SHA1)
|
||||||
if len(metadata.SHA1) != 40 || err != nil {
|
if len(metadata.SHA1) != 40 || err != nil {
|
||||||
return nil, errors.New("wrong sha1 hash")
|
return nil, false, errors.New("wrong sha1 hash")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// ChunkNum is allowed to be 0 in future versions
|
// ChunkNum is allowed to be 0 in future versions
|
||||||
if *metadata.ChunkNum < 1 && *metadata.Version <= metadataVersion {
|
if *metadata.ChunkNum < 1 && *metadata.Version <= metadataVersion {
|
||||||
return nil, errors.New("wrong number of chunks")
|
return nil, false, errors.New("wrong number of chunks")
|
||||||
}
|
}
|
||||||
// Non-strict mode also accepts future metadata versions
|
// Non-strict mode also accepts future metadata versions
|
||||||
if *metadata.Version > metadataVersion && strictChecks {
|
if *metadata.Version > metadataVersion {
|
||||||
return nil, fmt.Errorf("version %d is not supported, please upgrade rclone", metadata.Version)
|
return nil, true, ErrMetaUnknown // produced by incompatible version of rclone
|
||||||
}
|
}
|
||||||
|
|
||||||
var nilFs *Fs // nil object triggers appropriate type method
|
var nilFs *Fs // nil object triggers appropriate type method
|
||||||
@@ -2226,7 +2362,7 @@ func unmarshalSimpleJSON(ctx context.Context, metaObject fs.Object, data []byte,
|
|||||||
info.nChunks = *metadata.ChunkNum
|
info.nChunks = *metadata.ChunkNum
|
||||||
info.md5 = metadata.MD5
|
info.md5 = metadata.MD5
|
||||||
info.sha1 = metadata.SHA1
|
info.sha1 = metadata.SHA1
|
||||||
return info, nil
|
return info, true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func silentlyRemove(ctx context.Context, o fs.Object) {
|
func silentlyRemove(ctx context.Context, o fs.Object) {
|
||||||
@@ -2273,6 +2409,7 @@ var (
|
|||||||
_ fs.Abouter = (*Fs)(nil)
|
_ fs.Abouter = (*Fs)(nil)
|
||||||
_ fs.Wrapper = (*Fs)(nil)
|
_ fs.Wrapper = (*Fs)(nil)
|
||||||
_ fs.ChangeNotifier = (*Fs)(nil)
|
_ fs.ChangeNotifier = (*Fs)(nil)
|
||||||
|
_ fs.Shutdowner = (*Fs)(nil)
|
||||||
_ fs.ObjectInfo = (*ObjectInfo)(nil)
|
_ fs.ObjectInfo = (*ObjectInfo)(nil)
|
||||||
_ fs.Object = (*Object)(nil)
|
_ fs.Object = (*Object)(nil)
|
||||||
_ fs.ObjectUnWrapper = (*Object)(nil)
|
_ fs.ObjectUnWrapper = (*Object)(nil)
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import (
|
|||||||
|
|
||||||
"github.com/rclone/rclone/fs"
|
"github.com/rclone/rclone/fs"
|
||||||
"github.com/rclone/rclone/fs/hash"
|
"github.com/rclone/rclone/fs/hash"
|
||||||
|
"github.com/rclone/rclone/fs/object"
|
||||||
"github.com/rclone/rclone/fs/operations"
|
"github.com/rclone/rclone/fs/operations"
|
||||||
"github.com/rclone/rclone/fstest"
|
"github.com/rclone/rclone/fstest"
|
||||||
"github.com/rclone/rclone/fstest/fstests"
|
"github.com/rclone/rclone/fstest/fstests"
|
||||||
@@ -663,6 +664,80 @@ func testMetadataInput(t *testing.T, f *Fs) {
|
|||||||
runSubtest(futureMeta, "future")
|
runSubtest(futureMeta, "future")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// test that chunker refuses to change on objects with future/unknowm metadata
|
||||||
|
func testFutureProof(t *testing.T, f *Fs) {
|
||||||
|
if f.opt.MetaFormat == "none" {
|
||||||
|
t.Skip("this test requires metadata support")
|
||||||
|
}
|
||||||
|
|
||||||
|
saveOpt := f.opt
|
||||||
|
ctx := context.Background()
|
||||||
|
f.opt.FailHard = true
|
||||||
|
const dir = "future"
|
||||||
|
const file = dir + "/test"
|
||||||
|
defer func() {
|
||||||
|
f.opt.FailHard = false
|
||||||
|
_ = operations.Purge(ctx, f.base, dir)
|
||||||
|
f.opt = saveOpt
|
||||||
|
}()
|
||||||
|
|
||||||
|
modTime := fstest.Time("2001-02-03T04:05:06.499999999Z")
|
||||||
|
putPart := func(name string, part int, data, msg string) {
|
||||||
|
if part > 0 {
|
||||||
|
name = f.makeChunkName(name, part-1, "", "")
|
||||||
|
}
|
||||||
|
item := fstest.Item{Path: name, ModTime: modTime}
|
||||||
|
_, obj := fstests.PutTestContents(ctx, t, f.base, &item, data, true)
|
||||||
|
assert.NotNil(t, obj, msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
// simulate chunked object from future
|
||||||
|
meta := `{"ver":999,"nchunks":3,"size":9,"garbage":"litter","sha1":"0707f2970043f9f7c22029482db27733deaec029"}`
|
||||||
|
putPart(file, 0, meta, "metaobject")
|
||||||
|
putPart(file, 1, "abc", "chunk1")
|
||||||
|
putPart(file, 2, "def", "chunk2")
|
||||||
|
putPart(file, 3, "ghi", "chunk3")
|
||||||
|
|
||||||
|
// List should succeed
|
||||||
|
ls, err := f.List(ctx, dir)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.Equal(t, 1, len(ls))
|
||||||
|
assert.Equal(t, int64(9), ls[0].Size())
|
||||||
|
|
||||||
|
// NewObject should succeed
|
||||||
|
obj, err := f.NewObject(ctx, file)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.Equal(t, file, obj.Remote())
|
||||||
|
assert.Equal(t, int64(9), obj.Size())
|
||||||
|
|
||||||
|
// Hash must fail
|
||||||
|
_, err = obj.Hash(ctx, hash.SHA1)
|
||||||
|
assert.Equal(t, ErrMetaUnknown, err)
|
||||||
|
|
||||||
|
// Move must fail
|
||||||
|
mobj, err := operations.Move(ctx, f, nil, file+"2", obj)
|
||||||
|
assert.Nil(t, mobj)
|
||||||
|
assert.Error(t, err)
|
||||||
|
if err != nil {
|
||||||
|
assert.Contains(t, err.Error(), "please upgrade rclone")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Put must fail
|
||||||
|
oi := object.NewStaticObjectInfo(file, modTime, 3, true, nil, nil)
|
||||||
|
buf := bytes.NewBufferString("abc")
|
||||||
|
_, err = f.Put(ctx, buf, oi)
|
||||||
|
assert.Error(t, err)
|
||||||
|
|
||||||
|
// Rcat must fail
|
||||||
|
in := ioutil.NopCloser(bytes.NewBufferString("abc"))
|
||||||
|
robj, err := operations.Rcat(ctx, f, file, in, modTime)
|
||||||
|
assert.Nil(t, robj)
|
||||||
|
assert.NotNil(t, err)
|
||||||
|
if err != nil {
|
||||||
|
assert.Contains(t, err.Error(), "please upgrade rclone")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// InternalTest dispatches all internal tests
|
// InternalTest dispatches all internal tests
|
||||||
func (f *Fs) InternalTest(t *testing.T) {
|
func (f *Fs) InternalTest(t *testing.T) {
|
||||||
t.Run("PutLarge", func(t *testing.T) {
|
t.Run("PutLarge", func(t *testing.T) {
|
||||||
@@ -686,6 +761,9 @@ func (f *Fs) InternalTest(t *testing.T) {
|
|||||||
t.Run("MetadataInput", func(t *testing.T) {
|
t.Run("MetadataInput", func(t *testing.T) {
|
||||||
testMetadataInput(t, f)
|
testMetadataInput(t, f)
|
||||||
})
|
})
|
||||||
|
t.Run("FutureProof", func(t *testing.T) {
|
||||||
|
testFutureProof(t, f)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
var _ fstests.InternalTester = (*Fs)(nil)
|
var _ fstests.InternalTester = (*Fs)(nil)
|
||||||
@@ -15,10 +15,10 @@ import (
|
|||||||
|
|
||||||
// Command line flags
|
// Command line flags
|
||||||
var (
|
var (
|
||||||
// Invalid characters are not supported by some remotes, eg. Mailru.
|
// Invalid characters are not supported by some remotes, e.g. Mailru.
|
||||||
// We enable testing with invalid characters when -remote is not set, so
|
// We enable testing with invalid characters when -remote is not set, so
|
||||||
// chunker overlays a local directory, but invalid characters are disabled
|
// chunker overlays a local directory, but invalid characters are disabled
|
||||||
// by default when -remote is set, eg. when test_all runs backend tests.
|
// by default when -remote is set, e.g. when test_all runs backend tests.
|
||||||
// You can still test with invalid characters using the below flag.
|
// You can still test with invalid characters using the below flag.
|
||||||
UseBadChars = flag.Bool("bad-chars", false, "Set to test bad characters in file names when -remote is set")
|
UseBadChars = flag.Bool("bad-chars", false, "Set to test bad characters in file names when -remote is set")
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
test
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,65 @@
|
|||||||
|
// Test Crypt filesystem interface
|
||||||
|
package compress
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
_ "github.com/rclone/rclone/backend/drive"
|
||||||
|
_ "github.com/rclone/rclone/backend/local"
|
||||||
|
_ "github.com/rclone/rclone/backend/s3"
|
||||||
|
_ "github.com/rclone/rclone/backend/swift"
|
||||||
|
"github.com/rclone/rclone/fstest"
|
||||||
|
"github.com/rclone/rclone/fstest/fstests"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestIntegration runs integration tests against the remote
|
||||||
|
func TestIntegration(t *testing.T) {
|
||||||
|
opt := fstests.Opt{
|
||||||
|
RemoteName: *fstest.RemoteName,
|
||||||
|
NilObject: (*Object)(nil),
|
||||||
|
UnimplementableFsMethods: []string{
|
||||||
|
"OpenWriterAt",
|
||||||
|
"MergeDirs",
|
||||||
|
"DirCacheFlush",
|
||||||
|
"PutUnchecked",
|
||||||
|
"PutStream",
|
||||||
|
"UserInfo",
|
||||||
|
"Disconnect",
|
||||||
|
},
|
||||||
|
TiersToTest: []string{"STANDARD", "STANDARD_IA"},
|
||||||
|
UnimplementableObjectMethods: []string{}}
|
||||||
|
fstests.Run(t, &opt)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRemoteGzip tests GZIP compression
|
||||||
|
func TestRemoteGzip(t *testing.T) {
|
||||||
|
if *fstest.RemoteName != "" {
|
||||||
|
t.Skip("Skipping as -remote set")
|
||||||
|
}
|
||||||
|
tempdir := filepath.Join(os.TempDir(), "rclone-compress-test-gzip")
|
||||||
|
name := "TestCompressGzip"
|
||||||
|
fstests.Run(t, &fstests.Opt{
|
||||||
|
RemoteName: name + ":",
|
||||||
|
NilObject: (*Object)(nil),
|
||||||
|
UnimplementableFsMethods: []string{
|
||||||
|
"OpenWriterAt",
|
||||||
|
"MergeDirs",
|
||||||
|
"DirCacheFlush",
|
||||||
|
"PutUnchecked",
|
||||||
|
"PutStream",
|
||||||
|
"UserInfo",
|
||||||
|
"Disconnect",
|
||||||
|
},
|
||||||
|
UnimplementableObjectMethods: []string{
|
||||||
|
"GetTier",
|
||||||
|
"SetTier",
|
||||||
|
},
|
||||||
|
ExtraConfig: []fstests.ExtraConfigItem{
|
||||||
|
{Name: name, Key: "type", Value: "compress"},
|
||||||
|
{Name: name, Key: "remote", Value: tempdir},
|
||||||
|
{Name: name, Key: "compression_mode", Value: "gzip"},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
+42
-63
@@ -71,30 +71,6 @@ type ReadSeekCloser interface {
|
|||||||
// OpenRangeSeek opens the file handle at the offset with the limit given
|
// OpenRangeSeek opens the file handle at the offset with the limit given
|
||||||
type OpenRangeSeek func(ctx context.Context, offset, limit int64) (io.ReadCloser, error)
|
type OpenRangeSeek func(ctx context.Context, offset, limit int64) (io.ReadCloser, error)
|
||||||
|
|
||||||
// Cipher is used to swap out the encryption implementations
|
|
||||||
type Cipher interface {
|
|
||||||
// EncryptFileName encrypts a file path
|
|
||||||
EncryptFileName(string) string
|
|
||||||
// DecryptFileName decrypts a file path, returns error if decrypt was invalid
|
|
||||||
DecryptFileName(string) (string, error)
|
|
||||||
// EncryptDirName encrypts a directory path
|
|
||||||
EncryptDirName(string) string
|
|
||||||
// DecryptDirName decrypts a directory path, returns error if decrypt was invalid
|
|
||||||
DecryptDirName(string) (string, error)
|
|
||||||
// EncryptData
|
|
||||||
EncryptData(io.Reader) (io.Reader, error)
|
|
||||||
// DecryptData
|
|
||||||
DecryptData(io.ReadCloser) (io.ReadCloser, error)
|
|
||||||
// DecryptDataSeek decrypt at a given position
|
|
||||||
DecryptDataSeek(ctx context.Context, open OpenRangeSeek, offset, limit int64) (ReadSeekCloser, error)
|
|
||||||
// EncryptedSize calculates the size of the data when encrypted
|
|
||||||
EncryptedSize(int64) int64
|
|
||||||
// DecryptedSize calculates the size of the data when decrypted
|
|
||||||
DecryptedSize(int64) (int64, error)
|
|
||||||
// NameEncryptionMode returns the used mode for name handling
|
|
||||||
NameEncryptionMode() NameEncryptionMode
|
|
||||||
}
|
|
||||||
|
|
||||||
// NameEncryptionMode is the type of file name encryption in use
|
// NameEncryptionMode is the type of file name encryption in use
|
||||||
type NameEncryptionMode int
|
type NameEncryptionMode int
|
||||||
|
|
||||||
@@ -136,7 +112,8 @@ func (mode NameEncryptionMode) String() (out string) {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
type cipher struct {
|
// Cipher defines an encoding and decoding cipher for the crypt backend
|
||||||
|
type Cipher struct {
|
||||||
dataKey [32]byte // Key for secretbox
|
dataKey [32]byte // Key for secretbox
|
||||||
nameKey [32]byte // 16,24 or 32 bytes
|
nameKey [32]byte // 16,24 or 32 bytes
|
||||||
nameTweak [nameCipherBlockSize]byte // used to tweak the name crypto
|
nameTweak [nameCipherBlockSize]byte // used to tweak the name crypto
|
||||||
@@ -148,8 +125,8 @@ type cipher struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// newCipher initialises the cipher. If salt is "" then it uses a built in salt val
|
// newCipher initialises the cipher. If salt is "" then it uses a built in salt val
|
||||||
func newCipher(mode NameEncryptionMode, password, salt string, dirNameEncrypt bool) (*cipher, error) {
|
func newCipher(mode NameEncryptionMode, password, salt string, dirNameEncrypt bool) (*Cipher, error) {
|
||||||
c := &cipher{
|
c := &Cipher{
|
||||||
mode: mode,
|
mode: mode,
|
||||||
cryptoRand: rand.Reader,
|
cryptoRand: rand.Reader,
|
||||||
dirNameEncrypt: dirNameEncrypt,
|
dirNameEncrypt: dirNameEncrypt,
|
||||||
@@ -170,9 +147,9 @@ func newCipher(mode NameEncryptionMode, password, salt string, dirNameEncrypt bo
|
|||||||
// If salt is "" we use a fixed salt just to make attackers lives
|
// If salt is "" we use a fixed salt just to make attackers lives
|
||||||
// slighty harder than using no salt.
|
// slighty harder than using no salt.
|
||||||
//
|
//
|
||||||
// Note that empty passsword makes all 0x00 keys which is used in the
|
// Note that empty password makes all 0x00 keys which is used in the
|
||||||
// tests.
|
// tests.
|
||||||
func (c *cipher) Key(password, salt string) (err error) {
|
func (c *Cipher) Key(password, salt string) (err error) {
|
||||||
const keySize = len(c.dataKey) + len(c.nameKey) + len(c.nameTweak)
|
const keySize = len(c.dataKey) + len(c.nameKey) + len(c.nameTweak)
|
||||||
var saltBytes = defaultSalt
|
var saltBytes = defaultSalt
|
||||||
if salt != "" {
|
if salt != "" {
|
||||||
@@ -196,12 +173,12 @@ func (c *cipher) Key(password, salt string) (err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// getBlock gets a block from the pool of size blockSize
|
// getBlock gets a block from the pool of size blockSize
|
||||||
func (c *cipher) getBlock() []byte {
|
func (c *Cipher) getBlock() []byte {
|
||||||
return c.buffers.Get().([]byte)
|
return c.buffers.Get().([]byte)
|
||||||
}
|
}
|
||||||
|
|
||||||
// putBlock returns a block to the pool of size blockSize
|
// putBlock returns a block to the pool of size blockSize
|
||||||
func (c *cipher) putBlock(buf []byte) {
|
func (c *Cipher) putBlock(buf []byte) {
|
||||||
if len(buf) != blockSize {
|
if len(buf) != blockSize {
|
||||||
panic("bad blocksize returned to pool")
|
panic("bad blocksize returned to pool")
|
||||||
}
|
}
|
||||||
@@ -240,13 +217,13 @@ func decodeFileName(in string) ([]byte, error) {
|
|||||||
// 2003 paper "A Parallelizable Enciphering Mode" by Halevi and
|
// 2003 paper "A Parallelizable Enciphering Mode" by Halevi and
|
||||||
// Rogaway.
|
// Rogaway.
|
||||||
//
|
//
|
||||||
// This makes for determinstic encryption which is what we want - the
|
// This makes for deterministic encryption which is what we want - the
|
||||||
// same filename must encrypt to the same thing.
|
// same filename must encrypt to the same thing.
|
||||||
//
|
//
|
||||||
// This means that
|
// This means that
|
||||||
// * filenames with the same name will encrypt the same
|
// * filenames with the same name will encrypt the same
|
||||||
// * filenames which start the same won't have a common prefix
|
// * filenames which start the same won't have a common prefix
|
||||||
func (c *cipher) encryptSegment(plaintext string) string {
|
func (c *Cipher) encryptSegment(plaintext string) string {
|
||||||
if plaintext == "" {
|
if plaintext == "" {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
@@ -256,7 +233,7 @@ func (c *cipher) encryptSegment(plaintext string) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// decryptSegment decrypts a path segment
|
// decryptSegment decrypts a path segment
|
||||||
func (c *cipher) decryptSegment(ciphertext string) (string, error) {
|
func (c *Cipher) decryptSegment(ciphertext string) (string, error) {
|
||||||
if ciphertext == "" {
|
if ciphertext == "" {
|
||||||
return "", nil
|
return "", nil
|
||||||
}
|
}
|
||||||
@@ -283,7 +260,7 @@ func (c *cipher) decryptSegment(ciphertext string) (string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Simple obfuscation routines
|
// Simple obfuscation routines
|
||||||
func (c *cipher) obfuscateSegment(plaintext string) string {
|
func (c *Cipher) obfuscateSegment(plaintext string) string {
|
||||||
if plaintext == "" {
|
if plaintext == "" {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
@@ -370,7 +347,7 @@ func (c *cipher) obfuscateSegment(plaintext string) string {
|
|||||||
return result.String()
|
return result.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *cipher) deobfuscateSegment(ciphertext string) (string, error) {
|
func (c *Cipher) deobfuscateSegment(ciphertext string) (string, error) {
|
||||||
if ciphertext == "" {
|
if ciphertext == "" {
|
||||||
return "", nil
|
return "", nil
|
||||||
}
|
}
|
||||||
@@ -457,7 +434,7 @@ func (c *cipher) deobfuscateSegment(ciphertext string) (string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// encryptFileName encrypts a file path
|
// encryptFileName encrypts a file path
|
||||||
func (c *cipher) encryptFileName(in string) string {
|
func (c *Cipher) encryptFileName(in string) string {
|
||||||
segments := strings.Split(in, "/")
|
segments := strings.Split(in, "/")
|
||||||
for i := range segments {
|
for i := range segments {
|
||||||
// Skip directory name encryption if the user chose to
|
// Skip directory name encryption if the user chose to
|
||||||
@@ -475,7 +452,7 @@ func (c *cipher) encryptFileName(in string) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// EncryptFileName encrypts a file path
|
// EncryptFileName encrypts a file path
|
||||||
func (c *cipher) EncryptFileName(in string) string {
|
func (c *Cipher) EncryptFileName(in string) string {
|
||||||
if c.mode == NameEncryptionOff {
|
if c.mode == NameEncryptionOff {
|
||||||
return in + encryptedSuffix
|
return in + encryptedSuffix
|
||||||
}
|
}
|
||||||
@@ -483,7 +460,7 @@ func (c *cipher) EncryptFileName(in string) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// EncryptDirName encrypts a directory path
|
// EncryptDirName encrypts a directory path
|
||||||
func (c *cipher) EncryptDirName(in string) string {
|
func (c *Cipher) EncryptDirName(in string) string {
|
||||||
if c.mode == NameEncryptionOff || !c.dirNameEncrypt {
|
if c.mode == NameEncryptionOff || !c.dirNameEncrypt {
|
||||||
return in
|
return in
|
||||||
}
|
}
|
||||||
@@ -491,7 +468,7 @@ func (c *cipher) EncryptDirName(in string) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// decryptFileName decrypts a file path
|
// decryptFileName decrypts a file path
|
||||||
func (c *cipher) decryptFileName(in string) (string, error) {
|
func (c *Cipher) decryptFileName(in string) (string, error) {
|
||||||
segments := strings.Split(in, "/")
|
segments := strings.Split(in, "/")
|
||||||
for i := range segments {
|
for i := range segments {
|
||||||
var err error
|
var err error
|
||||||
@@ -514,7 +491,7 @@ func (c *cipher) decryptFileName(in string) (string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DecryptFileName decrypts a file path
|
// DecryptFileName decrypts a file path
|
||||||
func (c *cipher) DecryptFileName(in string) (string, error) {
|
func (c *Cipher) DecryptFileName(in string) (string, error) {
|
||||||
if c.mode == NameEncryptionOff {
|
if c.mode == NameEncryptionOff {
|
||||||
remainingLength := len(in) - len(encryptedSuffix)
|
remainingLength := len(in) - len(encryptedSuffix)
|
||||||
if remainingLength > 0 && strings.HasSuffix(in, encryptedSuffix) {
|
if remainingLength > 0 && strings.HasSuffix(in, encryptedSuffix) {
|
||||||
@@ -526,14 +503,15 @@ func (c *cipher) DecryptFileName(in string) (string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DecryptDirName decrypts a directory path
|
// DecryptDirName decrypts a directory path
|
||||||
func (c *cipher) DecryptDirName(in string) (string, error) {
|
func (c *Cipher) DecryptDirName(in string) (string, error) {
|
||||||
if c.mode == NameEncryptionOff || !c.dirNameEncrypt {
|
if c.mode == NameEncryptionOff || !c.dirNameEncrypt {
|
||||||
return in, nil
|
return in, nil
|
||||||
}
|
}
|
||||||
return c.decryptFileName(in)
|
return c.decryptFileName(in)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *cipher) NameEncryptionMode() NameEncryptionMode {
|
// NameEncryptionMode returns the encryption mode in use for names
|
||||||
|
func (c *Cipher) NameEncryptionMode() NameEncryptionMode {
|
||||||
return c.mode
|
return c.mode
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -581,7 +559,7 @@ func (n *nonce) increment() {
|
|||||||
n.carry(0)
|
n.carry(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
// add an uint64 to the nonce
|
// add a uint64 to the nonce
|
||||||
func (n *nonce) add(x uint64) {
|
func (n *nonce) add(x uint64) {
|
||||||
carry := uint16(0)
|
carry := uint16(0)
|
||||||
for i := 0; i < 8; i++ {
|
for i := 0; i < 8; i++ {
|
||||||
@@ -601,7 +579,7 @@ func (n *nonce) add(x uint64) {
|
|||||||
type encrypter struct {
|
type encrypter struct {
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
in io.Reader
|
in io.Reader
|
||||||
c *cipher
|
c *Cipher
|
||||||
nonce nonce
|
nonce nonce
|
||||||
buf []byte
|
buf []byte
|
||||||
readBuf []byte
|
readBuf []byte
|
||||||
@@ -611,7 +589,7 @@ type encrypter struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// newEncrypter creates a new file handle encrypting on the fly
|
// newEncrypter creates a new file handle encrypting on the fly
|
||||||
func (c *cipher) newEncrypter(in io.Reader, nonce *nonce) (*encrypter, error) {
|
func (c *Cipher) newEncrypter(in io.Reader, nonce *nonce) (*encrypter, error) {
|
||||||
fh := &encrypter{
|
fh := &encrypter{
|
||||||
in: in,
|
in: in,
|
||||||
c: c,
|
c: c,
|
||||||
@@ -655,11 +633,8 @@ func (fh *encrypter) Read(p []byte) (n int, err error) {
|
|||||||
}
|
}
|
||||||
// possibly err != nil here, but we will process the
|
// possibly err != nil here, but we will process the
|
||||||
// data and the next call to ReadFull will return 0, err
|
// data and the next call to ReadFull will return 0, err
|
||||||
// Write nonce to start of block
|
|
||||||
copy(fh.buf, fh.nonce[:])
|
|
||||||
// Encrypt the block using the nonce
|
// Encrypt the block using the nonce
|
||||||
block := fh.buf
|
secretbox.Seal(fh.buf[:0], readBuf[:n], fh.nonce.pointer(), &fh.c.dataKey)
|
||||||
secretbox.Seal(block[:0], readBuf[:n], fh.nonce.pointer(), &fh.c.dataKey)
|
|
||||||
fh.bufIndex = 0
|
fh.bufIndex = 0
|
||||||
fh.bufSize = blockHeaderSize + n
|
fh.bufSize = blockHeaderSize + n
|
||||||
fh.nonce.increment()
|
fh.nonce.increment()
|
||||||
@@ -683,13 +658,19 @@ func (fh *encrypter) finish(err error) (int, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Encrypt data encrypts the data stream
|
// Encrypt data encrypts the data stream
|
||||||
func (c *cipher) EncryptData(in io.Reader) (io.Reader, error) {
|
func (c *Cipher) encryptData(in io.Reader) (io.Reader, *encrypter, error) {
|
||||||
in, wrap := accounting.UnWrap(in) // unwrap the accounting off the Reader
|
in, wrap := accounting.UnWrap(in) // unwrap the accounting off the Reader
|
||||||
out, err := c.newEncrypter(in, nil)
|
out, err := c.newEncrypter(in, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
return wrap(out), nil // and wrap the accounting back on
|
return wrap(out), out, nil // and wrap the accounting back on
|
||||||
|
}
|
||||||
|
|
||||||
|
// EncryptData encrypts the data stream
|
||||||
|
func (c *Cipher) EncryptData(in io.Reader) (io.Reader, error) {
|
||||||
|
out, _, err := c.encryptData(in)
|
||||||
|
return out, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// decrypter decrypts an io.ReaderCloser on the fly
|
// decrypter decrypts an io.ReaderCloser on the fly
|
||||||
@@ -698,7 +679,7 @@ type decrypter struct {
|
|||||||
rc io.ReadCloser
|
rc io.ReadCloser
|
||||||
nonce nonce
|
nonce nonce
|
||||||
initialNonce nonce
|
initialNonce nonce
|
||||||
c *cipher
|
c *Cipher
|
||||||
buf []byte
|
buf []byte
|
||||||
readBuf []byte
|
readBuf []byte
|
||||||
bufIndex int
|
bufIndex int
|
||||||
@@ -709,7 +690,7 @@ type decrypter struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// newDecrypter creates a new file handle decrypting on the fly
|
// newDecrypter creates a new file handle decrypting on the fly
|
||||||
func (c *cipher) newDecrypter(rc io.ReadCloser) (*decrypter, error) {
|
func (c *Cipher) newDecrypter(rc io.ReadCloser) (*decrypter, error) {
|
||||||
fh := &decrypter{
|
fh := &decrypter{
|
||||||
rc: rc,
|
rc: rc,
|
||||||
c: c,
|
c: c,
|
||||||
@@ -737,7 +718,7 @@ func (c *cipher) newDecrypter(rc io.ReadCloser) (*decrypter, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// newDecrypterSeek creates a new file handle decrypting on the fly
|
// newDecrypterSeek creates a new file handle decrypting on the fly
|
||||||
func (c *cipher) newDecrypterSeek(ctx context.Context, open OpenRangeSeek, offset, limit int64) (fh *decrypter, err error) {
|
func (c *Cipher) newDecrypterSeek(ctx context.Context, open OpenRangeSeek, offset, limit int64) (fh *decrypter, err error) {
|
||||||
var rc io.ReadCloser
|
var rc io.ReadCloser
|
||||||
doRangeSeek := false
|
doRangeSeek := false
|
||||||
setLimit := false
|
setLimit := false
|
||||||
@@ -798,8 +779,7 @@ func (fh *decrypter) fillBuffer() (err error) {
|
|||||||
return ErrorEncryptedFileBadHeader
|
return ErrorEncryptedFileBadHeader
|
||||||
}
|
}
|
||||||
// Decrypt the block using the nonce
|
// Decrypt the block using the nonce
|
||||||
block := fh.buf
|
_, ok := secretbox.Open(fh.buf[:0], readBuf[:n], fh.nonce.pointer(), &fh.c.dataKey)
|
||||||
_, ok := secretbox.Open(block[:0], readBuf[:n], fh.nonce.pointer(), &fh.c.dataKey)
|
|
||||||
if !ok {
|
if !ok {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err // return pending error as it is likely more accurate
|
return err // return pending error as it is likely more accurate
|
||||||
@@ -1012,7 +992,7 @@ func (fh *decrypter) finishAndClose(err error) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DecryptData decrypts the data stream
|
// DecryptData decrypts the data stream
|
||||||
func (c *cipher) DecryptData(rc io.ReadCloser) (io.ReadCloser, error) {
|
func (c *Cipher) DecryptData(rc io.ReadCloser) (io.ReadCloser, error) {
|
||||||
out, err := c.newDecrypter(rc)
|
out, err := c.newDecrypter(rc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -1025,7 +1005,7 @@ func (c *cipher) DecryptData(rc io.ReadCloser) (io.ReadCloser, error) {
|
|||||||
// The open function must return a ReadCloser opened to the offset supplied
|
// The open function must return a ReadCloser opened to the offset supplied
|
||||||
//
|
//
|
||||||
// You must use this form of DecryptData if you might want to Seek the file handle
|
// You must use this form of DecryptData if you might want to Seek the file handle
|
||||||
func (c *cipher) DecryptDataSeek(ctx context.Context, open OpenRangeSeek, offset, limit int64) (ReadSeekCloser, error) {
|
func (c *Cipher) DecryptDataSeek(ctx context.Context, open OpenRangeSeek, offset, limit int64) (ReadSeekCloser, error) {
|
||||||
out, err := c.newDecrypterSeek(ctx, open, offset, limit)
|
out, err := c.newDecrypterSeek(ctx, open, offset, limit)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -1034,7 +1014,7 @@ func (c *cipher) DecryptDataSeek(ctx context.Context, open OpenRangeSeek, offset
|
|||||||
}
|
}
|
||||||
|
|
||||||
// EncryptedSize calculates the size of the data when encrypted
|
// EncryptedSize calculates the size of the data when encrypted
|
||||||
func (c *cipher) EncryptedSize(size int64) int64 {
|
func (c *Cipher) EncryptedSize(size int64) int64 {
|
||||||
blocks, residue := size/blockDataSize, size%blockDataSize
|
blocks, residue := size/blockDataSize, size%blockDataSize
|
||||||
encryptedSize := int64(fileHeaderSize) + blocks*(blockHeaderSize+blockDataSize)
|
encryptedSize := int64(fileHeaderSize) + blocks*(blockHeaderSize+blockDataSize)
|
||||||
if residue != 0 {
|
if residue != 0 {
|
||||||
@@ -1044,7 +1024,7 @@ func (c *cipher) EncryptedSize(size int64) int64 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DecryptedSize calculates the size of the data when decrypted
|
// DecryptedSize calculates the size of the data when decrypted
|
||||||
func (c *cipher) DecryptedSize(size int64) (int64, error) {
|
func (c *Cipher) DecryptedSize(size int64) (int64, error) {
|
||||||
size -= int64(fileHeaderSize)
|
size -= int64(fileHeaderSize)
|
||||||
if size < 0 {
|
if size < 0 {
|
||||||
return 0, ErrorEncryptedFileTooShort
|
return 0, ErrorEncryptedFileTooShort
|
||||||
@@ -1063,7 +1043,6 @@ func (c *cipher) DecryptedSize(size int64) (int64, error) {
|
|||||||
|
|
||||||
// check interfaces
|
// check interfaces
|
||||||
var (
|
var (
|
||||||
_ Cipher = (*cipher)(nil)
|
|
||||||
_ io.ReadCloser = (*decrypter)(nil)
|
_ io.ReadCloser = (*decrypter)(nil)
|
||||||
_ io.Seeker = (*decrypter)(nil)
|
_ io.Seeker = (*decrypter)(nil)
|
||||||
_ fs.RangeSeeker = (*decrypter)(nil)
|
_ fs.RangeSeeker = (*decrypter)(nil)
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import (
|
|||||||
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"github.com/rclone/rclone/backend/crypt/pkcs7"
|
"github.com/rclone/rclone/backend/crypt/pkcs7"
|
||||||
|
"github.com/rclone/rclone/lib/readers"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
@@ -784,7 +785,7 @@ func TestNewEncrypterErrUnexpectedEOF(t *testing.T) {
|
|||||||
c, err := newCipher(NameEncryptionStandard, "", "", true)
|
c, err := newCipher(NameEncryptionStandard, "", "", true)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
|
||||||
in := &errorReader{io.ErrUnexpectedEOF}
|
in := &readers.ErrorReader{Err: io.ErrUnexpectedEOF}
|
||||||
fh, err := c.newEncrypter(in, nil)
|
fh, err := c.newEncrypter(in, nil)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
|
||||||
@@ -793,14 +794,6 @@ func TestNewEncrypterErrUnexpectedEOF(t *testing.T) {
|
|||||||
assert.Equal(t, int64(32), n)
|
assert.Equal(t, int64(32), n)
|
||||||
}
|
}
|
||||||
|
|
||||||
type errorReader struct {
|
|
||||||
err error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (er errorReader) Read(p []byte) (n int, err error) {
|
|
||||||
return 0, er.err
|
|
||||||
}
|
|
||||||
|
|
||||||
type closeDetector struct {
|
type closeDetector struct {
|
||||||
io.Reader
|
io.Reader
|
||||||
closed int
|
closed int
|
||||||
@@ -838,7 +831,7 @@ func TestNewDecrypter(t *testing.T) {
|
|||||||
assert.Equal(t, 1, cd.closed)
|
assert.Equal(t, 1, cd.closed)
|
||||||
}
|
}
|
||||||
|
|
||||||
er := &errorReader{errors.New("potato")}
|
er := &readers.ErrorReader{Err: errors.New("potato")}
|
||||||
cd = newCloseDetector(er)
|
cd = newCloseDetector(er)
|
||||||
fh, err = c.newDecrypter(cd)
|
fh, err = c.newDecrypter(cd)
|
||||||
assert.Nil(t, fh)
|
assert.Nil(t, fh)
|
||||||
@@ -864,7 +857,7 @@ func TestNewDecrypterErrUnexpectedEOF(t *testing.T) {
|
|||||||
c, err := newCipher(NameEncryptionStandard, "", "", true)
|
c, err := newCipher(NameEncryptionStandard, "", "", true)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
|
||||||
in2 := &errorReader{io.ErrUnexpectedEOF}
|
in2 := &readers.ErrorReader{Err: io.ErrUnexpectedEOF}
|
||||||
in1 := bytes.NewBuffer(file16)
|
in1 := bytes.NewBuffer(file16)
|
||||||
in := ioutil.NopCloser(io.MultiReader(in1, in2))
|
in := ioutil.NopCloser(io.MultiReader(in1, in2))
|
||||||
|
|
||||||
@@ -936,7 +929,7 @@ func TestNewDecrypterSeekLimit(t *testing.T) {
|
|||||||
assert.Equal(t, 0, n)
|
assert.Equal(t, 0, n)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Now try decoding it with a open/seek
|
// Now try decoding it with an open/seek
|
||||||
for _, offset := range trials {
|
for _, offset := range trials {
|
||||||
for _, limit := range limits {
|
for _, limit := range limits {
|
||||||
if offset+limit > len(plaintext) {
|
if offset+limit > len(plaintext) {
|
||||||
@@ -1118,7 +1111,7 @@ func TestDecrypterRead(t *testing.T) {
|
|||||||
|
|
||||||
// Test producing an error on the file on Read the underlying file
|
// Test producing an error on the file on Read the underlying file
|
||||||
in1 := bytes.NewBuffer(file1)
|
in1 := bytes.NewBuffer(file1)
|
||||||
in2 := &errorReader{errors.New("potato")}
|
in2 := &readers.ErrorReader{Err: errors.New("potato")}
|
||||||
in := io.MultiReader(in1, in2)
|
in := io.MultiReader(in1, in2)
|
||||||
cd := newCloseDetector(in)
|
cd := newCloseDetector(in)
|
||||||
fh, err := c.newDecrypter(cd)
|
fh, err := c.newDecrypter(cd)
|
||||||
|
|||||||
+189
-62
@@ -5,12 +5,14 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"path"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"github.com/rclone/rclone/fs"
|
"github.com/rclone/rclone/fs"
|
||||||
"github.com/rclone/rclone/fs/accounting"
|
"github.com/rclone/rclone/fs/accounting"
|
||||||
|
"github.com/rclone/rclone/fs/cache"
|
||||||
"github.com/rclone/rclone/fs/config/configmap"
|
"github.com/rclone/rclone/fs/config/configmap"
|
||||||
"github.com/rclone/rclone/fs/config/configstruct"
|
"github.com/rclone/rclone/fs/config/configstruct"
|
||||||
"github.com/rclone/rclone/fs/config/obscure"
|
"github.com/rclone/rclone/fs/config/obscure"
|
||||||
@@ -25,9 +27,10 @@ func init() {
|
|||||||
Name: "crypt",
|
Name: "crypt",
|
||||||
Description: "Encrypt/Decrypt a remote",
|
Description: "Encrypt/Decrypt a remote",
|
||||||
NewFs: NewFs,
|
NewFs: NewFs,
|
||||||
|
CommandHelp: commandHelp,
|
||||||
Options: []fs.Option{{
|
Options: []fs.Option{{
|
||||||
Name: "remote",
|
Name: "remote",
|
||||||
Help: "Remote to encrypt/decrypt.\nNormally should contain a ':' and a path, eg \"myremote:path/to/dir\",\n\"myremote:bucket\" or maybe \"myremote:\" (not recommended).",
|
Help: "Remote to encrypt/decrypt.\nNormally should contain a ':' and a path, e.g. \"myremote:path/to/dir\",\n\"myremote:bucket\" or maybe \"myremote:\" (not recommended).",
|
||||||
Required: true,
|
Required: true,
|
||||||
}, {
|
}, {
|
||||||
Name: "filename_encryption",
|
Name: "filename_encryption",
|
||||||
@@ -35,19 +38,21 @@ func init() {
|
|||||||
Default: "standard",
|
Default: "standard",
|
||||||
Examples: []fs.OptionExample{
|
Examples: []fs.OptionExample{
|
||||||
{
|
{
|
||||||
Value: "off",
|
|
||||||
Help: "Don't encrypt the file names. Adds a \".bin\" extension only.",
|
|
||||||
}, {
|
|
||||||
Value: "standard",
|
Value: "standard",
|
||||||
Help: "Encrypt the filenames see the docs for the details.",
|
Help: "Encrypt the filenames see the docs for the details.",
|
||||||
}, {
|
}, {
|
||||||
Value: "obfuscate",
|
Value: "obfuscate",
|
||||||
Help: "Very simple filename obfuscation.",
|
Help: "Very simple filename obfuscation.",
|
||||||
|
}, {
|
||||||
|
Value: "off",
|
||||||
|
Help: "Don't encrypt the file names. Adds a \".bin\" extension only.",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}, {
|
}, {
|
||||||
Name: "directory_name_encryption",
|
Name: "directory_name_encryption",
|
||||||
Help: "Option to either encrypt directory names or leave them intact.",
|
Help: `Option to either encrypt directory names or leave them intact.
|
||||||
|
|
||||||
|
NB If filename_encryption is "off" then this option will do nothing.`,
|
||||||
Default: true,
|
Default: true,
|
||||||
Examples: []fs.OptionExample{
|
Examples: []fs.OptionExample{
|
||||||
{
|
{
|
||||||
@@ -68,6 +73,20 @@ func init() {
|
|||||||
Name: "password2",
|
Name: "password2",
|
||||||
Help: "Password or pass phrase for salt. Optional but recommended.\nShould be different to the previous password.",
|
Help: "Password or pass phrase for salt. Optional but recommended.\nShould be different to the previous password.",
|
||||||
IsPassword: true,
|
IsPassword: true,
|
||||||
|
}, {
|
||||||
|
Name: "server_side_across_configs",
|
||||||
|
Default: false,
|
||||||
|
Help: `Allow server-side operations (e.g. copy) to work across different crypt configs.
|
||||||
|
|
||||||
|
Normally this option is not what you want, but if you have two crypts
|
||||||
|
pointing to the same backend you can use it.
|
||||||
|
|
||||||
|
This can be used, for example, to change file name encryption type
|
||||||
|
without re-uploading all the data. Just make two crypt backends
|
||||||
|
pointing to two different directories with the single changed
|
||||||
|
parameter and use rclone move to move the files between the crypt
|
||||||
|
remotes.`,
|
||||||
|
Advanced: true,
|
||||||
}, {
|
}, {
|
||||||
Name: "show_mapping",
|
Name: "show_mapping",
|
||||||
Help: `For all files listed show how the names encrypt.
|
Help: `For all files listed show how the names encrypt.
|
||||||
@@ -87,7 +106,7 @@ names, or for debugging purposes.`,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// newCipherForConfig constructs a Cipher for the given config name
|
// newCipherForConfig constructs a Cipher for the given config name
|
||||||
func newCipherForConfig(opt *Options) (Cipher, error) {
|
func newCipherForConfig(opt *Options) (*Cipher, error) {
|
||||||
mode, err := NewNameEncryptionMode(opt.FilenameEncryption)
|
mode, err := NewNameEncryptionMode(opt.FilenameEncryption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -114,7 +133,7 @@ func newCipherForConfig(opt *Options) (Cipher, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// NewCipher constructs a Cipher for the given config
|
// NewCipher constructs a Cipher for the given config
|
||||||
func NewCipher(m configmap.Mapper) (Cipher, error) {
|
func NewCipher(m configmap.Mapper) (*Cipher, error) {
|
||||||
// Parse config into Options struct
|
// Parse config into Options struct
|
||||||
opt := new(Options)
|
opt := new(Options)
|
||||||
err := configstruct.Set(m, opt)
|
err := configstruct.Set(m, opt)
|
||||||
@@ -125,7 +144,7 @@ func NewCipher(m configmap.Mapper) (Cipher, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// NewFs constructs an Fs from the path, container:path
|
// NewFs constructs an Fs from the path, container:path
|
||||||
func NewFs(name, rpath string, m configmap.Mapper) (fs.Fs, error) {
|
func NewFs(ctx context.Context, name, rpath string, m configmap.Mapper) (fs.Fs, error) {
|
||||||
// Parse config into Options struct
|
// Parse config into Options struct
|
||||||
opt := new(Options)
|
opt := new(Options)
|
||||||
err := configstruct.Set(m, opt)
|
err := configstruct.Set(m, opt)
|
||||||
@@ -140,20 +159,25 @@ func NewFs(name, rpath string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
if strings.HasPrefix(remote, name+":") {
|
if strings.HasPrefix(remote, name+":") {
|
||||||
return nil, errors.New("can't point crypt remote at itself - check the value of the remote setting")
|
return nil, errors.New("can't point crypt remote at itself - check the value of the remote setting")
|
||||||
}
|
}
|
||||||
wInfo, wName, wPath, wConfig, err := fs.ConfigFs(remote)
|
// Make sure to remove trailing . referring to the current dir
|
||||||
if err != nil {
|
if path.Base(rpath) == "." {
|
||||||
return nil, errors.Wrapf(err, "failed to parse remote %q to wrap", remote)
|
rpath = strings.TrimSuffix(rpath, ".")
|
||||||
}
|
}
|
||||||
// Look for a file first
|
// Look for a file first
|
||||||
remotePath := fspath.JoinRootPath(wPath, cipher.EncryptFileName(rpath))
|
var wrappedFs fs.Fs
|
||||||
wrappedFs, err := wInfo.NewFs(wName, remotePath, wConfig)
|
if rpath == "" {
|
||||||
// if that didn't produce a file, look for a directory
|
wrappedFs, err = cache.Get(ctx, remote)
|
||||||
if err != fs.ErrorIsFile {
|
} else {
|
||||||
remotePath = fspath.JoinRootPath(wPath, cipher.EncryptDirName(rpath))
|
remotePath := fspath.JoinRootPath(remote, cipher.EncryptFileName(rpath))
|
||||||
wrappedFs, err = wInfo.NewFs(wName, remotePath, wConfig)
|
wrappedFs, err = cache.Get(ctx, remotePath)
|
||||||
|
// if that didn't produce a file, look for a directory
|
||||||
|
if err != fs.ErrorIsFile {
|
||||||
|
remotePath = fspath.JoinRootPath(remote, cipher.EncryptDirName(rpath))
|
||||||
|
wrappedFs, err = cache.Get(ctx, remotePath)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if err != fs.ErrorIsFile && err != nil {
|
if err != fs.ErrorIsFile && err != nil {
|
||||||
return nil, errors.Wrapf(err, "failed to make remote %s:%q to wrap", wName, remotePath)
|
return nil, errors.Wrapf(err, "failed to make remote %q to wrap", remote)
|
||||||
}
|
}
|
||||||
f := &Fs{
|
f := &Fs{
|
||||||
Fs: wrappedFs,
|
Fs: wrappedFs,
|
||||||
@@ -162,6 +186,7 @@ func NewFs(name, rpath string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
opt: *opt,
|
opt: *opt,
|
||||||
cipher: cipher,
|
cipher: cipher,
|
||||||
}
|
}
|
||||||
|
cache.PinUntilFinalized(f.Fs, f)
|
||||||
// the features here are ones we could support, and they are
|
// the features here are ones we could support, and they are
|
||||||
// ANDed with the ones from wrappedFs
|
// ANDed with the ones from wrappedFs
|
||||||
f.features = (&fs.Features{
|
f.features = (&fs.Features{
|
||||||
@@ -173,7 +198,8 @@ func NewFs(name, rpath string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
CanHaveEmptyDirectories: true,
|
CanHaveEmptyDirectories: true,
|
||||||
SetTier: true,
|
SetTier: true,
|
||||||
GetTier: true,
|
GetTier: true,
|
||||||
}).Fill(f).Mask(wrappedFs).WrapsFs(f, wrappedFs)
|
ServerSideAcrossConfigs: opt.ServerSideAcrossConfigs,
|
||||||
|
}).Fill(ctx, f).Mask(ctx, wrappedFs).WrapsFs(f, wrappedFs)
|
||||||
|
|
||||||
return f, err
|
return f, err
|
||||||
}
|
}
|
||||||
@@ -185,6 +211,7 @@ type Options struct {
|
|||||||
DirectoryNameEncryption bool `config:"directory_name_encryption"`
|
DirectoryNameEncryption bool `config:"directory_name_encryption"`
|
||||||
Password string `config:"password"`
|
Password string `config:"password"`
|
||||||
Password2 string `config:"password2"`
|
Password2 string `config:"password2"`
|
||||||
|
ServerSideAcrossConfigs bool `config:"server_side_across_configs"`
|
||||||
ShowMapping bool `config:"show_mapping"`
|
ShowMapping bool `config:"show_mapping"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -196,7 +223,7 @@ type Fs struct {
|
|||||||
root string
|
root string
|
||||||
opt Options
|
opt Options
|
||||||
features *fs.Features // optional features
|
features *fs.Features // optional features
|
||||||
cipher Cipher
|
cipher *Cipher
|
||||||
}
|
}
|
||||||
|
|
||||||
// Name of the remote (as passed into NewFs)
|
// Name of the remote (as passed into NewFs)
|
||||||
@@ -233,7 +260,7 @@ func (f *Fs) add(entries *fs.DirEntries, obj fs.Object) {
|
|||||||
*entries = append(*entries, f.newObject(obj))
|
*entries = append(*entries, f.newObject(obj))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Encrypt an directory file name to entries.
|
// Encrypt a directory file name to entries.
|
||||||
func (f *Fs) addDir(ctx context.Context, entries *fs.DirEntries, dir fs.Directory) {
|
func (f *Fs) addDir(ctx context.Context, entries *fs.DirEntries, dir fs.Directory) {
|
||||||
remote := dir.Remote()
|
remote := dir.Remote()
|
||||||
decryptedRemote, err := f.cipher.DecryptDirName(remote)
|
decryptedRemote, err := f.cipher.DecryptDirName(remote)
|
||||||
@@ -320,7 +347,7 @@ type putFn func(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ..
|
|||||||
// put implements Put or PutStream
|
// put implements Put or PutStream
|
||||||
func (f *Fs) put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options []fs.OpenOption, put putFn) (fs.Object, error) {
|
func (f *Fs) put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options []fs.OpenOption, put putFn) (fs.Object, error) {
|
||||||
// Encrypt the data into wrappedIn
|
// Encrypt the data into wrappedIn
|
||||||
wrappedIn, err := f.cipher.EncryptData(in)
|
wrappedIn, encrypter, err := f.cipher.encryptData(in)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -344,7 +371,7 @@ func (f *Fs) put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options [
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Transfer the data
|
// Transfer the data
|
||||||
o, err := put(ctx, wrappedIn, f.newObjectInfo(src), options...)
|
o, err := put(ctx, wrappedIn, f.newObjectInfo(src, encrypter.nonce), options...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -403,21 +430,21 @@ func (f *Fs) Rmdir(ctx context.Context, dir string) error {
|
|||||||
return f.Fs.Rmdir(ctx, f.cipher.EncryptDirName(dir))
|
return f.Fs.Rmdir(ctx, f.cipher.EncryptDirName(dir))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Purge all files in the root and the root directory
|
// Purge all files in the directory specified
|
||||||
//
|
//
|
||||||
// Implement this if you have a way of deleting all the files
|
// Implement this if you have a way of deleting all the files
|
||||||
// quicker than just running Remove() on the result of List()
|
// quicker than just running Remove() on the result of List()
|
||||||
//
|
//
|
||||||
// Return an error if it doesn't exist
|
// Return an error if it doesn't exist
|
||||||
func (f *Fs) Purge(ctx context.Context) error {
|
func (f *Fs) Purge(ctx context.Context, dir string) error {
|
||||||
do := f.Fs.Features().Purge
|
do := f.Fs.Features().Purge
|
||||||
if do == nil {
|
if do == nil {
|
||||||
return fs.ErrorCantPurge
|
return fs.ErrorCantPurge
|
||||||
}
|
}
|
||||||
return do(ctx)
|
return do(ctx, f.cipher.EncryptDirName(dir))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Copy src to this remote using server side copy operations.
|
// Copy src to this remote using server-side copy operations.
|
||||||
//
|
//
|
||||||
// This is stored with the remote path given
|
// This is stored with the remote path given
|
||||||
//
|
//
|
||||||
@@ -442,7 +469,7 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
return f.newObject(oResult), nil
|
return f.newObject(oResult), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Move src to this remote using server side move operations.
|
// Move src to this remote using server-side move operations.
|
||||||
//
|
//
|
||||||
// This is stored with the remote path given
|
// This is stored with the remote path given
|
||||||
//
|
//
|
||||||
@@ -468,7 +495,7 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DirMove moves src, srcRemote to this remote at dstRemote
|
// DirMove moves src, srcRemote to this remote at dstRemote
|
||||||
// using server side move operations.
|
// using server-side move operations.
|
||||||
//
|
//
|
||||||
// Will only be called if src.Fs().Name() == f.Name()
|
// Will only be called if src.Fs().Name() == f.Name()
|
||||||
//
|
//
|
||||||
@@ -497,11 +524,11 @@ func (f *Fs) PutUnchecked(ctx context.Context, in io.Reader, src fs.ObjectInfo,
|
|||||||
if do == nil {
|
if do == nil {
|
||||||
return nil, errors.New("can't PutUnchecked")
|
return nil, errors.New("can't PutUnchecked")
|
||||||
}
|
}
|
||||||
wrappedIn, err := f.cipher.EncryptData(in)
|
wrappedIn, encrypter, err := f.cipher.encryptData(in)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
o, err := do(ctx, wrappedIn, f.newObjectInfo(src))
|
o, err := do(ctx, wrappedIn, f.newObjectInfo(src, encrypter.nonce))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -554,6 +581,37 @@ func (f *Fs) DecryptFileName(encryptedFileName string) (string, error) {
|
|||||||
return f.cipher.DecryptFileName(encryptedFileName)
|
return f.cipher.DecryptFileName(encryptedFileName)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// computeHashWithNonce takes the nonce and encrypts the contents of
|
||||||
|
// src with it, and calculates the hash given by HashType on the fly
|
||||||
|
//
|
||||||
|
// Note that we break lots of encapsulation in this function.
|
||||||
|
func (f *Fs) computeHashWithNonce(ctx context.Context, nonce nonce, src fs.Object, hashType hash.Type) (hashStr string, err error) {
|
||||||
|
// Open the src for input
|
||||||
|
in, err := src.Open(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return "", errors.Wrap(err, "failed to open src")
|
||||||
|
}
|
||||||
|
defer fs.CheckClose(in, &err)
|
||||||
|
|
||||||
|
// Now encrypt the src with the nonce
|
||||||
|
out, err := f.cipher.newEncrypter(in, &nonce)
|
||||||
|
if err != nil {
|
||||||
|
return "", errors.Wrap(err, "failed to make encrypter")
|
||||||
|
}
|
||||||
|
|
||||||
|
// pipe into hash
|
||||||
|
m, err := hash.NewMultiHasherTypes(hash.NewHashSet(hashType))
|
||||||
|
if err != nil {
|
||||||
|
return "", errors.Wrap(err, "failed to make hasher")
|
||||||
|
}
|
||||||
|
_, err = io.Copy(m, out)
|
||||||
|
if err != nil {
|
||||||
|
return "", errors.Wrap(err, "failed to hash data")
|
||||||
|
}
|
||||||
|
|
||||||
|
return m.Sums()[hashType], nil
|
||||||
|
}
|
||||||
|
|
||||||
// ComputeHash takes the nonce from o, and encrypts the contents of
|
// ComputeHash takes the nonce from o, and encrypts the contents of
|
||||||
// src with it, and calculates the hash given by HashType on the fly
|
// src with it, and calculates the hash given by HashType on the fly
|
||||||
//
|
//
|
||||||
@@ -565,7 +623,7 @@ func (f *Fs) ComputeHash(ctx context.Context, o *Object, src fs.Object, hashType
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return "", errors.Wrap(err, "failed to open object to read nonce")
|
return "", errors.Wrap(err, "failed to open object to read nonce")
|
||||||
}
|
}
|
||||||
d, err := f.cipher.(*cipher).newDecrypter(in)
|
d, err := f.cipher.newDecrypter(in)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = in.Close()
|
_ = in.Close()
|
||||||
return "", errors.Wrap(err, "failed to open object to read nonce")
|
return "", errors.Wrap(err, "failed to open object to read nonce")
|
||||||
@@ -590,30 +648,7 @@ func (f *Fs) ComputeHash(ctx context.Context, o *Object, src fs.Object, hashType
|
|||||||
return "", errors.Wrap(err, "failed to close nonce read")
|
return "", errors.Wrap(err, "failed to close nonce read")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Open the src for input
|
return f.computeHashWithNonce(ctx, nonce, src, hashType)
|
||||||
in, err = src.Open(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return "", errors.Wrap(err, "failed to open src")
|
|
||||||
}
|
|
||||||
defer fs.CheckClose(in, &err)
|
|
||||||
|
|
||||||
// Now encrypt the src with the nonce
|
|
||||||
out, err := f.cipher.(*cipher).newEncrypter(in, &nonce)
|
|
||||||
if err != nil {
|
|
||||||
return "", errors.Wrap(err, "failed to make encrypter")
|
|
||||||
}
|
|
||||||
|
|
||||||
// pipe into hash
|
|
||||||
m, err := hash.NewMultiHasherTypes(hash.NewHashSet(hashType))
|
|
||||||
if err != nil {
|
|
||||||
return "", errors.Wrap(err, "failed to make hasher")
|
|
||||||
}
|
|
||||||
_, err = io.Copy(m, out)
|
|
||||||
if err != nil {
|
|
||||||
return "", errors.Wrap(err, "failed to hash data")
|
|
||||||
}
|
|
||||||
|
|
||||||
return m.Sums()[hashType], nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// MergeDirs merges the contents of all the directories passed
|
// MergeDirs merges the contents of all the directories passed
|
||||||
@@ -640,7 +675,7 @@ func (f *Fs) DirCacheFlush() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// PublicLink generates a public link to the remote path (usually readable by anyone)
|
// PublicLink generates a public link to the remote path (usually readable by anyone)
|
||||||
func (f *Fs) PublicLink(ctx context.Context, remote string) (string, error) {
|
func (f *Fs) PublicLink(ctx context.Context, remote string, expire fs.Duration, unlink bool) (string, error) {
|
||||||
do := f.Fs.Features().PublicLink
|
do := f.Fs.Features().PublicLink
|
||||||
if do == nil {
|
if do == nil {
|
||||||
return "", errors.New("PublicLink not supported")
|
return "", errors.New("PublicLink not supported")
|
||||||
@@ -648,9 +683,9 @@ func (f *Fs) PublicLink(ctx context.Context, remote string) (string, error) {
|
|||||||
o, err := f.NewObject(ctx, remote)
|
o, err := f.NewObject(ctx, remote)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// assume it is a directory
|
// assume it is a directory
|
||||||
return do(ctx, f.cipher.EncryptDirName(remote))
|
return do(ctx, f.cipher.EncryptDirName(remote), expire, unlink)
|
||||||
}
|
}
|
||||||
return do(ctx, o.(*Object).Object.Remote())
|
return do(ctx, o.(*Object).Object.Remote(), expire, unlink)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ChangeNotify calls the passed function with a path
|
// ChangeNotify calls the passed function with a path
|
||||||
@@ -685,6 +720,67 @@ func (f *Fs) ChangeNotify(ctx context.Context, notifyFunc func(string, fs.EntryT
|
|||||||
do(ctx, wrappedNotifyFunc, pollIntervalChan)
|
do(ctx, wrappedNotifyFunc, pollIntervalChan)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var commandHelp = []fs.CommandHelp{
|
||||||
|
{
|
||||||
|
Name: "encode",
|
||||||
|
Short: "Encode the given filename(s)",
|
||||||
|
Long: `This encodes the filenames given as arguments returning a list of
|
||||||
|
strings of the encoded results.
|
||||||
|
|
||||||
|
Usage Example:
|
||||||
|
|
||||||
|
rclone backend encode crypt: file1 [file2...]
|
||||||
|
rclone rc backend/command command=encode fs=crypt: file1 [file2...]
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "decode",
|
||||||
|
Short: "Decode the given filename(s)",
|
||||||
|
Long: `This decodes the filenames given as arguments returning a list of
|
||||||
|
strings of the decoded results. It will return an error if any of the
|
||||||
|
inputs are invalid.
|
||||||
|
|
||||||
|
Usage Example:
|
||||||
|
|
||||||
|
rclone backend decode crypt: encryptedfile1 [encryptedfile2...]
|
||||||
|
rclone rc backend/command command=decode fs=crypt: encryptedfile1 [encryptedfile2...]
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// Command the backend to run a named command
|
||||||
|
//
|
||||||
|
// The command run is name
|
||||||
|
// args may be used to read arguments from
|
||||||
|
// opts may be used to read optional arguments from
|
||||||
|
//
|
||||||
|
// The result should be capable of being JSON encoded
|
||||||
|
// If it is a string or a []string it will be shown to the user
|
||||||
|
// otherwise it will be JSON encoded and shown to the user like that
|
||||||
|
func (f *Fs) Command(ctx context.Context, name string, arg []string, opt map[string]string) (out interface{}, err error) {
|
||||||
|
switch name {
|
||||||
|
case "decode":
|
||||||
|
out := make([]string, 0, len(arg))
|
||||||
|
for _, encryptedFileName := range arg {
|
||||||
|
fileName, err := f.DecryptFileName(encryptedFileName)
|
||||||
|
if err != nil {
|
||||||
|
return out, errors.Wrap(err, fmt.Sprintf("Failed to decrypt : %s", encryptedFileName))
|
||||||
|
}
|
||||||
|
out = append(out, fileName)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
case "encode":
|
||||||
|
out := make([]string, 0, len(arg))
|
||||||
|
for _, fileName := range arg {
|
||||||
|
encryptedFileName := f.EncryptFileName(fileName)
|
||||||
|
out = append(out, encryptedFileName)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
default:
|
||||||
|
return nil, fs.ErrorCommandNotFound
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Object describes a wrapped for being read from the Fs
|
// Object describes a wrapped for being read from the Fs
|
||||||
//
|
//
|
||||||
// This decrypts the remote name and decrypts the data
|
// This decrypts the remote name and decrypts the data
|
||||||
@@ -821,18 +917,30 @@ func (f *Fs) Disconnect(ctx context.Context) error {
|
|||||||
return do(ctx)
|
return do(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Shutdown the backend, closing any background tasks and any
|
||||||
|
// cached connections.
|
||||||
|
func (f *Fs) Shutdown(ctx context.Context) error {
|
||||||
|
do := f.Fs.Features().Shutdown
|
||||||
|
if do == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return do(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
// ObjectInfo describes a wrapped fs.ObjectInfo for being the source
|
// ObjectInfo describes a wrapped fs.ObjectInfo for being the source
|
||||||
//
|
//
|
||||||
// This encrypts the remote name and adjusts the size
|
// This encrypts the remote name and adjusts the size
|
||||||
type ObjectInfo struct {
|
type ObjectInfo struct {
|
||||||
fs.ObjectInfo
|
fs.ObjectInfo
|
||||||
f *Fs
|
f *Fs
|
||||||
|
nonce nonce
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fs) newObjectInfo(src fs.ObjectInfo) *ObjectInfo {
|
func (f *Fs) newObjectInfo(src fs.ObjectInfo, nonce nonce) *ObjectInfo {
|
||||||
return &ObjectInfo{
|
return &ObjectInfo{
|
||||||
ObjectInfo: src,
|
ObjectInfo: src,
|
||||||
f: f,
|
f: f,
|
||||||
|
nonce: nonce,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -858,6 +966,23 @@ func (o *ObjectInfo) Size() int64 {
|
|||||||
// Hash returns the selected checksum of the file
|
// Hash returns the selected checksum of the file
|
||||||
// If no checksum is available it returns ""
|
// If no checksum is available it returns ""
|
||||||
func (o *ObjectInfo) Hash(ctx context.Context, hash hash.Type) (string, error) {
|
func (o *ObjectInfo) Hash(ctx context.Context, hash hash.Type) (string, error) {
|
||||||
|
var srcObj fs.Object
|
||||||
|
var ok bool
|
||||||
|
// Get the underlying object if there is one
|
||||||
|
if srcObj, ok = o.ObjectInfo.(fs.Object); ok {
|
||||||
|
// Prefer direct interface assertion
|
||||||
|
} else if do, ok := o.ObjectInfo.(fs.ObjectUnWrapper); ok {
|
||||||
|
// Otherwise likely is an operations.OverrideRemote
|
||||||
|
srcObj = do.UnWrap()
|
||||||
|
} else {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
// if this is wrapping a local object then we work out the hash
|
||||||
|
if srcObj.Fs().Features().IsLocal {
|
||||||
|
// Read the data and encrypt it to calculate the hash
|
||||||
|
fs.Debugf(o, "Computing %v hash of encrypted source", hash)
|
||||||
|
return o.f.computeHashWithNonce(ctx, o.nonce, srcObj, hash)
|
||||||
|
}
|
||||||
return "", nil
|
return "", nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -896,6 +1021,7 @@ var (
|
|||||||
_ fs.Copier = (*Fs)(nil)
|
_ fs.Copier = (*Fs)(nil)
|
||||||
_ fs.Mover = (*Fs)(nil)
|
_ fs.Mover = (*Fs)(nil)
|
||||||
_ fs.DirMover = (*Fs)(nil)
|
_ fs.DirMover = (*Fs)(nil)
|
||||||
|
_ fs.Commander = (*Fs)(nil)
|
||||||
_ fs.PutUncheckeder = (*Fs)(nil)
|
_ fs.PutUncheckeder = (*Fs)(nil)
|
||||||
_ fs.PutStreamer = (*Fs)(nil)
|
_ fs.PutStreamer = (*Fs)(nil)
|
||||||
_ fs.CleanUpper = (*Fs)(nil)
|
_ fs.CleanUpper = (*Fs)(nil)
|
||||||
@@ -909,6 +1035,7 @@ var (
|
|||||||
_ fs.PublicLinker = (*Fs)(nil)
|
_ fs.PublicLinker = (*Fs)(nil)
|
||||||
_ fs.UserInfoer = (*Fs)(nil)
|
_ fs.UserInfoer = (*Fs)(nil)
|
||||||
_ fs.Disconnecter = (*Fs)(nil)
|
_ fs.Disconnecter = (*Fs)(nil)
|
||||||
|
_ fs.Shutdowner = (*Fs)(nil)
|
||||||
_ fs.ObjectInfo = (*ObjectInfo)(nil)
|
_ fs.ObjectInfo = (*ObjectInfo)(nil)
|
||||||
_ fs.Object = (*Object)(nil)
|
_ fs.Object = (*Object)(nil)
|
||||||
_ fs.ObjectUnWrapper = (*Object)(nil)
|
_ fs.ObjectUnWrapper = (*Object)(nil)
|
||||||
|
|||||||
@@ -0,0 +1,143 @@
|
|||||||
|
package crypt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/md5"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/rclone/rclone/fs"
|
||||||
|
"github.com/rclone/rclone/fs/hash"
|
||||||
|
"github.com/rclone/rclone/fs/object"
|
||||||
|
"github.com/rclone/rclone/lib/random"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
type testWrapper struct {
|
||||||
|
fs.ObjectInfo
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnWrap returns the Object that this Object is wrapping or nil if it
|
||||||
|
// isn't wrapping anything
|
||||||
|
func (o testWrapper) UnWrap() fs.Object {
|
||||||
|
if o, ok := o.ObjectInfo.(fs.Object); ok {
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create a temporary local fs to upload things from
|
||||||
|
|
||||||
|
func makeTempLocalFs(t *testing.T) (localFs fs.Fs, cleanup func()) {
|
||||||
|
localFs, err := fs.TemporaryLocalFs(context.Background())
|
||||||
|
require.NoError(t, err)
|
||||||
|
cleanup = func() {
|
||||||
|
require.NoError(t, localFs.Rmdir(context.Background(), ""))
|
||||||
|
}
|
||||||
|
return localFs, cleanup
|
||||||
|
}
|
||||||
|
|
||||||
|
// Upload a file to a remote
|
||||||
|
func uploadFile(t *testing.T, f fs.Fs, remote, contents string) (obj fs.Object, cleanup func()) {
|
||||||
|
inBuf := bytes.NewBufferString(contents)
|
||||||
|
t1 := time.Date(2012, time.December, 17, 18, 32, 31, 0, time.UTC)
|
||||||
|
upSrc := object.NewStaticObjectInfo(remote, t1, int64(len(contents)), true, nil, nil)
|
||||||
|
obj, err := f.Put(context.Background(), inBuf, upSrc)
|
||||||
|
require.NoError(t, err)
|
||||||
|
cleanup = func() {
|
||||||
|
require.NoError(t, obj.Remove(context.Background()))
|
||||||
|
}
|
||||||
|
return obj, cleanup
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test the ObjectInfo
|
||||||
|
func testObjectInfo(t *testing.T, f *Fs, wrap bool) {
|
||||||
|
var (
|
||||||
|
contents = random.String(100)
|
||||||
|
path = "hash_test_object"
|
||||||
|
ctx = context.Background()
|
||||||
|
)
|
||||||
|
if wrap {
|
||||||
|
path = "_wrap"
|
||||||
|
}
|
||||||
|
|
||||||
|
localFs, cleanupLocalFs := makeTempLocalFs(t)
|
||||||
|
defer cleanupLocalFs()
|
||||||
|
|
||||||
|
obj, cleanupObj := uploadFile(t, localFs, path, contents)
|
||||||
|
defer cleanupObj()
|
||||||
|
|
||||||
|
// encrypt the data
|
||||||
|
inBuf := bytes.NewBufferString(contents)
|
||||||
|
var outBuf bytes.Buffer
|
||||||
|
enc, err := f.cipher.newEncrypter(inBuf, nil)
|
||||||
|
require.NoError(t, err)
|
||||||
|
nonce := enc.nonce // read the nonce at the start
|
||||||
|
_, err = io.Copy(&outBuf, enc)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
var oi fs.ObjectInfo = obj
|
||||||
|
if wrap {
|
||||||
|
// wrap the object in an fs.ObjectUnwrapper if required
|
||||||
|
oi = testWrapper{oi}
|
||||||
|
}
|
||||||
|
|
||||||
|
// wrap the object in a crypt for upload using the nonce we
|
||||||
|
// saved from the encrypter
|
||||||
|
src := f.newObjectInfo(oi, nonce)
|
||||||
|
|
||||||
|
// Test ObjectInfo methods
|
||||||
|
assert.Equal(t, int64(outBuf.Len()), src.Size())
|
||||||
|
assert.Equal(t, f, src.Fs())
|
||||||
|
assert.NotEqual(t, path, src.Remote())
|
||||||
|
|
||||||
|
// Test ObjectInfo.Hash
|
||||||
|
wantHash := md5.Sum(outBuf.Bytes())
|
||||||
|
gotHash, err := src.Hash(ctx, hash.MD5)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, fmt.Sprintf("%x", wantHash), gotHash)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testComputeHash(t *testing.T, f *Fs) {
|
||||||
|
var (
|
||||||
|
contents = random.String(100)
|
||||||
|
path = "compute_hash_test"
|
||||||
|
ctx = context.Background()
|
||||||
|
hashType = f.Fs.Hashes().GetOne()
|
||||||
|
)
|
||||||
|
|
||||||
|
if hashType == hash.None {
|
||||||
|
t.Skipf("%v: does not support hashes", f.Fs)
|
||||||
|
}
|
||||||
|
|
||||||
|
localFs, cleanupLocalFs := makeTempLocalFs(t)
|
||||||
|
defer cleanupLocalFs()
|
||||||
|
|
||||||
|
// Upload a file to localFs as a test object
|
||||||
|
localObj, cleanupLocalObj := uploadFile(t, localFs, path, contents)
|
||||||
|
defer cleanupLocalObj()
|
||||||
|
|
||||||
|
// Upload the same data to the remote Fs also
|
||||||
|
remoteObj, cleanupRemoteObj := uploadFile(t, f, path, contents)
|
||||||
|
defer cleanupRemoteObj()
|
||||||
|
|
||||||
|
// Calculate the expected Hash of the remote object
|
||||||
|
computedHash, err := f.ComputeHash(ctx, remoteObj.(*Object), localObj, hashType)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
// Test computed hash matches remote object hash
|
||||||
|
remoteObjHash, err := remoteObj.(*Object).Object.Hash(ctx, hashType)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, remoteObjHash, computedHash)
|
||||||
|
}
|
||||||
|
|
||||||
|
// InternalTest is called by fstests.Run to extra tests
|
||||||
|
func (f *Fs) InternalTest(t *testing.T) {
|
||||||
|
t.Run("ObjectInfo", func(t *testing.T) { testObjectInfo(t, f, false) })
|
||||||
|
t.Run("ObjectInfoWrap", func(t *testing.T) { testObjectInfo(t, f, true) })
|
||||||
|
t.Run("ComputeHash", func(t *testing.T) { testComputeHash(t, f) })
|
||||||
|
}
|
||||||
Regular → Executable
+1224
-425
File diff suppressed because it is too large.
Load diff
@@ -7,15 +7,21 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"mime"
|
"mime"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
_ "github.com/rclone/rclone/backend/local"
|
_ "github.com/rclone/rclone/backend/local"
|
||||||
"github.com/rclone/rclone/fs"
|
"github.com/rclone/rclone/fs"
|
||||||
|
"github.com/rclone/rclone/fs/hash"
|
||||||
"github.com/rclone/rclone/fs/operations"
|
"github.com/rclone/rclone/fs/operations"
|
||||||
|
"github.com/rclone/rclone/fstest"
|
||||||
"github.com/rclone/rclone/fstest/fstests"
|
"github.com/rclone/rclone/fstest/fstests"
|
||||||
|
"github.com/rclone/rclone/lib/random"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
"google.golang.org/api/drive/v3"
|
"google.golang.org/api/drive/v3"
|
||||||
@@ -190,7 +196,7 @@ func (f *Fs) InternalTestDocumentImport(t *testing.T) {
|
|||||||
testFilesPath, err := filepath.Abs(filepath.FromSlash("test/files"))
|
testFilesPath, err := filepath.Abs(filepath.FromSlash("test/files"))
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
testFilesFs, err := fs.NewFs(testFilesPath)
|
testFilesFs, err := fs.NewFs(context.Background(), testFilesPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
_, f.importMimeTypes, err = parseExtensions("odt,ods,doc")
|
_, f.importMimeTypes, err = parseExtensions("odt,ods,doc")
|
||||||
@@ -204,7 +210,7 @@ func (f *Fs) InternalTestDocumentUpdate(t *testing.T) {
|
|||||||
testFilesPath, err := filepath.Abs(filepath.FromSlash("test/files"))
|
testFilesPath, err := filepath.Abs(filepath.FromSlash("test/files"))
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
testFilesFs, err := fs.NewFs(testFilesPath)
|
testFilesFs, err := fs.NewFs(context.Background(), testFilesPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
_, f.importMimeTypes, err = parseExtensions("odt,ods,doc")
|
_, f.importMimeTypes, err = parseExtensions("odt,ods,doc")
|
||||||
@@ -268,6 +274,192 @@ func (f *Fs) InternalTestDocumentLink(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
// from fstest/fstests/fstests.go
|
||||||
|
existingDir = "hello? sausage"
|
||||||
|
existingFile = `hello? sausage/êé/Hello, 世界/ " ' @ < > & ? + ≠/z.txt`
|
||||||
|
existingSubDir = "êé"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestIntegration/FsMkdir/FsPutFiles/Internal/Shortcuts
|
||||||
|
func (f *Fs) InternalTestShortcuts(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
srcObj, err := f.NewObject(ctx, existingFile)
|
||||||
|
require.NoError(t, err)
|
||||||
|
srcHash, err := srcObj.Hash(ctx, hash.MD5)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.NotEqual(t, "", srcHash)
|
||||||
|
t.Run("Errors", func(t *testing.T) {
|
||||||
|
_, err := f.makeShortcut(ctx, "", f, "")
|
||||||
|
assert.Error(t, err)
|
||||||
|
assert.Contains(t, err.Error(), "can't be root")
|
||||||
|
|
||||||
|
_, err = f.makeShortcut(ctx, "notfound", f, "dst")
|
||||||
|
assert.Error(t, err)
|
||||||
|
assert.Contains(t, err.Error(), "can't find source")
|
||||||
|
|
||||||
|
_, err = f.makeShortcut(ctx, existingFile, f, existingFile)
|
||||||
|
assert.Error(t, err)
|
||||||
|
assert.Contains(t, err.Error(), "not overwriting")
|
||||||
|
assert.Contains(t, err.Error(), "existing file")
|
||||||
|
|
||||||
|
_, err = f.makeShortcut(ctx, existingFile, f, existingDir)
|
||||||
|
assert.Error(t, err)
|
||||||
|
assert.Contains(t, err.Error(), "not overwriting")
|
||||||
|
assert.Contains(t, err.Error(), "existing directory")
|
||||||
|
})
|
||||||
|
t.Run("File", func(t *testing.T) {
|
||||||
|
dstObj, err := f.makeShortcut(ctx, existingFile, f, "shortcut.txt")
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.NotNil(t, dstObj)
|
||||||
|
assert.Equal(t, "shortcut.txt", dstObj.Remote())
|
||||||
|
dstHash, err := dstObj.Hash(ctx, hash.MD5)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, srcHash, dstHash)
|
||||||
|
require.NoError(t, dstObj.Remove(ctx))
|
||||||
|
})
|
||||||
|
t.Run("Dir", func(t *testing.T) {
|
||||||
|
dstObj, err := f.makeShortcut(ctx, existingDir, f, "shortcutdir")
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Nil(t, dstObj)
|
||||||
|
entries, err := f.List(ctx, "shortcutdir")
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Equal(t, 1, len(entries))
|
||||||
|
require.Equal(t, "shortcutdir/"+existingSubDir, entries[0].Remote())
|
||||||
|
require.NoError(t, f.Rmdir(ctx, "shortcutdir"))
|
||||||
|
})
|
||||||
|
t.Run("Command", func(t *testing.T) {
|
||||||
|
_, err := f.Command(ctx, "shortcut", []string{"one"}, nil)
|
||||||
|
require.Error(t, err)
|
||||||
|
require.Contains(t, err.Error(), "need exactly 2 arguments")
|
||||||
|
|
||||||
|
_, err = f.Command(ctx, "shortcut", []string{"one", "two"}, map[string]string{
|
||||||
|
"target": "doesnotexistremote:",
|
||||||
|
})
|
||||||
|
require.Error(t, err)
|
||||||
|
require.Contains(t, err.Error(), "couldn't find target")
|
||||||
|
|
||||||
|
_, err = f.Command(ctx, "shortcut", []string{"one", "two"}, map[string]string{
|
||||||
|
"target": ".",
|
||||||
|
})
|
||||||
|
require.Error(t, err)
|
||||||
|
require.Contains(t, err.Error(), "target is not a drive backend")
|
||||||
|
|
||||||
|
dstObjI, err := f.Command(ctx, "shortcut", []string{existingFile, "shortcut2.txt"}, map[string]string{
|
||||||
|
"target": fs.ConfigString(f),
|
||||||
|
})
|
||||||
|
require.NoError(t, err)
|
||||||
|
dstObj := dstObjI.(*Object)
|
||||||
|
assert.Equal(t, "shortcut2.txt", dstObj.Remote())
|
||||||
|
dstHash, err := dstObj.Hash(ctx, hash.MD5)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, srcHash, dstHash)
|
||||||
|
require.NoError(t, dstObj.Remove(ctx))
|
||||||
|
|
||||||
|
dstObjI, err = f.Command(ctx, "shortcut", []string{existingFile, "shortcut3.txt"}, nil)
|
||||||
|
require.NoError(t, err)
|
||||||
|
dstObj = dstObjI.(*Object)
|
||||||
|
assert.Equal(t, "shortcut3.txt", dstObj.Remote())
|
||||||
|
dstHash, err = dstObj.Hash(ctx, hash.MD5)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, srcHash, dstHash)
|
||||||
|
require.NoError(t, dstObj.Remove(ctx))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestIntegration/FsMkdir/FsPutFiles/Internal/UnTrash
|
||||||
|
func (f *Fs) InternalTestUnTrash(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
// Make some objects, one in a subdir
|
||||||
|
contents := random.String(100)
|
||||||
|
file1 := fstest.NewItem("trashDir/toBeTrashed", contents, time.Now())
|
||||||
|
_, obj1 := fstests.PutTestContents(ctx, t, f, &file1, contents, false)
|
||||||
|
file2 := fstest.NewItem("trashDir/subdir/toBeTrashed", contents, time.Now())
|
||||||
|
_, _ = fstests.PutTestContents(ctx, t, f, &file2, contents, false)
|
||||||
|
|
||||||
|
// Check objects
|
||||||
|
checkObjects := func() {
|
||||||
|
fstest.CheckListingWithRoot(t, f, "trashDir", []fstest.Item{
|
||||||
|
file1,
|
||||||
|
file2,
|
||||||
|
}, []string{
|
||||||
|
"trashDir/subdir",
|
||||||
|
}, f.Precision())
|
||||||
|
}
|
||||||
|
checkObjects()
|
||||||
|
|
||||||
|
// Make sure we are using the trash
|
||||||
|
require.Equal(t, true, f.opt.UseTrash)
|
||||||
|
|
||||||
|
// Remove the object and the dir
|
||||||
|
require.NoError(t, obj1.Remove(ctx))
|
||||||
|
require.NoError(t, f.Purge(ctx, "trashDir/subdir"))
|
||||||
|
|
||||||
|
// Check objects gone
|
||||||
|
fstest.CheckListingWithRoot(t, f, "trashDir", []fstest.Item{}, []string{}, f.Precision())
|
||||||
|
|
||||||
|
// Restore the object and directory
|
||||||
|
r, err := f.unTrashDir(ctx, "trashDir", true)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, unTrashResult{Errors: 0, Untrashed: 2}, r)
|
||||||
|
|
||||||
|
// Check objects restored
|
||||||
|
checkObjects()
|
||||||
|
|
||||||
|
// Remove the test dir
|
||||||
|
require.NoError(t, f.Purge(ctx, "trashDir"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestIntegration/FsMkdir/FsPutFiles/Internal/CopyID
|
||||||
|
func (f *Fs) InternalTestCopyID(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
obj, err := f.NewObject(ctx, existingFile)
|
||||||
|
require.NoError(t, err)
|
||||||
|
o := obj.(*Object)
|
||||||
|
|
||||||
|
dir, err := ioutil.TempDir("", "rclone-drive-copyid-test")
|
||||||
|
require.NoError(t, err)
|
||||||
|
defer func() {
|
||||||
|
_ = os.RemoveAll(dir)
|
||||||
|
}()
|
||||||
|
|
||||||
|
checkFile := func(name string) {
|
||||||
|
filePath := filepath.Join(dir, name)
|
||||||
|
fi, err := os.Stat(filePath)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, int64(100), fi.Size())
|
||||||
|
err = os.Remove(filePath)
|
||||||
|
require.NoError(t, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("BadID", func(t *testing.T) {
|
||||||
|
err = f.copyID(ctx, "ID-NOT-FOUND", dir+"/")
|
||||||
|
require.Error(t, err)
|
||||||
|
assert.Contains(t, err.Error(), "couldn't find id")
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Directory", func(t *testing.T) {
|
||||||
|
rootID, err := f.dirCache.RootID(ctx, false)
|
||||||
|
require.NoError(t, err)
|
||||||
|
err = f.copyID(ctx, rootID, dir+"/")
|
||||||
|
require.Error(t, err)
|
||||||
|
assert.Contains(t, err.Error(), "can't copy directory")
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("WithoutDestName", func(t *testing.T) {
|
||||||
|
err = f.copyID(ctx, o.id, dir+"/")
|
||||||
|
require.NoError(t, err)
|
||||||
|
checkFile(path.Base(existingFile))
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("WithDestName", func(t *testing.T) {
|
||||||
|
err = f.copyID(ctx, o.id, dir+"/potato.txt")
|
||||||
|
require.NoError(t, err)
|
||||||
|
checkFile("potato.txt")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func (f *Fs) InternalTest(t *testing.T) {
|
func (f *Fs) InternalTest(t *testing.T) {
|
||||||
// These tests all depend on each other so run them as nested tests
|
// These tests all depend on each other so run them as nested tests
|
||||||
t.Run("DocumentImport", func(t *testing.T) {
|
t.Run("DocumentImport", func(t *testing.T) {
|
||||||
@@ -282,6 +474,9 @@ func (f *Fs) InternalTest(t *testing.T) {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
t.Run("Shortcuts", f.InternalTestShortcuts)
|
||||||
|
t.Run("UnTrash", f.InternalTestUnTrash)
|
||||||
|
t.Run("CopyID", f.InternalTestCopyID)
|
||||||
}
|
}
|
||||||
|
|
||||||
var _ fstests.InternalTester = (*Fs)(nil)
|
var _ fstests.InternalTester = (*Fs)(nil)
|
||||||
+41
-50
@@ -11,16 +11,15 @@
|
|||||||
package drive
|
package drive
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
"regexp"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"github.com/rclone/rclone/fs"
|
"github.com/rclone/rclone/fs"
|
||||||
"github.com/rclone/rclone/fs/fserrors"
|
"github.com/rclone/rclone/fs/fserrors"
|
||||||
"github.com/rclone/rclone/lib/readers"
|
"github.com/rclone/rclone/lib/readers"
|
||||||
@@ -78,23 +77,24 @@ func (f *Fs) Upload(ctx context.Context, in io.Reader, size int64, contentType,
|
|||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
var req *http.Request
|
var req *http.Request
|
||||||
req, err = http.NewRequest(method, urls, body)
|
req, err = http.NewRequestWithContext(ctx, method, urls, body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
req = req.WithContext(ctx) // go1.13 can use NewRequestWithContext
|
|
||||||
googleapi.Expand(req.URL, map[string]string{
|
googleapi.Expand(req.URL, map[string]string{
|
||||||
"fileId": fileID,
|
"fileId": fileID,
|
||||||
})
|
})
|
||||||
req.Header.Set("Content-Type", "application/json; charset=UTF-8")
|
req.Header.Set("Content-Type", "application/json; charset=UTF-8")
|
||||||
req.Header.Set("X-Upload-Content-Type", contentType)
|
req.Header.Set("X-Upload-Content-Type", contentType)
|
||||||
req.Header.Set("X-Upload-Content-Length", fmt.Sprintf("%v", size))
|
if size >= 0 {
|
||||||
|
req.Header.Set("X-Upload-Content-Length", fmt.Sprintf("%v", size))
|
||||||
|
}
|
||||||
res, err = f.client.Do(req)
|
res, err = f.client.Do(req)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
defer googleapi.CloseBody(res)
|
defer googleapi.CloseBody(res)
|
||||||
err = googleapi.CheckResponse(res)
|
err = googleapi.CheckResponse(res)
|
||||||
}
|
}
|
||||||
return shouldRetry(err)
|
return f.shouldRetry(err)
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -113,52 +113,21 @@ func (f *Fs) Upload(ctx context.Context, in io.Reader, size int64, contentType,
|
|||||||
|
|
||||||
// Make an http.Request for the range passed in
|
// Make an http.Request for the range passed in
|
||||||
func (rx *resumableUpload) makeRequest(ctx context.Context, start int64, body io.ReadSeeker, reqSize int64) *http.Request {
|
func (rx *resumableUpload) makeRequest(ctx context.Context, start int64, body io.ReadSeeker, reqSize int64) *http.Request {
|
||||||
req, _ := http.NewRequest("POST", rx.URI, body)
|
req, _ := http.NewRequestWithContext(ctx, "POST", rx.URI, body)
|
||||||
req = req.WithContext(ctx) // go1.13 can use NewRequestWithContext
|
|
||||||
req.ContentLength = reqSize
|
req.ContentLength = reqSize
|
||||||
|
totalSize := "*"
|
||||||
|
if rx.ContentLength >= 0 {
|
||||||
|
totalSize = strconv.FormatInt(rx.ContentLength, 10)
|
||||||
|
}
|
||||||
if reqSize != 0 {
|
if reqSize != 0 {
|
||||||
req.Header.Set("Content-Range", fmt.Sprintf("bytes %v-%v/%v", start, start+reqSize-1, rx.ContentLength))
|
req.Header.Set("Content-Range", fmt.Sprintf("bytes %v-%v/%v", start, start+reqSize-1, totalSize))
|
||||||
} else {
|
} else {
|
||||||
req.Header.Set("Content-Range", fmt.Sprintf("bytes */%v", rx.ContentLength))
|
req.Header.Set("Content-Range", fmt.Sprintf("bytes */%v", totalSize))
|
||||||
}
|
}
|
||||||
req.Header.Set("Content-Type", rx.MediaType)
|
req.Header.Set("Content-Type", rx.MediaType)
|
||||||
return req
|
return req
|
||||||
}
|
}
|
||||||
|
|
||||||
// rangeRE matches the transfer status response from the server. $1 is
|
|
||||||
// the last byte index uploaded.
|
|
||||||
var rangeRE = regexp.MustCompile(`^0\-(\d+)$`)
|
|
||||||
|
|
||||||
// Query drive for the amount transferred so far
|
|
||||||
//
|
|
||||||
// If error is nil, then start should be valid
|
|
||||||
func (rx *resumableUpload) transferStatus(ctx context.Context) (start int64, err error) {
|
|
||||||
req := rx.makeRequest(ctx, 0, nil, 0)
|
|
||||||
res, err := rx.f.client.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
defer googleapi.CloseBody(res)
|
|
||||||
if res.StatusCode == http.StatusCreated || res.StatusCode == http.StatusOK {
|
|
||||||
return rx.ContentLength, nil
|
|
||||||
}
|
|
||||||
if res.StatusCode != statusResumeIncomplete {
|
|
||||||
err = googleapi.CheckResponse(res)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
return 0, errors.Errorf("unexpected http return code %v", res.StatusCode)
|
|
||||||
}
|
|
||||||
Range := res.Header.Get("Range")
|
|
||||||
if m := rangeRE.FindStringSubmatch(Range); len(m) == 2 {
|
|
||||||
start, err = strconv.ParseInt(m[1], 10, 64)
|
|
||||||
if err == nil {
|
|
||||||
return start, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return 0, errors.Errorf("unable to parse range %q", Range)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Transfer a chunk - caller must call googleapi.CloseBody(res) if err == nil || res != nil
|
// Transfer a chunk - caller must call googleapi.CloseBody(res) if err == nil || res != nil
|
||||||
func (rx *resumableUpload) transferChunk(ctx context.Context, start int64, chunk io.ReadSeeker, chunkSize int64) (int, error) {
|
func (rx *resumableUpload) transferChunk(ctx context.Context, start int64, chunk io.ReadSeeker, chunkSize int64) (int, error) {
|
||||||
_, _ = chunk.Seek(0, io.SeekStart)
|
_, _ = chunk.Seek(0, io.SeekStart)
|
||||||
@@ -200,18 +169,40 @@ func (rx *resumableUpload) Upload(ctx context.Context) (*drive.File, error) {
|
|||||||
var StatusCode int
|
var StatusCode int
|
||||||
var err error
|
var err error
|
||||||
buf := make([]byte, int(rx.f.opt.ChunkSize))
|
buf := make([]byte, int(rx.f.opt.ChunkSize))
|
||||||
for start < rx.ContentLength {
|
for finished := false; !finished; {
|
||||||
reqSize := rx.ContentLength - start
|
var reqSize int64
|
||||||
if reqSize >= int64(rx.f.opt.ChunkSize) {
|
var chunk io.ReadSeeker
|
||||||
reqSize = int64(rx.f.opt.ChunkSize)
|
if rx.ContentLength >= 0 {
|
||||||
|
// If size known use repeatable reader for smoother bwlimit
|
||||||
|
if start >= rx.ContentLength {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
reqSize = rx.ContentLength - start
|
||||||
|
if reqSize >= int64(rx.f.opt.ChunkSize) {
|
||||||
|
reqSize = int64(rx.f.opt.ChunkSize)
|
||||||
|
}
|
||||||
|
chunk = readers.NewRepeatableLimitReaderBuffer(rx.Media, buf, reqSize)
|
||||||
|
} else {
|
||||||
|
// If size unknown read into buffer
|
||||||
|
var n int
|
||||||
|
n, err = readers.ReadFill(rx.Media, buf)
|
||||||
|
if err == io.EOF {
|
||||||
|
// Send the last chunk with the correct ContentLength
|
||||||
|
// otherwise Google doesn't know we've finished
|
||||||
|
rx.ContentLength = start + int64(n)
|
||||||
|
finished = true
|
||||||
|
} else if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
reqSize = int64(n)
|
||||||
|
chunk = bytes.NewReader(buf[:reqSize])
|
||||||
}
|
}
|
||||||
chunk := readers.NewRepeatableLimitReaderBuffer(rx.Media, buf, reqSize)
|
|
||||||
|
|
||||||
// Transfer the chunk
|
// Transfer the chunk
|
||||||
err = rx.f.pacer.Call(func() (bool, error) {
|
err = rx.f.pacer.Call(func() (bool, error) {
|
||||||
fs.Debugf(rx.remote, "Sending chunk %d length %d", start, reqSize)
|
fs.Debugf(rx.remote, "Sending chunk %d length %d", start, reqSize)
|
||||||
StatusCode, err = rx.transferChunk(ctx, start, chunk, reqSize)
|
StatusCode, err = rx.transferChunk(ctx, start, chunk, reqSize)
|
||||||
again, err := shouldRetry(err)
|
again, err := rx.f.shouldRetry(err)
|
||||||
if StatusCode == statusResumeIncomplete || StatusCode == http.StatusCreated || StatusCode == http.StatusOK {
|
if StatusCode == statusResumeIncomplete || StatusCode == http.StatusCreated || StatusCode == http.StatusOK {
|
||||||
again = false
|
again = false
|
||||||
err = nil
|
err = nil
|
||||||
|
|||||||
Regular → Executable
+423
-80
@@ -30,6 +30,7 @@ import (
|
|||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox"
|
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox"
|
||||||
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/auth"
|
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/auth"
|
||||||
@@ -45,17 +46,15 @@ import (
|
|||||||
"github.com/rclone/rclone/fs/config/configmap"
|
"github.com/rclone/rclone/fs/config/configmap"
|
||||||
"github.com/rclone/rclone/fs/config/configstruct"
|
"github.com/rclone/rclone/fs/config/configstruct"
|
||||||
"github.com/rclone/rclone/fs/config/obscure"
|
"github.com/rclone/rclone/fs/config/obscure"
|
||||||
"github.com/rclone/rclone/fs/encodings"
|
|
||||||
"github.com/rclone/rclone/fs/fserrors"
|
"github.com/rclone/rclone/fs/fserrors"
|
||||||
"github.com/rclone/rclone/fs/hash"
|
"github.com/rclone/rclone/fs/hash"
|
||||||
|
"github.com/rclone/rclone/lib/encoder"
|
||||||
"github.com/rclone/rclone/lib/oauthutil"
|
"github.com/rclone/rclone/lib/oauthutil"
|
||||||
"github.com/rclone/rclone/lib/pacer"
|
"github.com/rclone/rclone/lib/pacer"
|
||||||
"github.com/rclone/rclone/lib/readers"
|
"github.com/rclone/rclone/lib/readers"
|
||||||
"golang.org/x/oauth2"
|
"golang.org/x/oauth2"
|
||||||
)
|
)
|
||||||
|
|
||||||
const enc = encodings.Dropbox
|
|
||||||
|
|
||||||
// Constants
|
// Constants
|
||||||
const (
|
const (
|
||||||
rcloneClientID = "5jcck7diasz0rqy"
|
rcloneClientID = "5jcck7diasz0rqy"
|
||||||
@@ -88,6 +87,8 @@ const (
|
|||||||
// by default.
|
// by default.
|
||||||
defaultChunkSize = 48 * fs.MebiByte
|
defaultChunkSize = 48 * fs.MebiByte
|
||||||
maxChunkSize = 150 * fs.MebiByte
|
maxChunkSize = 150 * fs.MebiByte
|
||||||
|
// Max length of filename parts: https://help.dropbox.com/installs-integrations/sync-uploads/files-not-syncing
|
||||||
|
maxFileNameLength = 255
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -109,6 +110,9 @@ var (
|
|||||||
|
|
||||||
// DbHashType is the hash.Type for Dropbox
|
// DbHashType is the hash.Type for Dropbox
|
||||||
DbHashType hash.Type
|
DbHashType hash.Type
|
||||||
|
|
||||||
|
// Errors
|
||||||
|
errNotSupportedInSharedMode = fserrors.NoRetryError(errors.New("not supported in shared files mode"))
|
||||||
)
|
)
|
||||||
|
|
||||||
// Register with Fs
|
// Register with Fs
|
||||||
@@ -118,19 +122,19 @@ func init() {
|
|||||||
Name: "dropbox",
|
Name: "dropbox",
|
||||||
Description: "Dropbox",
|
Description: "Dropbox",
|
||||||
NewFs: NewFs,
|
NewFs: NewFs,
|
||||||
Config: func(name string, m configmap.Mapper) {
|
Config: func(ctx context.Context, name string, m configmap.Mapper) {
|
||||||
err := oauthutil.ConfigNoOffline("dropbox", name, m, dropboxConfig)
|
opt := oauthutil.Options{
|
||||||
|
NoOffline: true,
|
||||||
|
OAuth2Opts: []oauth2.AuthCodeOption{
|
||||||
|
oauth2.SetAuthURLParam("token_access_type", "offline"),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
err := oauthutil.Config(ctx, "dropbox", name, m, dropboxConfig, &opt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Failed to configure token: %v", err)
|
log.Fatalf("Failed to configure token: %v", err)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
Options: []fs.Option{{
|
Options: append(oauthutil.SharedOptions, []fs.Option{{
|
||||||
Name: config.ConfigClientID,
|
|
||||||
Help: "Dropbox App Client Id\nLeave blank normally.",
|
|
||||||
}, {
|
|
||||||
Name: config.ConfigClientSecret,
|
|
||||||
Help: "Dropbox App Client Secret\nLeave blank normally.",
|
|
||||||
}, {
|
|
||||||
Name: "chunk_size",
|
Name: "chunk_size",
|
||||||
Help: fmt.Sprintf(`Upload chunk size. (< %v).
|
Help: fmt.Sprintf(`Upload chunk size. (< %v).
|
||||||
|
|
||||||
@@ -147,14 +151,55 @@ memory. It can be set smaller if you are tight on memory.`, maxChunkSize),
|
|||||||
Help: "Impersonate this user when using a business account.",
|
Help: "Impersonate this user when using a business account.",
|
||||||
Default: "",
|
Default: "",
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
}},
|
}, {
|
||||||
|
Name: "shared_files",
|
||||||
|
Help: `Instructs rclone to work on individual shared files.
|
||||||
|
|
||||||
|
In this mode rclone's features are extremely limited - only list (ls, lsl, etc.)
|
||||||
|
operations and read operations (e.g. downloading) are supported in this mode.
|
||||||
|
All other operations will be disabled.`,
|
||||||
|
Default: false,
|
||||||
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: "shared_folders",
|
||||||
|
Help: `Instructs rclone to work on shared folders.
|
||||||
|
|
||||||
|
When this flag is used with no path only the List operation is supported and
|
||||||
|
all available shared folders will be listed. If you specify a path the first part
|
||||||
|
will be interpreted as the name of shared folder. Rclone will then try to mount this
|
||||||
|
shared to the root namespace. On success shared folder rclone proceeds normally.
|
||||||
|
The shared folder is now pretty much a normal folder and all normal operations
|
||||||
|
are supported.
|
||||||
|
|
||||||
|
Note that we don't unmount the shared folder afterwards so the
|
||||||
|
--dropbox-shared-folders can be omitted after the first use of a particular
|
||||||
|
shared folder.`,
|
||||||
|
Default: false,
|
||||||
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: config.ConfigEncoding,
|
||||||
|
Help: config.ConfigEncodingHelp,
|
||||||
|
Advanced: true,
|
||||||
|
// https://www.dropbox.com/help/syncing-uploads/files-not-syncing lists / and \
|
||||||
|
// as invalid characters.
|
||||||
|
// Testing revealed names with trailing spaces and the DEL character don't work.
|
||||||
|
// Also encode invalid UTF-8 bytes as json doesn't handle them properly.
|
||||||
|
Default: (encoder.Base |
|
||||||
|
encoder.EncodeBackSlash |
|
||||||
|
encoder.EncodeDel |
|
||||||
|
encoder.EncodeRightSpace |
|
||||||
|
encoder.EncodeInvalidUtf8),
|
||||||
|
}}...),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Options defines the configuration for this backend
|
// Options defines the configuration for this backend
|
||||||
type Options struct {
|
type Options struct {
|
||||||
ChunkSize fs.SizeSuffix `config:"chunk_size"`
|
ChunkSize fs.SizeSuffix `config:"chunk_size"`
|
||||||
Impersonate string `config:"impersonate"`
|
Impersonate string `config:"impersonate"`
|
||||||
|
SharedFiles bool `config:"shared_files"`
|
||||||
|
SharedFolders bool `config:"shared_folders"`
|
||||||
|
Enc encoder.MultiEncoder `config:"encoding"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fs represents a remote dropbox server
|
// Fs represents a remote dropbox server
|
||||||
@@ -177,7 +222,9 @@ type Fs struct {
|
|||||||
//
|
//
|
||||||
// Dropbox Objects always have full metadata
|
// Dropbox Objects always have full metadata
|
||||||
type Object struct {
|
type Object struct {
|
||||||
fs *Fs // what this object is part of
|
fs *Fs // what this object is part of
|
||||||
|
id string
|
||||||
|
url string
|
||||||
remote string // The remote path
|
remote string // The remote path
|
||||||
bytes int64 // size of the object
|
bytes int64 // size of the object
|
||||||
modTime time.Time // time it was last modified
|
modTime time.Time // time it was last modified
|
||||||
@@ -213,7 +260,13 @@ func shouldRetry(err error) (bool, error) {
|
|||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
baseErrString := errors.Cause(err).Error()
|
baseErrString := errors.Cause(err).Error()
|
||||||
// handle any official Retry-After header from Dropbox's SDK first
|
// First check for specific errors
|
||||||
|
if strings.Contains(baseErrString, "insufficient_space") {
|
||||||
|
return false, fserrors.FatalError(err)
|
||||||
|
} else if strings.Contains(baseErrString, "malformed_path") {
|
||||||
|
return false, fserrors.NoRetryError(err)
|
||||||
|
}
|
||||||
|
// Then handle any official Retry-After header from Dropbox's SDK
|
||||||
switch e := err.(type) {
|
switch e := err.(type) {
|
||||||
case auth.RateLimitAPIError:
|
case auth.RateLimitAPIError:
|
||||||
if e.RateLimitError.RetryAfter > 0 {
|
if e.RateLimitError.RetryAfter > 0 {
|
||||||
@@ -249,7 +302,7 @@ func (f *Fs) setUploadChunkSize(cs fs.SizeSuffix) (old fs.SizeSuffix, err error)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// NewFs constructs an Fs from the path, container:path
|
// NewFs constructs an Fs from the path, container:path
|
||||||
func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {
|
||||||
// Parse config into Options struct
|
// Parse config into Options struct
|
||||||
opt := new(Options)
|
opt := new(Options)
|
||||||
err := configstruct.Set(m, opt)
|
err := configstruct.Set(m, opt)
|
||||||
@@ -274,7 +327,7 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
oAuthClient, _, err := oauthutil.NewClient(name, m, dropboxConfig)
|
oAuthClient, _, err := oauthutil.NewClient(ctx, name, m, dropboxConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "failed to configure dropbox")
|
return nil, errors.Wrap(err, "failed to configure dropbox")
|
||||||
}
|
}
|
||||||
@@ -282,7 +335,7 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
f := &Fs{
|
f := &Fs{
|
||||||
name: name,
|
name: name,
|
||||||
opt: *opt,
|
opt: *opt,
|
||||||
pacer: fs.NewPacer(pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
|
pacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
|
||||||
}
|
}
|
||||||
config := dropbox.Config{
|
config := dropbox.Config{
|
||||||
LogLevel: dropbox.LogOff, // logging in the SDK: LogOff, LogDebug, LogInfo
|
LogLevel: dropbox.LogOff, // logging in the SDK: LogOff, LogDebug, LogInfo
|
||||||
@@ -317,10 +370,62 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
f.users = users.New(config)
|
f.users = users.New(config)
|
||||||
f.features = (&fs.Features{
|
f.features = (&fs.Features{
|
||||||
CaseInsensitive: true,
|
CaseInsensitive: true,
|
||||||
ReadMimeType: true,
|
ReadMimeType: false,
|
||||||
CanHaveEmptyDirectories: true,
|
CanHaveEmptyDirectories: true,
|
||||||
}).Fill(f)
|
})
|
||||||
f.setRoot(root)
|
|
||||||
|
// do not fill features yet
|
||||||
|
if f.opt.SharedFiles {
|
||||||
|
f.setRoot(root)
|
||||||
|
if f.root == "" {
|
||||||
|
return f, nil
|
||||||
|
}
|
||||||
|
_, err := f.findSharedFile(f.root)
|
||||||
|
f.root = ""
|
||||||
|
if err == nil {
|
||||||
|
return f, fs.ErrorIsFile
|
||||||
|
}
|
||||||
|
return f, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if f.opt.SharedFolders {
|
||||||
|
f.setRoot(root)
|
||||||
|
if f.root == "" {
|
||||||
|
return f, nil // our root it empty so we probably want to list shared folders
|
||||||
|
}
|
||||||
|
|
||||||
|
dir := path.Dir(f.root)
|
||||||
|
if dir == "." {
|
||||||
|
dir = f.root
|
||||||
|
}
|
||||||
|
|
||||||
|
// root is not empty so we have find the right shared folder if it exists
|
||||||
|
id, err := f.findSharedFolder(dir)
|
||||||
|
if err != nil {
|
||||||
|
// if we didn't find the specified shared folder we have to bail out here
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// we found the specified shared folder so let's mount it
|
||||||
|
// this will add it to the users normal root namespace and allows us
|
||||||
|
// to actually perform operations on it using the normal api endpoints.
|
||||||
|
err = f.mountSharedFolder(id)
|
||||||
|
if err != nil {
|
||||||
|
switch e := err.(type) {
|
||||||
|
case sharing.MountFolderAPIError:
|
||||||
|
if e.EndpointError == nil || (e.EndpointError != nil && e.EndpointError.Tag != sharing.MountFolderErrorAlreadyMounted) {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// if the moint failed we have to abort here
|
||||||
|
}
|
||||||
|
// if the mount succeeded it's now a normal folder in the users root namespace
|
||||||
|
// we disable shared folder mode and proceed normally
|
||||||
|
f.opt.SharedFolders = false
|
||||||
|
}
|
||||||
|
|
||||||
|
f.features.Fill(ctx, f)
|
||||||
|
|
||||||
// If root starts with / then use the actual root
|
// If root starts with / then use the actual root
|
||||||
if strings.HasPrefix(root, "/") {
|
if strings.HasPrefix(root, "/") {
|
||||||
@@ -342,6 +447,7 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
}
|
}
|
||||||
fs.Debugf(f, "Using root namespace %q", f.ns)
|
fs.Debugf(f, "Using root namespace %q", f.ns)
|
||||||
}
|
}
|
||||||
|
f.setRoot(root)
|
||||||
|
|
||||||
// See if the root is actually an object
|
// See if the root is actually an object
|
||||||
_, err = f.getFileMetadata(f.slashRoot)
|
_, err = f.getFileMetadata(f.slashRoot)
|
||||||
@@ -381,7 +487,7 @@ func (f *Fs) setRoot(root string) {
|
|||||||
func (f *Fs) getMetadata(objPath string) (entry files.IsMetadata, notFound bool, err error) {
|
func (f *Fs) getMetadata(objPath string) (entry files.IsMetadata, notFound bool, err error) {
|
||||||
err = f.pacer.Call(func() (bool, error) {
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
entry, err = f.srv.GetMetadata(&files.GetMetadataArg{
|
entry, err = f.srv.GetMetadata(&files.GetMetadataArg{
|
||||||
Path: enc.FromStandardPath(objPath),
|
Path: f.opt.Enc.FromStandardPath(objPath),
|
||||||
})
|
})
|
||||||
return shouldRetry(err)
|
return shouldRetry(err)
|
||||||
})
|
})
|
||||||
@@ -452,9 +558,150 @@ func (f *Fs) newObjectWithInfo(remote string, info *files.FileMetadata) (fs.Obje
|
|||||||
// NewObject finds the Object at remote. If it can't be found
|
// NewObject finds the Object at remote. If it can't be found
|
||||||
// it returns the error fs.ErrorObjectNotFound.
|
// it returns the error fs.ErrorObjectNotFound.
|
||||||
func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) {
|
func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) {
|
||||||
|
if f.opt.SharedFiles {
|
||||||
|
return f.findSharedFile(remote)
|
||||||
|
}
|
||||||
return f.newObjectWithInfo(remote, nil)
|
return f.newObjectWithInfo(remote, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// listSharedFoldersApi lists all available shared folders mounted and not mounted
|
||||||
|
// we'll need the id later so we have to return them in original format
|
||||||
|
func (f *Fs) listSharedFolders() (entries fs.DirEntries, err error) {
|
||||||
|
started := false
|
||||||
|
var res *sharing.ListFoldersResult
|
||||||
|
for {
|
||||||
|
if !started {
|
||||||
|
arg := sharing.ListFoldersArgs{
|
||||||
|
Limit: 100,
|
||||||
|
}
|
||||||
|
err := f.pacer.Call(func() (bool, error) {
|
||||||
|
res, err = f.sharing.ListFolders(&arg)
|
||||||
|
return shouldRetry(err)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
started = true
|
||||||
|
} else {
|
||||||
|
arg := sharing.ListFoldersContinueArg{
|
||||||
|
Cursor: res.Cursor,
|
||||||
|
}
|
||||||
|
err := f.pacer.Call(func() (bool, error) {
|
||||||
|
res, err = f.sharing.ListFoldersContinue(&arg)
|
||||||
|
return shouldRetry(err)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "list continue")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, entry := range res.Entries {
|
||||||
|
leaf := f.opt.Enc.ToStandardName(entry.Name)
|
||||||
|
d := fs.NewDir(leaf, time.Now()).SetID(entry.SharedFolderId)
|
||||||
|
entries = append(entries, d)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if res.Cursor == "" {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return entries, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// findSharedFolder find the id for a given shared folder name
|
||||||
|
// somewhat annoyingly there is no endpoint to query a shared folder by it's name
|
||||||
|
// so our only option is to iterate over all shared folders
|
||||||
|
func (f *Fs) findSharedFolder(name string) (id string, err error) {
|
||||||
|
entries, err := f.listSharedFolders()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
for _, entry := range entries {
|
||||||
|
if entry.(*fs.Dir).Remote() == name {
|
||||||
|
return entry.(*fs.Dir).ID(), nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "", fs.ErrorDirNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
// mountSharedFolders mount a shared folder to the root namespace
|
||||||
|
func (f *Fs) mountSharedFolder(id string) error {
|
||||||
|
arg := sharing.MountFolderArg{
|
||||||
|
SharedFolderId: id,
|
||||||
|
}
|
||||||
|
err := f.pacer.Call(func() (bool, error) {
|
||||||
|
_, err := f.sharing.MountFolder(&arg)
|
||||||
|
return shouldRetry(err)
|
||||||
|
})
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// listSharedFolders lists shared the user as access to (note this means individual
|
||||||
|
// files not files contained in shared folders)
|
||||||
|
func (f *Fs) listReceivedFiles() (entries fs.DirEntries, err error) {
|
||||||
|
started := false
|
||||||
|
var res *sharing.ListFilesResult
|
||||||
|
for {
|
||||||
|
if !started {
|
||||||
|
arg := sharing.ListFilesArg{
|
||||||
|
Limit: 100,
|
||||||
|
}
|
||||||
|
err := f.pacer.Call(func() (bool, error) {
|
||||||
|
res, err = f.sharing.ListReceivedFiles(&arg)
|
||||||
|
return shouldRetry(err)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
started = true
|
||||||
|
} else {
|
||||||
|
arg := sharing.ListFilesContinueArg{
|
||||||
|
Cursor: res.Cursor,
|
||||||
|
}
|
||||||
|
err := f.pacer.Call(func() (bool, error) {
|
||||||
|
res, err = f.sharing.ListReceivedFilesContinue(&arg)
|
||||||
|
return shouldRetry(err)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "list continue")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, entry := range res.Entries {
|
||||||
|
fmt.Printf("%+v\n", entry)
|
||||||
|
entryPath := entry.Name
|
||||||
|
o := &Object{
|
||||||
|
fs: f,
|
||||||
|
url: entry.PreviewUrl,
|
||||||
|
remote: entryPath,
|
||||||
|
modTime: entry.TimeInvited,
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
entries = append(entries, o)
|
||||||
|
}
|
||||||
|
if res.Cursor == "" {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return entries, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fs) findSharedFile(name string) (o *Object, err error) {
|
||||||
|
files, err := f.listReceivedFiles()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for _, entry := range files {
|
||||||
|
if entry.(*Object).remote == name {
|
||||||
|
return entry.(*Object), nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil, fs.ErrorObjectNotFound
|
||||||
|
}
|
||||||
|
|
||||||
// List the objects and directories in dir into entries. The
|
// List the objects and directories in dir into entries. The
|
||||||
// entries can be returned in any order but should be for a
|
// entries can be returned in any order but should be for a
|
||||||
// complete directory.
|
// complete directory.
|
||||||
@@ -465,6 +712,13 @@ func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) {
|
|||||||
// This should return ErrDirNotFound if the directory isn't
|
// This should return ErrDirNotFound if the directory isn't
|
||||||
// found.
|
// found.
|
||||||
func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) {
|
func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) {
|
||||||
|
if f.opt.SharedFiles {
|
||||||
|
return f.listReceivedFiles()
|
||||||
|
}
|
||||||
|
if f.opt.SharedFolders {
|
||||||
|
return f.listSharedFolders()
|
||||||
|
}
|
||||||
|
|
||||||
root := f.slashRoot
|
root := f.slashRoot
|
||||||
if dir != "" {
|
if dir != "" {
|
||||||
root += "/" + dir
|
root += "/" + dir
|
||||||
@@ -475,7 +729,7 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
|
|||||||
for {
|
for {
|
||||||
if !started {
|
if !started {
|
||||||
arg := files.ListFolderArg{
|
arg := files.ListFolderArg{
|
||||||
Path: enc.FromStandardPath(root),
|
Path: f.opt.Enc.FromStandardPath(root),
|
||||||
Recursive: false,
|
Recursive: false,
|
||||||
}
|
}
|
||||||
if root == "/" {
|
if root == "/" {
|
||||||
@@ -525,10 +779,10 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
|
|||||||
|
|
||||||
// Only the last element is reliably cased in PathDisplay
|
// Only the last element is reliably cased in PathDisplay
|
||||||
entryPath := metadata.PathDisplay
|
entryPath := metadata.PathDisplay
|
||||||
leaf := enc.ToStandardName(path.Base(entryPath))
|
leaf := f.opt.Enc.ToStandardName(path.Base(entryPath))
|
||||||
remote := path.Join(dir, leaf)
|
remote := path.Join(dir, leaf)
|
||||||
if folderInfo != nil {
|
if folderInfo != nil {
|
||||||
d := fs.NewDir(remote, time.Now())
|
d := fs.NewDir(remote, time.Now()).SetID(folderInfo.Id)
|
||||||
entries = append(entries, d)
|
entries = append(entries, d)
|
||||||
} else if fileInfo != nil {
|
} else if fileInfo != nil {
|
||||||
o, err := f.newObjectWithInfo(remote, fileInfo)
|
o, err := f.newObjectWithInfo(remote, fileInfo)
|
||||||
@@ -551,6 +805,9 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
|
|||||||
//
|
//
|
||||||
// The new object may have been created if an error is returned
|
// The new object may have been created if an error is returned
|
||||||
func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
|
func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
|
||||||
|
if f.opt.SharedFiles || f.opt.SharedFolders {
|
||||||
|
return nil, errNotSupportedInSharedMode
|
||||||
|
}
|
||||||
// Temporary Object under construction
|
// Temporary Object under construction
|
||||||
o := &Object{
|
o := &Object{
|
||||||
fs: f,
|
fs: f,
|
||||||
@@ -566,6 +823,9 @@ func (f *Fs) PutStream(ctx context.Context, in io.Reader, src fs.ObjectInfo, opt
|
|||||||
|
|
||||||
// Mkdir creates the container if it doesn't exist
|
// Mkdir creates the container if it doesn't exist
|
||||||
func (f *Fs) Mkdir(ctx context.Context, dir string) error {
|
func (f *Fs) Mkdir(ctx context.Context, dir string) error {
|
||||||
|
if f.opt.SharedFiles || f.opt.SharedFolders {
|
||||||
|
return errNotSupportedInSharedMode
|
||||||
|
}
|
||||||
root := path.Join(f.slashRoot, dir)
|
root := path.Join(f.slashRoot, dir)
|
||||||
|
|
||||||
// can't create or run metadata on root
|
// can't create or run metadata on root
|
||||||
@@ -583,7 +843,11 @@ func (f *Fs) Mkdir(ctx context.Context, dir string) error {
|
|||||||
|
|
||||||
// create it
|
// create it
|
||||||
arg2 := files.CreateFolderArg{
|
arg2 := files.CreateFolderArg{
|
||||||
Path: enc.FromStandardPath(root),
|
Path: f.opt.Enc.FromStandardPath(root),
|
||||||
|
}
|
||||||
|
// Don't attempt to create filenames that are too long
|
||||||
|
if cErr := checkPathLength(arg2.Path); cErr != nil {
|
||||||
|
return cErr
|
||||||
}
|
}
|
||||||
err = f.pacer.Call(func() (bool, error) {
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
_, err = f.srv.CreateFolderV2(&arg2)
|
_, err = f.srv.CreateFolderV2(&arg2)
|
||||||
@@ -592,10 +856,9 @@ func (f *Fs) Mkdir(ctx context.Context, dir string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Rmdir deletes the container
|
// purgeCheck removes the root directory, if check is set then it
|
||||||
//
|
// refuses to do so if it has anything in
|
||||||
// Returns an error if it isn't empty
|
func (f *Fs) purgeCheck(ctx context.Context, dir string, check bool) (err error) {
|
||||||
func (f *Fs) Rmdir(ctx context.Context, dir string) error {
|
|
||||||
root := path.Join(f.slashRoot, dir)
|
root := path.Join(f.slashRoot, dir)
|
||||||
|
|
||||||
// can't remove root
|
// can't remove root
|
||||||
@@ -603,31 +866,33 @@ func (f *Fs) Rmdir(ctx context.Context, dir string) error {
|
|||||||
return errors.New("can't remove root directory")
|
return errors.New("can't remove root directory")
|
||||||
}
|
}
|
||||||
|
|
||||||
// check directory exists
|
if check {
|
||||||
_, err := f.getDirMetadata(root)
|
// check directory exists
|
||||||
if err != nil {
|
_, err = f.getDirMetadata(root)
|
||||||
return errors.Wrap(err, "Rmdir")
|
if err != nil {
|
||||||
}
|
return errors.Wrap(err, "Rmdir")
|
||||||
|
}
|
||||||
|
|
||||||
root = enc.FromStandardPath(root)
|
root = f.opt.Enc.FromStandardPath(root)
|
||||||
// check directory empty
|
// check directory empty
|
||||||
arg := files.ListFolderArg{
|
arg := files.ListFolderArg{
|
||||||
Path: root,
|
Path: root,
|
||||||
Recursive: false,
|
Recursive: false,
|
||||||
}
|
}
|
||||||
if root == "/" {
|
if root == "/" {
|
||||||
arg.Path = "" // Specify root folder as empty string
|
arg.Path = "" // Specify root folder as empty string
|
||||||
}
|
}
|
||||||
var res *files.ListFolderResult
|
var res *files.ListFolderResult
|
||||||
err = f.pacer.Call(func() (bool, error) {
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
res, err = f.srv.ListFolder(&arg)
|
res, err = f.srv.ListFolder(&arg)
|
||||||
return shouldRetry(err)
|
return shouldRetry(err)
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.Wrap(err, "Rmdir")
|
return errors.Wrap(err, "Rmdir")
|
||||||
}
|
}
|
||||||
if len(res.Entries) != 0 {
|
if len(res.Entries) != 0 {
|
||||||
return errors.New("directory not empty")
|
return errors.New("directory not empty")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// remove it
|
// remove it
|
||||||
@@ -638,12 +903,22 @@ func (f *Fs) Rmdir(ctx context.Context, dir string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Rmdir deletes the container
|
||||||
|
//
|
||||||
|
// Returns an error if it isn't empty
|
||||||
|
func (f *Fs) Rmdir(ctx context.Context, dir string) error {
|
||||||
|
if f.opt.SharedFiles || f.opt.SharedFolders {
|
||||||
|
return errNotSupportedInSharedMode
|
||||||
|
}
|
||||||
|
return f.purgeCheck(ctx, dir, true)
|
||||||
|
}
|
||||||
|
|
||||||
// Precision returns the precision
|
// Precision returns the precision
|
||||||
func (f *Fs) Precision() time.Duration {
|
func (f *Fs) Precision() time.Duration {
|
||||||
return time.Second
|
return time.Second
|
||||||
}
|
}
|
||||||
|
|
||||||
// Copy src to this remote using server side copy operations.
|
// Copy src to this remote using server-side copy operations.
|
||||||
//
|
//
|
||||||
// This is stored with the remote path given
|
// This is stored with the remote path given
|
||||||
//
|
//
|
||||||
@@ -668,8 +943,8 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
// Copy
|
// Copy
|
||||||
arg := files.RelocationArg{
|
arg := files.RelocationArg{
|
||||||
RelocationPath: files.RelocationPath{
|
RelocationPath: files.RelocationPath{
|
||||||
FromPath: enc.FromStandardPath(srcObj.remotePath()),
|
FromPath: f.opt.Enc.FromStandardPath(srcObj.remotePath()),
|
||||||
ToPath: enc.FromStandardPath(dstObj.remotePath()),
|
ToPath: f.opt.Enc.FromStandardPath(dstObj.remotePath()),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
var err error
|
var err error
|
||||||
@@ -700,18 +975,11 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
// Optional interface: Only implement this if you have a way of
|
// Optional interface: Only implement this if you have a way of
|
||||||
// deleting all the files quicker than just running Remove() on the
|
// deleting all the files quicker than just running Remove() on the
|
||||||
// result of List()
|
// result of List()
|
||||||
func (f *Fs) Purge(ctx context.Context) (err error) {
|
func (f *Fs) Purge(ctx context.Context, dir string) (err error) {
|
||||||
// Let dropbox delete the filesystem tree
|
return f.purgeCheck(ctx, dir, false)
|
||||||
err = f.pacer.Call(func() (bool, error) {
|
|
||||||
_, err = f.srv.DeleteV2(&files.DeleteArg{
|
|
||||||
Path: enc.FromStandardPath(f.slashRoot),
|
|
||||||
})
|
|
||||||
return shouldRetry(err)
|
|
||||||
})
|
|
||||||
return err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Move src to this remote using server side move operations.
|
// Move src to this remote using server-side move operations.
|
||||||
//
|
//
|
||||||
// This is stored with the remote path given
|
// This is stored with the remote path given
|
||||||
//
|
//
|
||||||
@@ -736,8 +1004,8 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
// Do the move
|
// Do the move
|
||||||
arg := files.RelocationArg{
|
arg := files.RelocationArg{
|
||||||
RelocationPath: files.RelocationPath{
|
RelocationPath: files.RelocationPath{
|
||||||
FromPath: enc.FromStandardPath(srcObj.remotePath()),
|
FromPath: f.opt.Enc.FromStandardPath(srcObj.remotePath()),
|
||||||
ToPath: enc.FromStandardPath(dstObj.remotePath()),
|
ToPath: f.opt.Enc.FromStandardPath(dstObj.remotePath()),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
var err error
|
var err error
|
||||||
@@ -763,11 +1031,17 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// PublicLink adds a "readable by anyone with link" permission on the given file or folder.
|
// PublicLink adds a "readable by anyone with link" permission on the given file or folder.
|
||||||
func (f *Fs) PublicLink(ctx context.Context, remote string) (link string, err error) {
|
func (f *Fs) PublicLink(ctx context.Context, remote string, expire fs.Duration, unlink bool) (link string, err error) {
|
||||||
absPath := enc.FromStandardPath(path.Join(f.slashRoot, remote))
|
absPath := f.opt.Enc.FromStandardPath(path.Join(f.slashRoot, remote))
|
||||||
fs.Debugf(f, "attempting to share '%s' (absolute path: %s)", remote, absPath)
|
fs.Debugf(f, "attempting to share '%s' (absolute path: %s)", remote, absPath)
|
||||||
createArg := sharing.CreateSharedLinkWithSettingsArg{
|
createArg := sharing.CreateSharedLinkWithSettingsArg{
|
||||||
Path: absPath,
|
Path: absPath,
|
||||||
|
// FIXME this gives settings_error/not_authorized/.. errors
|
||||||
|
// and the expires setting isn't in the documentation so remove
|
||||||
|
// for now.
|
||||||
|
// Settings: &sharing.SharedLinkSettings{
|
||||||
|
// Expires: time.Now().Add(time.Duration(expire)).UTC().Round(time.Second),
|
||||||
|
// },
|
||||||
}
|
}
|
||||||
var linkRes sharing.IsSharedLinkMetadata
|
var linkRes sharing.IsSharedLinkMetadata
|
||||||
err = f.pacer.Call(func() (bool, error) {
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
@@ -810,7 +1084,7 @@ func (f *Fs) PublicLink(ctx context.Context, remote string) (link string, err er
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DirMove moves src, srcRemote to this remote at dstRemote
|
// DirMove moves src, srcRemote to this remote at dstRemote
|
||||||
// using server side move operations.
|
// using server-side move operations.
|
||||||
//
|
//
|
||||||
// Will only be called if src.Fs().Name() == f.Name()
|
// Will only be called if src.Fs().Name() == f.Name()
|
||||||
//
|
//
|
||||||
@@ -840,8 +1114,8 @@ func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string
|
|||||||
// Do the move
|
// Do the move
|
||||||
arg := files.RelocationArg{
|
arg := files.RelocationArg{
|
||||||
RelocationPath: files.RelocationPath{
|
RelocationPath: files.RelocationPath{
|
||||||
FromPath: enc.FromStandardPath(srcPath),
|
FromPath: f.opt.Enc.FromStandardPath(srcPath),
|
||||||
ToPath: enc.FromStandardPath(dstPath),
|
ToPath: f.opt.Enc.FromStandardPath(dstPath),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
err = f.pacer.Call(func() (bool, error) {
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
@@ -907,8 +1181,16 @@ func (o *Object) Remote() string {
|
|||||||
return o.remote
|
return o.remote
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ID returns the object id
|
||||||
|
func (o *Object) ID() string {
|
||||||
|
return o.id
|
||||||
|
}
|
||||||
|
|
||||||
// Hash returns the dropbox special hash
|
// Hash returns the dropbox special hash
|
||||||
func (o *Object) Hash(ctx context.Context, t hash.Type) (string, error) {
|
func (o *Object) Hash(ctx context.Context, t hash.Type) (string, error) {
|
||||||
|
if o.fs.opt.SharedFiles || o.fs.opt.SharedFolders {
|
||||||
|
return "", errNotSupportedInSharedMode
|
||||||
|
}
|
||||||
if t != DbHashType {
|
if t != DbHashType {
|
||||||
return "", hash.ErrUnsupported
|
return "", hash.ErrUnsupported
|
||||||
}
|
}
|
||||||
@@ -926,8 +1208,9 @@ func (o *Object) Size() int64 {
|
|||||||
|
|
||||||
// setMetadataFromEntry sets the fs data from a files.FileMetadata
|
// setMetadataFromEntry sets the fs data from a files.FileMetadata
|
||||||
//
|
//
|
||||||
// This isn't a complete set of metadata and has an inacurate date
|
// This isn't a complete set of metadata and has an inaccurate date
|
||||||
func (o *Object) setMetadataFromEntry(info *files.FileMetadata) error {
|
func (o *Object) setMetadataFromEntry(info *files.FileMetadata) error {
|
||||||
|
o.id = info.Id
|
||||||
o.bytes = int64(info.Size)
|
o.bytes = int64(info.Size)
|
||||||
o.modTime = info.ClientModified
|
o.modTime = info.ClientModified
|
||||||
o.hash = info.ContentHash
|
o.hash = info.ContentHash
|
||||||
@@ -996,10 +1279,27 @@ func (o *Object) Storable() bool {
|
|||||||
|
|
||||||
// Open an object for read
|
// Open an object for read
|
||||||
func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.ReadCloser, err error) {
|
func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.ReadCloser, err error) {
|
||||||
|
if o.fs.opt.SharedFiles {
|
||||||
|
if len(options) != 0 {
|
||||||
|
return nil, errors.New("OpenOptions not supported for shared files")
|
||||||
|
}
|
||||||
|
arg := sharing.GetSharedLinkMetadataArg{
|
||||||
|
Url: o.url,
|
||||||
|
}
|
||||||
|
err = o.fs.pacer.Call(func() (bool, error) {
|
||||||
|
_, in, err = o.fs.sharing.GetSharedLinkFile(&arg)
|
||||||
|
return shouldRetry(err)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
fs.FixRangeOption(options, o.bytes)
|
fs.FixRangeOption(options, o.bytes)
|
||||||
headers := fs.OpenOptionHeaders(options)
|
headers := fs.OpenOptionHeaders(options)
|
||||||
arg := files.DownloadArg{
|
arg := files.DownloadArg{
|
||||||
Path: enc.FromStandardPath(o.remotePath()),
|
Path: o.id,
|
||||||
ExtraHeaders: headers,
|
ExtraHeaders: headers,
|
||||||
}
|
}
|
||||||
err = o.fs.pacer.Call(func() (bool, error) {
|
err = o.fs.pacer.Call(func() (bool, error) {
|
||||||
@@ -1111,6 +1411,13 @@ func (o *Object) uploadChunked(in0 io.Reader, commitInfo *files.CommitInfo, size
|
|||||||
return false, nil
|
return false, nil
|
||||||
}
|
}
|
||||||
entry, err = o.fs.srv.UploadSessionFinish(args, chunk)
|
entry, err = o.fs.srv.UploadSessionFinish(args, chunk)
|
||||||
|
// If error is insufficient space then don't retry
|
||||||
|
if e, ok := err.(files.UploadSessionFinishAPIError); ok {
|
||||||
|
if e.EndpointError != nil && e.EndpointError.Path != nil && e.EndpointError.Path.Tag == files.WriteErrorInsufficientSpace {
|
||||||
|
err = fserrors.NoRetryError(err)
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
}
|
||||||
// after the first chunk is uploaded, we retry everything
|
// after the first chunk is uploaded, we retry everything
|
||||||
return err != nil, err
|
return err != nil, err
|
||||||
})
|
})
|
||||||
@@ -1120,20 +1427,52 @@ func (o *Object) uploadChunked(in0 io.Reader, commitInfo *files.CommitInfo, size
|
|||||||
return entry, nil
|
return entry, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// checks all the parts of name to see they are below
|
||||||
|
// maxFileNameLength runes.
|
||||||
|
//
|
||||||
|
// This checks the length as runes which isn't quite right as dropbox
|
||||||
|
// seems to encode some symbols (eg ☺) as two "characters". This seems
|
||||||
|
// like utf-16 except that ☺ doesn't need two characters in utf-16.
|
||||||
|
//
|
||||||
|
// Using runes instead of what dropbox is using will work for most
|
||||||
|
// cases, and when it goes wrong we will upload something we should
|
||||||
|
// have detected as too long which is the least damaging way to fail.
|
||||||
|
func checkPathLength(name string) (err error) {
|
||||||
|
for next := ""; len(name) > 0; name = next {
|
||||||
|
if slash := strings.IndexRune(name, '/'); slash >= 0 {
|
||||||
|
name, next = name[:slash], name[slash+1:]
|
||||||
|
} else {
|
||||||
|
next = ""
|
||||||
|
}
|
||||||
|
length := utf8.RuneCountInString(name)
|
||||||
|
if length > maxFileNameLength {
|
||||||
|
return fserrors.NoRetryError(fs.ErrorFileNameTooLong)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// Update the already existing object
|
// Update the already existing object
|
||||||
//
|
//
|
||||||
// Copy the reader into the object updating modTime and size
|
// Copy the reader into the object updating modTime and size
|
||||||
//
|
//
|
||||||
// The new object may have been created if an error is returned
|
// The new object may have been created if an error is returned
|
||||||
func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) error {
|
func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) error {
|
||||||
|
if o.fs.opt.SharedFiles || o.fs.opt.SharedFolders {
|
||||||
|
return errNotSupportedInSharedMode
|
||||||
|
}
|
||||||
remote := o.remotePath()
|
remote := o.remotePath()
|
||||||
if ignoredFiles.MatchString(remote) {
|
if ignoredFiles.MatchString(remote) {
|
||||||
return fserrors.NoRetryError(errors.Errorf("file name %q is disallowed - not uploading", path.Base(remote)))
|
return fserrors.NoRetryError(errors.Errorf("file name %q is disallowed - not uploading", path.Base(remote)))
|
||||||
}
|
}
|
||||||
commitInfo := files.NewCommitInfo(enc.FromStandardPath(o.remotePath()))
|
commitInfo := files.NewCommitInfo(o.fs.opt.Enc.FromStandardPath(o.remotePath()))
|
||||||
commitInfo.Mode.Tag = "overwrite"
|
commitInfo.Mode.Tag = "overwrite"
|
||||||
// The Dropbox API only accepts timestamps in UTC with second precision.
|
// The Dropbox API only accepts timestamps in UTC with second precision.
|
||||||
commitInfo.ClientModified = src.ModTime(ctx).UTC().Round(time.Second)
|
commitInfo.ClientModified = src.ModTime(ctx).UTC().Round(time.Second)
|
||||||
|
// Don't attempt to create filenames that are too long
|
||||||
|
if cErr := checkPathLength(commitInfo.Path); cErr != nil {
|
||||||
|
return cErr
|
||||||
|
}
|
||||||
|
|
||||||
size := src.Size()
|
size := src.Size()
|
||||||
var err error
|
var err error
|
||||||
@@ -1154,9 +1493,12 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
|
|
||||||
// Remove an object
|
// Remove an object
|
||||||
func (o *Object) Remove(ctx context.Context) (err error) {
|
func (o *Object) Remove(ctx context.Context) (err error) {
|
||||||
|
if o.fs.opt.SharedFiles || o.fs.opt.SharedFolders {
|
||||||
|
return errNotSupportedInSharedMode
|
||||||
|
}
|
||||||
err = o.fs.pacer.Call(func() (bool, error) {
|
err = o.fs.pacer.Call(func() (bool, error) {
|
||||||
_, err = o.fs.srv.DeleteV2(&files.DeleteArg{
|
_, err = o.fs.srv.DeleteV2(&files.DeleteArg{
|
||||||
Path: enc.FromStandardPath(o.remotePath()),
|
Path: o.fs.opt.Enc.FromStandardPath(o.remotePath()),
|
||||||
})
|
})
|
||||||
return shouldRetry(err)
|
return shouldRetry(err)
|
||||||
})
|
})
|
||||||
@@ -1174,4 +1516,5 @@ var (
|
|||||||
_ fs.DirMover = (*Fs)(nil)
|
_ fs.DirMover = (*Fs)(nil)
|
||||||
_ fs.Abouter = (*Fs)(nil)
|
_ fs.Abouter = (*Fs)(nil)
|
||||||
_ fs.Object = (*Object)(nil)
|
_ fs.Object = (*Object)(nil)
|
||||||
|
_ fs.IDer = (*Object)(nil)
|
||||||
)
|
)
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package dropbox
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestInternalCheckPathLength(t *testing.T) {
|
||||||
|
rep := func(n int, r rune) (out string) {
|
||||||
|
rs := make([]rune, n)
|
||||||
|
for i := range rs {
|
||||||
|
rs[i] = r
|
||||||
|
}
|
||||||
|
return string(rs)
|
||||||
|
}
|
||||||
|
for _, test := range []struct {
|
||||||
|
in string
|
||||||
|
ok bool
|
||||||
|
}{
|
||||||
|
{in: "", ok: true},
|
||||||
|
{in: rep(maxFileNameLength, 'a'), ok: true},
|
||||||
|
{in: rep(maxFileNameLength+1, 'a'), ok: false},
|
||||||
|
{in: rep(maxFileNameLength, '£'), ok: true},
|
||||||
|
{in: rep(maxFileNameLength+1, '£'), ok: false},
|
||||||
|
{in: rep(maxFileNameLength, '☺'), ok: true},
|
||||||
|
{in: rep(maxFileNameLength+1, '☺'), ok: false},
|
||||||
|
{in: rep(maxFileNameLength, '你'), ok: true},
|
||||||
|
{in: rep(maxFileNameLength+1, '你'), ok: false},
|
||||||
|
{in: "/ok/ok", ok: true},
|
||||||
|
{in: "/ok/" + rep(maxFileNameLength, 'a') + "/ok", ok: true},
|
||||||
|
{in: "/ok/" + rep(maxFileNameLength+1, 'a') + "/ok", ok: false},
|
||||||
|
{in: "/ok/" + rep(maxFileNameLength, '£') + "/ok", ok: true},
|
||||||
|
{in: "/ok/" + rep(maxFileNameLength+1, '£') + "/ok", ok: false},
|
||||||
|
{in: "/ok/" + rep(maxFileNameLength, '☺') + "/ok", ok: true},
|
||||||
|
{in: "/ok/" + rep(maxFileNameLength+1, '☺') + "/ok", ok: false},
|
||||||
|
{in: "/ok/" + rep(maxFileNameLength, '你') + "/ok", ok: true},
|
||||||
|
{in: "/ok/" + rep(maxFileNameLength+1, '你') + "/ok", ok: false},
|
||||||
|
} {
|
||||||
|
|
||||||
|
err := checkPathLength(test.in)
|
||||||
|
assert.Equal(t, test.ok, err == nil, test.in)
|
||||||
|
}
|
||||||
|
}
|
||||||
+23
-11
@@ -6,6 +6,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
@@ -17,6 +18,7 @@ import (
|
|||||||
// retryErrorCodes is a slice of error codes that we will retry
|
// retryErrorCodes is a slice of error codes that we will retry
|
||||||
var retryErrorCodes = []int{
|
var retryErrorCodes = []int{
|
||||||
429, // Too Many Requests.
|
429, // Too Many Requests.
|
||||||
|
403, // Forbidden (may happen when request limit is exceeded)
|
||||||
500, // Internal Server Error
|
500, // Internal Server Error
|
||||||
502, // Bad Gateway
|
502, // Bad Gateway
|
||||||
503, // Service Unavailable
|
503, // Service Unavailable
|
||||||
@@ -27,6 +29,20 @@ var retryErrorCodes = []int{
|
|||||||
// shouldRetry returns a boolean as to whether this resp and err
|
// shouldRetry returns a boolean as to whether this resp and err
|
||||||
// deserve to be retried. It returns the err as a convenience
|
// deserve to be retried. It returns the err as a convenience
|
||||||
func shouldRetry(resp *http.Response, err error) (bool, error) {
|
func shouldRetry(resp *http.Response, err error) (bool, error) {
|
||||||
|
// Detect this error which the integration tests provoke
|
||||||
|
// error HTTP error 403 (403 Forbidden) returned body: "{\"message\":\"Flood detected: IP Locked #374\",\"status\":\"KO\"}"
|
||||||
|
//
|
||||||
|
// https://1fichier.com/api.html
|
||||||
|
//
|
||||||
|
// file/ls.cgi is limited :
|
||||||
|
//
|
||||||
|
// Warning (can be changed in case of abuses) :
|
||||||
|
// List all files of the account is limited to 1 request per hour.
|
||||||
|
// List folders is limited to 5 000 results and 1 request per folder per 30s.
|
||||||
|
if err != nil && strings.Contains(err.Error(), "Flood detected") {
|
||||||
|
fs.Debugf(nil, "Sleeping for 30 seconds due to: %v", err)
|
||||||
|
time.Sleep(30 * time.Second)
|
||||||
|
}
|
||||||
return fserrors.ShouldRetry(err) || fserrors.ShouldRetryHTTP(resp, retryErrorCodes), err
|
return fserrors.ShouldRetry(err) || fserrors.ShouldRetryHTTP(resp, retryErrorCodes), err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -109,7 +125,7 @@ func (f *Fs) listFiles(ctx context.Context, directoryID int) (filesList *FilesLi
|
|||||||
}
|
}
|
||||||
for i := range filesList.Items {
|
for i := range filesList.Items {
|
||||||
item := &filesList.Items[i]
|
item := &filesList.Items[i]
|
||||||
item.Filename = enc.ToStandardName(item.Filename)
|
item.Filename = f.opt.Enc.ToStandardName(item.Filename)
|
||||||
}
|
}
|
||||||
|
|
||||||
return filesList, nil
|
return filesList, nil
|
||||||
@@ -135,10 +151,10 @@ func (f *Fs) listFolders(ctx context.Context, directoryID int) (foldersList *Fol
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "couldn't list folders")
|
return nil, errors.Wrap(err, "couldn't list folders")
|
||||||
}
|
}
|
||||||
foldersList.Name = enc.ToStandardName(foldersList.Name)
|
foldersList.Name = f.opt.Enc.ToStandardName(foldersList.Name)
|
||||||
for i := range foldersList.SubFolders {
|
for i := range foldersList.SubFolders {
|
||||||
folder := &foldersList.SubFolders[i]
|
folder := &foldersList.SubFolders[i]
|
||||||
folder.Name = enc.ToStandardName(folder.Name)
|
folder.Name = f.opt.Enc.ToStandardName(folder.Name)
|
||||||
}
|
}
|
||||||
|
|
||||||
// fs.Debugf(f, "Got FoldersList for id `%s`", directoryID)
|
// fs.Debugf(f, "Got FoldersList for id `%s`", directoryID)
|
||||||
@@ -147,11 +163,6 @@ func (f *Fs) listFolders(ctx context.Context, directoryID int) (foldersList *Fol
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fs) listDir(ctx context.Context, dir string) (entries fs.DirEntries, err error) {
|
func (f *Fs) listDir(ctx context.Context, dir string) (entries fs.DirEntries, err error) {
|
||||||
err = f.dirCache.FindRoot(ctx, false)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
directoryID, err := f.dirCache.FindDir(ctx, dir, false)
|
directoryID, err := f.dirCache.FindDir(ctx, dir, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -213,7 +224,7 @@ func getRemote(dir, fileName string) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fs) makeFolder(ctx context.Context, leaf string, folderID int) (response *MakeFolderResponse, err error) {
|
func (f *Fs) makeFolder(ctx context.Context, leaf string, folderID int) (response *MakeFolderResponse, err error) {
|
||||||
name := enc.FromStandardName(leaf)
|
name := f.opt.Enc.FromStandardName(leaf)
|
||||||
// fs.Debugf(f, "Creating folder `%s` in id `%s`", name, directoryID)
|
// fs.Debugf(f, "Creating folder `%s` in id `%s`", name, directoryID)
|
||||||
|
|
||||||
request := MakeFolderRequest{
|
request := MakeFolderRequest{
|
||||||
@@ -320,10 +331,10 @@ func (f *Fs) getUploadNode(ctx context.Context) (response *GetUploadNodeResponse
|
|||||||
return response, err
|
return response, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fs) uploadFile(ctx context.Context, in io.Reader, size int64, fileName, folderID, uploadID, node string) (response *http.Response, err error) {
|
func (f *Fs) uploadFile(ctx context.Context, in io.Reader, size int64, fileName, folderID, uploadID, node string, options ...fs.OpenOption) (response *http.Response, err error) {
|
||||||
// fs.Debugf(f, "Uploading File `%s`", fileName)
|
// fs.Debugf(f, "Uploading File `%s`", fileName)
|
||||||
|
|
||||||
fileName = enc.FromStandardName(fileName)
|
fileName = f.opt.Enc.FromStandardName(fileName)
|
||||||
|
|
||||||
if len(uploadID) > 10 || !isAlphaNumeric(uploadID) {
|
if len(uploadID) > 10 || !isAlphaNumeric(uploadID) {
|
||||||
return nil, errors.New("Invalid UploadID")
|
return nil, errors.New("Invalid UploadID")
|
||||||
@@ -338,6 +349,7 @@ func (f *Fs) uploadFile(ctx context.Context, in io.Reader, size int64, fileName,
|
|||||||
NoResponse: true,
|
NoResponse: true,
|
||||||
Body: in,
|
Body: in,
|
||||||
ContentLength: &size,
|
ContentLength: &size,
|
||||||
|
Options: options,
|
||||||
MultipartContentName: "file[]",
|
MultipartContentName: "file[]",
|
||||||
MultipartFileName: fileName,
|
MultipartFileName: fileName,
|
||||||
MultipartParams: map[string][]string{
|
MultipartParams: map[string][]string{
|
||||||
|
|||||||
+65
-54
@@ -11,52 +11,75 @@ import (
|
|||||||
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"github.com/rclone/rclone/fs"
|
"github.com/rclone/rclone/fs"
|
||||||
|
"github.com/rclone/rclone/fs/config"
|
||||||
"github.com/rclone/rclone/fs/config/configmap"
|
"github.com/rclone/rclone/fs/config/configmap"
|
||||||
"github.com/rclone/rclone/fs/config/configstruct"
|
"github.com/rclone/rclone/fs/config/configstruct"
|
||||||
"github.com/rclone/rclone/fs/encodings"
|
|
||||||
"github.com/rclone/rclone/fs/fshttp"
|
"github.com/rclone/rclone/fs/fshttp"
|
||||||
"github.com/rclone/rclone/fs/hash"
|
"github.com/rclone/rclone/fs/hash"
|
||||||
"github.com/rclone/rclone/lib/dircache"
|
"github.com/rclone/rclone/lib/dircache"
|
||||||
|
"github.com/rclone/rclone/lib/encoder"
|
||||||
"github.com/rclone/rclone/lib/pacer"
|
"github.com/rclone/rclone/lib/pacer"
|
||||||
"github.com/rclone/rclone/lib/rest"
|
"github.com/rclone/rclone/lib/rest"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
rootID = "0"
|
rootID = "0"
|
||||||
apiBaseURL = "https://api.1fichier.com/v1"
|
apiBaseURL = "https://api.1fichier.com/v1"
|
||||||
minSleep = 334 * time.Millisecond // 3 API calls per second is recommended
|
minSleep = 400 * time.Millisecond // api is extremely rate limited now
|
||||||
maxSleep = 5 * time.Second
|
maxSleep = 5 * time.Second
|
||||||
decayConstant = 2 // bigger for slower decay, exponential
|
decayConstant = 2 // bigger for slower decay, exponential
|
||||||
|
attackConstant = 0 // start with max sleep
|
||||||
)
|
)
|
||||||
|
|
||||||
const enc = encodings.Fichier
|
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
fs.Register(&fs.RegInfo{
|
fs.Register(&fs.RegInfo{
|
||||||
Name: "fichier",
|
Name: "fichier",
|
||||||
Description: "1Fichier",
|
Description: "1Fichier",
|
||||||
Config: func(name string, config configmap.Mapper) {
|
Config: func(ctx context.Context, name string, config configmap.Mapper) {
|
||||||
},
|
},
|
||||||
NewFs: NewFs,
|
NewFs: NewFs,
|
||||||
Options: []fs.Option{
|
Options: []fs.Option{{
|
||||||
{
|
Help: "Your API Key, get it from https://1fichier.com/console/params.pl",
|
||||||
Help: "Your API Key, get it from https://1fichier.com/console/params.pl",
|
Name: "api_key",
|
||||||
Name: "api_key",
|
}, {
|
||||||
},
|
Help: "If you want to download a shared folder, add this parameter",
|
||||||
{
|
Name: "shared_folder",
|
||||||
Help: "If you want to download a shared folder, add this parameter",
|
Required: false,
|
||||||
Name: "shared_folder",
|
Advanced: true,
|
||||||
Required: false,
|
}, {
|
||||||
Advanced: true,
|
Name: config.ConfigEncoding,
|
||||||
},
|
Help: config.ConfigEncodingHelp,
|
||||||
},
|
Advanced: true,
|
||||||
|
// Characters that need escaping
|
||||||
|
//
|
||||||
|
// '\\': '\', // FULLWIDTH REVERSE SOLIDUS
|
||||||
|
// '<': '<', // FULLWIDTH LESS-THAN SIGN
|
||||||
|
// '>': '>', // FULLWIDTH GREATER-THAN SIGN
|
||||||
|
// '"': '"', // FULLWIDTH QUOTATION MARK - not on the list but seems to be reserved
|
||||||
|
// '\'': ''', // FULLWIDTH APOSTROPHE
|
||||||
|
// '$': '$', // FULLWIDTH DOLLAR SIGN
|
||||||
|
// '`': '`', // FULLWIDTH GRAVE ACCENT
|
||||||
|
//
|
||||||
|
// Leading space and trailing space
|
||||||
|
Default: (encoder.Display |
|
||||||
|
encoder.EncodeBackSlash |
|
||||||
|
encoder.EncodeSingleQuote |
|
||||||
|
encoder.EncodeBackQuote |
|
||||||
|
encoder.EncodeDoubleQuote |
|
||||||
|
encoder.EncodeLtGt |
|
||||||
|
encoder.EncodeDollar |
|
||||||
|
encoder.EncodeLeftSpace |
|
||||||
|
encoder.EncodeRightSpace |
|
||||||
|
encoder.EncodeInvalidUtf8),
|
||||||
|
}},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Options defines the configuration for this backend
|
// Options defines the configuration for this backend
|
||||||
type Options struct {
|
type Options struct {
|
||||||
APIKey string `config:"api_key"`
|
APIKey string `config:"api_key"`
|
||||||
SharedFolder string `config:"shared_folder"`
|
SharedFolder string `config:"shared_folder"`
|
||||||
|
Enc encoder.MultiEncoder `config:"encoding"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fs is the interface a cloud storage system must provide
|
// Fs is the interface a cloud storage system must provide
|
||||||
@@ -64,9 +87,9 @@ type Fs struct {
|
|||||||
root string
|
root string
|
||||||
name string
|
name string
|
||||||
features *fs.Features
|
features *fs.Features
|
||||||
|
opt Options
|
||||||
dirCache *dircache.DirCache
|
dirCache *dircache.DirCache
|
||||||
baseClient *http.Client
|
baseClient *http.Client
|
||||||
options *Options
|
|
||||||
pacer *fs.Pacer
|
pacer *fs.Pacer
|
||||||
rest *rest.Client
|
rest *rest.Client
|
||||||
}
|
}
|
||||||
@@ -144,7 +167,7 @@ func (f *Fs) Features() *fs.Features {
|
|||||||
//
|
//
|
||||||
// On Windows avoid single character remote names as they can be mixed
|
// On Windows avoid single character remote names as they can be mixed
|
||||||
// up with drive letters.
|
// up with drive letters.
|
||||||
func NewFs(name string, root string, config configmap.Mapper) (fs.Fs, error) {
|
func NewFs(ctx context.Context, name string, root string, config configmap.Mapper) (fs.Fs, error) {
|
||||||
opt := new(Options)
|
opt := new(Options)
|
||||||
err := configstruct.Set(config, opt)
|
err := configstruct.Set(config, opt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -162,26 +185,25 @@ func NewFs(name string, root string, config configmap.Mapper) (fs.Fs, error) {
|
|||||||
f := &Fs{
|
f := &Fs{
|
||||||
name: name,
|
name: name,
|
||||||
root: root,
|
root: root,
|
||||||
options: opt,
|
opt: *opt,
|
||||||
pacer: fs.NewPacer(pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
|
pacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant), pacer.AttackConstant(attackConstant))),
|
||||||
baseClient: &http.Client{},
|
baseClient: &http.Client{},
|
||||||
}
|
}
|
||||||
|
|
||||||
f.features = (&fs.Features{
|
f.features = (&fs.Features{
|
||||||
DuplicateFiles: true,
|
DuplicateFiles: true,
|
||||||
CanHaveEmptyDirectories: true,
|
CanHaveEmptyDirectories: true,
|
||||||
}).Fill(f)
|
ReadMimeType: true,
|
||||||
|
}).Fill(ctx, f)
|
||||||
|
|
||||||
client := fshttp.NewClient(fs.Config)
|
client := fshttp.NewClient(ctx)
|
||||||
|
|
||||||
f.rest = rest.NewClient(client).SetRoot(apiBaseURL)
|
f.rest = rest.NewClient(client).SetRoot(apiBaseURL)
|
||||||
|
|
||||||
f.rest.SetHeader("Authorization", "Bearer "+f.options.APIKey)
|
f.rest.SetHeader("Authorization", "Bearer "+f.opt.APIKey)
|
||||||
|
|
||||||
f.dirCache = dircache.New(root, rootID, f)
|
f.dirCache = dircache.New(root, rootID, f)
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
// Find the current root
|
// Find the current root
|
||||||
err = f.dirCache.FindRoot(ctx, false)
|
err = f.dirCache.FindRoot(ctx, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -204,7 +226,7 @@ func NewFs(name string, root string, config configmap.Mapper) (fs.Fs, error) {
|
|||||||
}
|
}
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
f.features.Fill(&tempF)
|
f.features.Fill(ctx, &tempF)
|
||||||
// XXX: update the old f here instead of returning tempF, since
|
// XXX: update the old f here instead of returning tempF, since
|
||||||
// `features` were already filled with functions having *f as a receiver.
|
// `features` were already filled with functions having *f as a receiver.
|
||||||
// See https://github.com/rclone/rclone/issues/2182
|
// See https://github.com/rclone/rclone/issues/2182
|
||||||
@@ -226,8 +248,8 @@ func NewFs(name string, root string, config configmap.Mapper) (fs.Fs, error) {
|
|||||||
// This should return ErrDirNotFound if the directory isn't
|
// This should return ErrDirNotFound if the directory isn't
|
||||||
// found.
|
// found.
|
||||||
func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) {
|
func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) {
|
||||||
if f.options.SharedFolder != "" {
|
if f.opt.SharedFolder != "" {
|
||||||
return f.listSharedFiles(ctx, f.options.SharedFolder)
|
return f.listSharedFiles(ctx, f.opt.SharedFolder)
|
||||||
}
|
}
|
||||||
|
|
||||||
dirContent, err := f.listDir(ctx, dir)
|
dirContent, err := f.listDir(ctx, dir)
|
||||||
@@ -241,7 +263,7 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
|
|||||||
// NewObject finds the Object at remote. If it can't be found
|
// NewObject finds the Object at remote. If it can't be found
|
||||||
// it returns the error ErrorObjectNotFound.
|
// it returns the error ErrorObjectNotFound.
|
||||||
func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) {
|
func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) {
|
||||||
leaf, directoryID, err := f.dirCache.FindRootAndPath(ctx, remote, false)
|
leaf, directoryID, err := f.dirCache.FindPath(ctx, remote, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err == fs.ErrorDirNotFound {
|
if err == fs.ErrorDirNotFound {
|
||||||
return nil, fs.ErrorObjectNotFound
|
return nil, fs.ErrorObjectNotFound
|
||||||
@@ -275,7 +297,7 @@ func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) {
|
|||||||
|
|
||||||
// Put in to the remote path with the modTime given of the given size
|
// Put in to the remote path with the modTime given of the given size
|
||||||
//
|
//
|
||||||
// When called from outside a Fs by rclone, src.Size() will always be >= 0.
|
// When called from outside an Fs by rclone, src.Size() will always be >= 0.
|
||||||
// But for unknown-sized objects (indicated by src.Size() == -1), Put should either
|
// But for unknown-sized objects (indicated by src.Size() == -1), Put should either
|
||||||
// return an error or upload it properly (rather than e.g. calling panic).
|
// return an error or upload it properly (rather than e.g. calling panic).
|
||||||
//
|
//
|
||||||
@@ -283,10 +305,10 @@ func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) {
|
|||||||
// will return the object and the error, otherwise will return
|
// will return the object and the error, otherwise will return
|
||||||
// nil and the error
|
// nil and the error
|
||||||
func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
|
func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
|
||||||
exisitingObj, err := f.NewObject(ctx, src.Remote())
|
existingObj, err := f.NewObject(ctx, src.Remote())
|
||||||
switch err {
|
switch err {
|
||||||
case nil:
|
case nil:
|
||||||
return exisitingObj, exisitingObj.Update(ctx, in, src, options...)
|
return existingObj, existingObj.Update(ctx, in, src, options...)
|
||||||
case fs.ErrorObjectNotFound:
|
case fs.ErrorObjectNotFound:
|
||||||
// Not found so create it
|
// Not found so create it
|
||||||
return f.PutUnchecked(ctx, in, src, options...)
|
return f.PutUnchecked(ctx, in, src, options...)
|
||||||
@@ -300,7 +322,7 @@ func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options .
|
|||||||
// This will create a duplicate if we upload a new file without
|
// This will create a duplicate if we upload a new file without
|
||||||
// checking to see if there is one already - use Put() for that.
|
// checking to see if there is one already - use Put() for that.
|
||||||
func (f *Fs) putUnchecked(ctx context.Context, in io.Reader, remote string, size int64, options ...fs.OpenOption) (fs.Object, error) {
|
func (f *Fs) putUnchecked(ctx context.Context, in io.Reader, remote string, size int64, options ...fs.OpenOption) (fs.Object, error) {
|
||||||
if size > int64(100e9) {
|
if size > int64(300e9) {
|
||||||
return nil, errors.New("File too big, cant upload")
|
return nil, errors.New("File too big, cant upload")
|
||||||
} else if size == 0 {
|
} else if size == 0 {
|
||||||
return nil, fs.ErrorCantUploadEmptyFiles
|
return nil, fs.ErrorCantUploadEmptyFiles
|
||||||
@@ -311,12 +333,12 @@ func (f *Fs) putUnchecked(ctx context.Context, in io.Reader, remote string, size
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
leaf, directoryID, err := f.dirCache.FindRootAndPath(ctx, remote, true)
|
leaf, directoryID, err := f.dirCache.FindPath(ctx, remote, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err = f.uploadFile(ctx, in, size, leaf, directoryID, nodeResponse.ID, nodeResponse.URL)
|
_, err = f.uploadFile(ctx, in, size, leaf, directoryID, nodeResponse.ID, nodeResponse.URL, options...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -366,13 +388,7 @@ func (f *Fs) PutUnchecked(ctx context.Context, in io.Reader, src fs.ObjectInfo,
|
|||||||
//
|
//
|
||||||
// Shouldn't return an error if it already exists
|
// Shouldn't return an error if it already exists
|
||||||
func (f *Fs) Mkdir(ctx context.Context, dir string) error {
|
func (f *Fs) Mkdir(ctx context.Context, dir string) error {
|
||||||
err := f.dirCache.FindRoot(ctx, true)
|
_, err := f.dirCache.FindDir(ctx, dir, true)
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if dir != "" {
|
|
||||||
_, err = f.dirCache.FindDir(ctx, dir, true)
|
|
||||||
}
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -380,11 +396,6 @@ func (f *Fs) Mkdir(ctx context.Context, dir string) error {
|
|||||||
//
|
//
|
||||||
// Return an error if it doesn't exist or isn't empty
|
// Return an error if it doesn't exist or isn't empty
|
||||||
func (f *Fs) Rmdir(ctx context.Context, dir string) error {
|
func (f *Fs) Rmdir(ctx context.Context, dir string) error {
|
||||||
err := f.dirCache.FindRoot(ctx, false)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
directoryID, err := f.dirCache.FindDir(ctx, dir, false)
|
directoryID, err := f.dirCache.FindDir(ctx, dir, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
|||||||
@@ -4,13 +4,11 @@ package fichier
|
|||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/rclone/rclone/fs"
|
|
||||||
"github.com/rclone/rclone/fstest/fstests"
|
"github.com/rclone/rclone/fstest/fstests"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TestIntegration runs integration tests against the remote
|
// TestIntegration runs integration tests against the remote
|
||||||
func TestIntegration(t *testing.T) {
|
func TestIntegration(t *testing.T) {
|
||||||
fs.Config.LogLevel = fs.LogLevelDebug
|
|
||||||
fstests.Run(t, &fstests.Opt{
|
fstests.Run(t, &fstests.Opt{
|
||||||
RemoteName: "TestFichier:",
|
RemoteName: "TestFichier:",
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -101,7 +101,7 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadClo
|
|||||||
|
|
||||||
// Update in to the object with the modTime given of the given size
|
// Update in to the object with the modTime given of the given size
|
||||||
//
|
//
|
||||||
// When called from outside a Fs by rclone, src.Size() will always be >= 0.
|
// When called from outside an Fs by rclone, src.Size() will always be >= 0.
|
||||||
// But for unknown-sized objects (indicated by src.Size() == -1), Upload should either
|
// But for unknown-sized objects (indicated by src.Size() == -1), Upload should either
|
||||||
// return an error or update the object properly (rather than e.g. calling panic).
|
// return an error or update the object properly (rather than e.g. calling panic).
|
||||||
func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) error {
|
func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) error {
|
||||||
|
|||||||
@@ -0,0 +1,391 @@
|
|||||||
|
// Package api has type definitions for filefabric
|
||||||
|
//
|
||||||
|
// Converted from the API responses with help from https://mholt.github.io/json-to-go/
|
||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// TimeFormat for parameters (UTC)
|
||||||
|
timeFormatParameters = `2006-01-02 15:04:05`
|
||||||
|
// "2020-08-11 10:10:04" for JSON parsing
|
||||||
|
timeFormatJSON = `"` + timeFormatParameters + `"`
|
||||||
|
)
|
||||||
|
|
||||||
|
// Time represents represents date and time information for the
|
||||||
|
// filefabric API
|
||||||
|
type Time time.Time
|
||||||
|
|
||||||
|
// MarshalJSON turns a Time into JSON (in UTC)
|
||||||
|
func (t *Time) MarshalJSON() (out []byte, err error) {
|
||||||
|
timeString := (*time.Time)(t).UTC().Format(timeFormatJSON)
|
||||||
|
return []byte(timeString), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var zeroTime = []byte(`"0000-00-00 00:00:00"`)
|
||||||
|
|
||||||
|
// UnmarshalJSON turns JSON into a Time (in UTC)
|
||||||
|
func (t *Time) UnmarshalJSON(data []byte) error {
|
||||||
|
// Set a Zero time.Time if we receive a zero time input
|
||||||
|
if bytes.Equal(data, zeroTime) {
|
||||||
|
*t = Time(time.Time{})
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
newT, err := time.Parse(timeFormatJSON, string(data))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
*t = Time(newT)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// String turns a Time into a string in UTC suitable for the API
|
||||||
|
// parameters
|
||||||
|
func (t Time) String() string {
|
||||||
|
return time.Time(t).UTC().Format(timeFormatParameters)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Status return returned in all status responses
|
||||||
|
type Status struct {
|
||||||
|
Code string `json:"status"`
|
||||||
|
Message string `json:"statusmessage"`
|
||||||
|
TaskID string `json:"taskid"`
|
||||||
|
// Warning string `json:"warning"` // obsolete
|
||||||
|
}
|
||||||
|
|
||||||
|
// Status statisfies the error interface
|
||||||
|
func (e *Status) Error() string {
|
||||||
|
return fmt.Sprintf("%s (%s)", e.Message, e.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
// OK returns true if the status is all good
|
||||||
|
func (e *Status) OK() bool {
|
||||||
|
return e.Code == "ok"
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetCode returns the status code if any
|
||||||
|
func (e *Status) GetCode() string {
|
||||||
|
return e.Code
|
||||||
|
}
|
||||||
|
|
||||||
|
// OKError defines an interface for items which can be OK or be an error
|
||||||
|
type OKError interface {
|
||||||
|
error
|
||||||
|
OK() bool
|
||||||
|
GetCode() string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check Status satisfies the OKError interface
|
||||||
|
var _ OKError = (*Status)(nil)
|
||||||
|
|
||||||
|
// EmptyResponse is response which just returns the error condition
|
||||||
|
type EmptyResponse struct {
|
||||||
|
Status
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetTokenByAuthTokenResponse is the response to getTokenByAuthToken
|
||||||
|
type GetTokenByAuthTokenResponse struct {
|
||||||
|
Status
|
||||||
|
Token string `json:"token"`
|
||||||
|
UserID string `json:"userid"`
|
||||||
|
AllowLoginRemember string `json:"allowloginremember"`
|
||||||
|
LastLogin Time `json:"lastlogin"`
|
||||||
|
AutoLoginCode string `json:"autologincode"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ApplianceInfo is the response to getApplianceInfo
|
||||||
|
type ApplianceInfo struct {
|
||||||
|
Status
|
||||||
|
Sitetitle string `json:"sitetitle"`
|
||||||
|
OauthLoginSupport string `json:"oauthloginsupport"`
|
||||||
|
IsAppliance string `json:"isappliance"`
|
||||||
|
SoftwareVersion string `json:"softwareversion"`
|
||||||
|
SoftwareVersionLabel string `json:"softwareversionlabel"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetFolderContentsResponse is returned from getFolderContents
|
||||||
|
type GetFolderContentsResponse struct {
|
||||||
|
Status
|
||||||
|
Total int `json:"total,string"`
|
||||||
|
Items []Item `json:"filelist"`
|
||||||
|
Folder Item `json:"folder"`
|
||||||
|
From int `json:"from,string"`
|
||||||
|
//Count int `json:"count"`
|
||||||
|
Pid string `json:"pid"`
|
||||||
|
RefreshResult Status `json:"refreshresult"`
|
||||||
|
// Curfolder Item `json:"curfolder"` - sometimes returned as "ROOT"?
|
||||||
|
Parents []Item `json:"parents"`
|
||||||
|
CustomPermissions CustomPermissions `json:"custompermissions"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ItemType determine whether it is a file or a folder
|
||||||
|
type ItemType uint8
|
||||||
|
|
||||||
|
// Types of things in Item
|
||||||
|
const (
|
||||||
|
ItemTypeFile ItemType = 0
|
||||||
|
ItemTypeFolder ItemType = 1
|
||||||
|
)
|
||||||
|
|
||||||
|
// Item ia a File or a Folder
|
||||||
|
type Item struct {
|
||||||
|
ID string `json:"fi_id"`
|
||||||
|
PID string `json:"fi_pid"`
|
||||||
|
// UID string `json:"fi_uid"`
|
||||||
|
Name string `json:"fi_name"`
|
||||||
|
// S3Name string `json:"fi_s3name"`
|
||||||
|
// Extension string `json:"fi_extension"`
|
||||||
|
// Description string `json:"fi_description"`
|
||||||
|
Type ItemType `json:"fi_type,string"`
|
||||||
|
// Created Time `json:"fi_created"`
|
||||||
|
Size int64 `json:"fi_size,string"`
|
||||||
|
ContentType string `json:"fi_contenttype"`
|
||||||
|
// Tags string `json:"fi_tags"`
|
||||||
|
// MainCode string `json:"fi_maincode"`
|
||||||
|
// Public int `json:"fi_public,string"`
|
||||||
|
// Provider string `json:"fi_provider"`
|
||||||
|
// ProviderFolder string `json:"fi_providerfolder"` // folder
|
||||||
|
// Encrypted int `json:"fi_encrypted,string"`
|
||||||
|
// StructType string `json:"fi_structtype"`
|
||||||
|
// Bname string `json:"fi_bname"` // folder
|
||||||
|
// OrgID string `json:"fi_orgid"`
|
||||||
|
// Favorite int `json:"fi_favorite,string"`
|
||||||
|
// IspartOf string `json:"fi_ispartof"` // folder
|
||||||
|
Modified Time `json:"fi_modified"`
|
||||||
|
// LastAccessed Time `json:"fi_lastaccessed"`
|
||||||
|
// Hits int64 `json:"fi_hits,string"`
|
||||||
|
// IP string `json:"fi_ip"` // folder
|
||||||
|
// BigDescription string `json:"fi_bigdescription"`
|
||||||
|
LocalTime Time `json:"fi_localtime"`
|
||||||
|
// OrgfolderID string `json:"fi_orgfolderid"`
|
||||||
|
// StorageIP string `json:"fi_storageip"` // folder
|
||||||
|
// RemoteTime Time `json:"fi_remotetime"`
|
||||||
|
// ProviderOptions string `json:"fi_provideroptions"`
|
||||||
|
// Access string `json:"fi_access"`
|
||||||
|
// Hidden string `json:"fi_hidden"` // folder
|
||||||
|
// VersionOf string `json:"fi_versionof"`
|
||||||
|
Trash bool `json:"trash"`
|
||||||
|
// Isbucket string `json:"isbucket"` // filelist
|
||||||
|
SubFolders int64 `json:"subfolders"` // folder
|
||||||
|
}
|
||||||
|
|
||||||
|
// ItemFields is a | separated list of fields in Item
|
||||||
|
var ItemFields = mustFields(Item{})
|
||||||
|
|
||||||
|
// fields returns the JSON fields in use by opt as a | separated
|
||||||
|
// string.
|
||||||
|
func fields(opt interface{}) (pipeTags string, err error) {
|
||||||
|
var tags []string
|
||||||
|
def := reflect.ValueOf(opt)
|
||||||
|
defType := def.Type()
|
||||||
|
for i := 0; i < def.NumField(); i++ {
|
||||||
|
field := defType.Field(i)
|
||||||
|
tag, ok := field.Tag.Lookup("json")
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if comma := strings.IndexRune(tag, ','); comma >= 0 {
|
||||||
|
tag = tag[:comma]
|
||||||
|
}
|
||||||
|
if tag == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
tags = append(tags, tag)
|
||||||
|
}
|
||||||
|
return strings.Join(tags, "|"), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// mustFields returns the JSON fields in use by opt as a | separated
|
||||||
|
// string. It panics on failure.
|
||||||
|
func mustFields(opt interface{}) string {
|
||||||
|
tags, err := fields(opt)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return tags
|
||||||
|
}
|
||||||
|
|
||||||
|
// CustomPermissions is returned as part of GetFolderContentsResponse
|
||||||
|
type CustomPermissions struct {
|
||||||
|
Upload string `json:"upload"`
|
||||||
|
CreateSubFolder string `json:"createsubfolder"`
|
||||||
|
Rename string `json:"rename"`
|
||||||
|
Delete string `json:"delete"`
|
||||||
|
Move string `json:"move"`
|
||||||
|
ManagePermissions string `json:"managepermissions"`
|
||||||
|
ListOnly string `json:"listonly"`
|
||||||
|
VisibleInTrash string `json:"visibleintrash"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DoCreateNewFolderResponse is response from foCreateNewFolder
|
||||||
|
type DoCreateNewFolderResponse struct {
|
||||||
|
Status
|
||||||
|
Item Item `json:"file"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DoInitUploadResponse is response from doInitUpload
|
||||||
|
type DoInitUploadResponse struct {
|
||||||
|
Status
|
||||||
|
ProviderID string `json:"providerid"`
|
||||||
|
UploadCode string `json:"uploadcode"`
|
||||||
|
FileType string `json:"filetype"`
|
||||||
|
DirectUploadSupport string `json:"directuploadsupport"`
|
||||||
|
ResumeAllowed string `json:"resumeallowed"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// UploaderResponse is returned from /cgi-bin/uploader/uploader1.cgi
|
||||||
|
//
|
||||||
|
// Sometimes the response is returned as XML and sometimes as JSON
|
||||||
|
type UploaderResponse struct {
|
||||||
|
FileSize int64 `xml:"filesize" json:"filesize,string"`
|
||||||
|
MD5 string `xml:"md5" json:"md5"`
|
||||||
|
Success string `xml:"success" json:"success"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// UploadStatus is returned from getUploadStatus
|
||||||
|
type UploadStatus struct {
|
||||||
|
Status
|
||||||
|
UploadCode string `json:"uploadcode"`
|
||||||
|
Metafile string `json:"metafile"`
|
||||||
|
Percent int `json:"percent,string"`
|
||||||
|
Uploaded int64 `json:"uploaded,string"`
|
||||||
|
Size int64 `json:"size,string"`
|
||||||
|
Filename string `json:"filename"`
|
||||||
|
Nofile string `json:"nofile"`
|
||||||
|
Completed string `json:"completed"`
|
||||||
|
Completsuccess string `json:"completsuccess"`
|
||||||
|
Completerror string `json:"completerror"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DoCompleteUploadResponse is the response to doCompleteUpload
|
||||||
|
type DoCompleteUploadResponse struct {
|
||||||
|
Status
|
||||||
|
UploadedSize int64 `json:"uploadedsize,string"`
|
||||||
|
StorageIP string `json:"storageip"`
|
||||||
|
UploadedName string `json:"uploadedname"`
|
||||||
|
// Versioned []interface{} `json:"versioned"`
|
||||||
|
// VersionedID int `json:"versionedid"`
|
||||||
|
// Comment interface{} `json:"comment"`
|
||||||
|
File Item `json:"file"`
|
||||||
|
// UsSize string `json:"us_size"`
|
||||||
|
// PaSize string `json:"pa_size"`
|
||||||
|
// SpaceInfo SpaceInfo `json:"spaceinfo"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Providers is returned as part of UploadResponse
|
||||||
|
type Providers struct {
|
||||||
|
Max string `json:"max"`
|
||||||
|
Used string `json:"used"`
|
||||||
|
ID string `json:"id"`
|
||||||
|
Private string `json:"private"`
|
||||||
|
Limit string `json:"limit"`
|
||||||
|
Percent int `json:"percent"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Total is returned as part of UploadResponse
|
||||||
|
type Total struct {
|
||||||
|
Max string `json:"max"`
|
||||||
|
Used string `json:"used"`
|
||||||
|
ID string `json:"id"`
|
||||||
|
Priused string `json:"priused"`
|
||||||
|
Primax string `json:"primax"`
|
||||||
|
Limit string `json:"limit"`
|
||||||
|
Percent int `json:"percent"`
|
||||||
|
Pripercent int `json:"pripercent"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// UploadResponse is returned as part of SpaceInfo
|
||||||
|
type UploadResponse struct {
|
||||||
|
Providers []Providers `json:"providers"`
|
||||||
|
Total Total `json:"total"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// SpaceInfo is returned as part of DoCompleteUploadResponse
|
||||||
|
type SpaceInfo struct {
|
||||||
|
Response UploadResponse `json:"response"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteResponse is returned from doDeleteFile
|
||||||
|
type DeleteResponse struct {
|
||||||
|
Status
|
||||||
|
Deleted []string `json:"deleted"`
|
||||||
|
Errors []interface{} `json:"errors"`
|
||||||
|
ID string `json:"fi_id"`
|
||||||
|
BackgroundTask int `json:"backgroundtask"`
|
||||||
|
UsSize string `json:"us_size"`
|
||||||
|
PaSize string `json:"pa_size"`
|
||||||
|
//SpaceInfo SpaceInfo `json:"spaceinfo"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// FileResponse is returned from doRenameFile
|
||||||
|
type FileResponse struct {
|
||||||
|
Status
|
||||||
|
Item Item `json:"file"`
|
||||||
|
Exists string `json:"exists"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// MoveFilesResponse is returned from doMoveFiles
|
||||||
|
type MoveFilesResponse struct {
|
||||||
|
Status
|
||||||
|
Filesleft string `json:"filesleft"`
|
||||||
|
Addedtobackground string `json:"addedtobackground"`
|
||||||
|
Moved string `json:"moved"`
|
||||||
|
Item Item `json:"file"`
|
||||||
|
IDs []string `json:"fi_ids"`
|
||||||
|
Length int `json:"length"`
|
||||||
|
DirID string `json:"dir_id"`
|
||||||
|
MovedObjects []Item `json:"movedobjects"`
|
||||||
|
// FolderTasks []interface{} `json:"foldertasks"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// TasksResponse is the response to getUserBackgroundTasks
|
||||||
|
type TasksResponse struct {
|
||||||
|
Status
|
||||||
|
Tasks []Task `json:"tasks"`
|
||||||
|
Total string `json:"total"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BtData is part of TasksResponse
|
||||||
|
type BtData struct {
|
||||||
|
Callback string `json:"callback"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Task describes a task returned in TasksResponse
|
||||||
|
type Task struct {
|
||||||
|
BtID string `json:"bt_id"`
|
||||||
|
UsID string `json:"us_id"`
|
||||||
|
BtType string `json:"bt_type"`
|
||||||
|
BtData BtData `json:"bt_data"`
|
||||||
|
BtStatustext string `json:"bt_statustext"`
|
||||||
|
BtStatusdata string `json:"bt_statusdata"`
|
||||||
|
BtMessage string `json:"bt_message"`
|
||||||
|
BtProcent string `json:"bt_procent"`
|
||||||
|
BtAdded string `json:"bt_added"`
|
||||||
|
BtStatus string `json:"bt_status"`
|
||||||
|
BtCompleted string `json:"bt_completed"`
|
||||||
|
BtTitle string `json:"bt_title"`
|
||||||
|
BtCredentials string `json:"bt_credentials"`
|
||||||
|
BtHidden string `json:"bt_hidden"`
|
||||||
|
BtAutoremove string `json:"bt_autoremove"`
|
||||||
|
BtDevsite string `json:"bt_devsite"`
|
||||||
|
BtPriority string `json:"bt_priority"`
|
||||||
|
BtReport string `json:"bt_report"`
|
||||||
|
BtSitemarker string `json:"bt_sitemarker"`
|
||||||
|
BtExecuteafter string `json:"bt_executeafter"`
|
||||||
|
BtCompletestatus string `json:"bt_completestatus"`
|
||||||
|
BtSubtype string `json:"bt_subtype"`
|
||||||
|
BtCanceled string `json:"bt_canceled"`
|
||||||
|
Callback string `json:"callback"`
|
||||||
|
CanBeCanceled bool `json:"canbecanceled"`
|
||||||
|
CanBeRestarted bool `json:"canberestarted"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Settings string `json:"settings"`
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,17 @@
|
|||||||
|
// Test filefabric filesystem interface
|
||||||
|
package filefabric_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/rclone/rclone/backend/filefabric"
|
||||||
|
"github.com/rclone/rclone/fstest/fstests"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestIntegration runs integration tests against the remote
|
||||||
|
func TestIntegration(t *testing.T) {
|
||||||
|
fstests.Run(t, &fstests.Opt{
|
||||||
|
RemoteName: "TestFileFabric:",
|
||||||
|
NilObject: (*filefabric.Object)(nil),
|
||||||
|
})
|
||||||
|
}
|
||||||
+221
-117
@@ -6,24 +6,30 @@ import (
|
|||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"io"
|
"io"
|
||||||
"net/textproto"
|
"net/textproto"
|
||||||
"os"
|
|
||||||
"path"
|
"path"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/jlaffaye/ftp"
|
"github.com/jlaffaye/ftp"
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"github.com/rclone/rclone/fs"
|
"github.com/rclone/rclone/fs"
|
||||||
|
"github.com/rclone/rclone/fs/accounting"
|
||||||
|
"github.com/rclone/rclone/fs/config"
|
||||||
"github.com/rclone/rclone/fs/config/configmap"
|
"github.com/rclone/rclone/fs/config/configmap"
|
||||||
"github.com/rclone/rclone/fs/config/configstruct"
|
"github.com/rclone/rclone/fs/config/configstruct"
|
||||||
"github.com/rclone/rclone/fs/config/obscure"
|
"github.com/rclone/rclone/fs/config/obscure"
|
||||||
"github.com/rclone/rclone/fs/encodings"
|
|
||||||
"github.com/rclone/rclone/fs/hash"
|
"github.com/rclone/rclone/fs/hash"
|
||||||
|
"github.com/rclone/rclone/lib/encoder"
|
||||||
|
"github.com/rclone/rclone/lib/env"
|
||||||
"github.com/rclone/rclone/lib/pacer"
|
"github.com/rclone/rclone/lib/pacer"
|
||||||
"github.com/rclone/rclone/lib/readers"
|
"github.com/rclone/rclone/lib/readers"
|
||||||
)
|
)
|
||||||
|
|
||||||
const enc = encodings.FTP
|
var (
|
||||||
|
currentUser = env.CurrentUser()
|
||||||
|
)
|
||||||
|
|
||||||
// Register with Fs
|
// Register with Fs
|
||||||
func init() {
|
func init() {
|
||||||
@@ -31,68 +37,97 @@ func init() {
|
|||||||
Name: "ftp",
|
Name: "ftp",
|
||||||
Description: "FTP Connection",
|
Description: "FTP Connection",
|
||||||
NewFs: NewFs,
|
NewFs: NewFs,
|
||||||
Options: []fs.Option{
|
Options: []fs.Option{{
|
||||||
{
|
Name: "host",
|
||||||
Name: "host",
|
Help: "FTP host to connect to",
|
||||||
Help: "FTP host to connect to",
|
Required: true,
|
||||||
Required: true,
|
Examples: []fs.OptionExample{{
|
||||||
Examples: []fs.OptionExample{{
|
Value: "ftp.example.com",
|
||||||
Value: "ftp.example.com",
|
Help: "Connect to ftp.example.com",
|
||||||
Help: "Connect to ftp.example.com",
|
}},
|
||||||
}},
|
}, {
|
||||||
}, {
|
Name: "user",
|
||||||
Name: "user",
|
Help: "FTP username, leave blank for current username, " + currentUser,
|
||||||
Help: "FTP username, leave blank for current username, " + os.Getenv("USER"),
|
}, {
|
||||||
}, {
|
Name: "port",
|
||||||
Name: "port",
|
Help: "FTP port, leave blank to use default (21)",
|
||||||
Help: "FTP port, leave blank to use default (21)",
|
}, {
|
||||||
}, {
|
Name: "pass",
|
||||||
Name: "pass",
|
Help: "FTP password",
|
||||||
Help: "FTP password",
|
IsPassword: true,
|
||||||
IsPassword: true,
|
Required: true,
|
||||||
Required: true,
|
}, {
|
||||||
}, {
|
Name: "tls",
|
||||||
Name: "tls",
|
Help: `Use Implicit FTPS (FTP over TLS)
|
||||||
Help: "Use FTP over TLS (Implicit)",
|
When using implicit FTP over TLS the client connects using TLS
|
||||||
Default: false,
|
right from the start which breaks compatibility with
|
||||||
}, {
|
non-TLS-aware servers. This is usually served over port 990 rather
|
||||||
Name: "concurrency",
|
than port 21. Cannot be used in combination with explicit FTP.`,
|
||||||
Help: "Maximum number of FTP simultaneous connections, 0 for unlimited",
|
Default: false,
|
||||||
Default: 0,
|
}, {
|
||||||
Advanced: true,
|
Name: "explicit_tls",
|
||||||
}, {
|
Help: `Use Explicit FTPS (FTP over TLS)
|
||||||
Name: "no_check_certificate",
|
When using explicit FTP over TLS the client explicitly requests
|
||||||
Help: "Do not verify the TLS certificate of the server",
|
security from the server in order to upgrade a plain text connection
|
||||||
Default: false,
|
to an encrypted one. Cannot be used in combination with implicit FTP.`,
|
||||||
Advanced: true,
|
Default: false,
|
||||||
}, {
|
}, {
|
||||||
Name: "disable_epsv",
|
Name: "concurrency",
|
||||||
Help: "Disable using EPSV even if server advertises support",
|
Help: "Maximum number of FTP simultaneous connections, 0 for unlimited",
|
||||||
Default: false,
|
Default: 0,
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
},
|
}, {
|
||||||
},
|
Name: "no_check_certificate",
|
||||||
|
Help: "Do not verify the TLS certificate of the server",
|
||||||
|
Default: false,
|
||||||
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: "disable_epsv",
|
||||||
|
Help: "Disable using EPSV even if server advertises support",
|
||||||
|
Default: false,
|
||||||
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: "disable_mlsd",
|
||||||
|
Help: "Disable using MLSD even if server advertises support",
|
||||||
|
Default: false,
|
||||||
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: config.ConfigEncoding,
|
||||||
|
Help: config.ConfigEncodingHelp,
|
||||||
|
Advanced: true,
|
||||||
|
// The FTP protocol can't handle trailing spaces (for instance
|
||||||
|
// pureftpd turns them into _)
|
||||||
|
//
|
||||||
|
// proftpd can't handle '*' in file names
|
||||||
|
// pureftpd can't handle '[', ']' or '*'
|
||||||
|
Default: (encoder.Display |
|
||||||
|
encoder.EncodeRightSpace),
|
||||||
|
}},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Options defines the configuration for this backend
|
// Options defines the configuration for this backend
|
||||||
type Options struct {
|
type Options struct {
|
||||||
Host string `config:"host"`
|
Host string `config:"host"`
|
||||||
User string `config:"user"`
|
User string `config:"user"`
|
||||||
Pass string `config:"pass"`
|
Pass string `config:"pass"`
|
||||||
Port string `config:"port"`
|
Port string `config:"port"`
|
||||||
TLS bool `config:"tls"`
|
TLS bool `config:"tls"`
|
||||||
Concurrency int `config:"concurrency"`
|
ExplicitTLS bool `config:"explicit_tls"`
|
||||||
SkipVerifyTLSCert bool `config:"no_check_certificate"`
|
Concurrency int `config:"concurrency"`
|
||||||
DisableEPSV bool `config:"disable_epsv"`
|
SkipVerifyTLSCert bool `config:"no_check_certificate"`
|
||||||
|
DisableEPSV bool `config:"disable_epsv"`
|
||||||
|
DisableMLSD bool `config:"disable_mlsd"`
|
||||||
|
Enc encoder.MultiEncoder `config:"encoding"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fs represents a remote FTP server
|
// Fs represents a remote FTP server
|
||||||
type Fs struct {
|
type Fs struct {
|
||||||
name string // name of this remote
|
name string // name of this remote
|
||||||
root string // the path we are working on if any
|
root string // the path we are working on if any
|
||||||
opt Options // parsed options
|
opt Options // parsed options
|
||||||
features *fs.Features // optional features
|
ci *fs.ConfigInfo // global config
|
||||||
|
features *fs.Features // optional features
|
||||||
url string
|
url string
|
||||||
user string
|
user string
|
||||||
pass string
|
pass string
|
||||||
@@ -139,20 +174,72 @@ func (f *Fs) Features() *fs.Features {
|
|||||||
return f.features
|
return f.features
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Enable debugging output
|
||||||
|
type debugLog struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
auth bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write writes len(p) bytes from p to the underlying data stream. It returns
|
||||||
|
// the number of bytes written from p (0 <= n <= len(p)) and any error
|
||||||
|
// encountered that caused the write to stop early. Write must return a non-nil
|
||||||
|
// error if it returns n < len(p). Write must not modify the slice data, even
|
||||||
|
// temporarily.
|
||||||
|
//
|
||||||
|
// Implementations must not retain p.
|
||||||
|
//
|
||||||
|
// This writes debug info to the log
|
||||||
|
func (dl *debugLog) Write(p []byte) (n int, err error) {
|
||||||
|
dl.mu.Lock()
|
||||||
|
defer dl.mu.Unlock()
|
||||||
|
_, file, _, ok := runtime.Caller(1)
|
||||||
|
direction := "FTP Rx"
|
||||||
|
if ok && strings.Contains(file, "multi") {
|
||||||
|
direction = "FTP Tx"
|
||||||
|
}
|
||||||
|
lines := strings.Split(string(p), "\r\n")
|
||||||
|
if lines[len(lines)-1] == "" {
|
||||||
|
lines = lines[:len(lines)-1]
|
||||||
|
}
|
||||||
|
for _, line := range lines {
|
||||||
|
if !dl.auth && strings.HasPrefix(line, "PASS") {
|
||||||
|
fs.Debugf(direction, "PASS *****")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
fs.Debugf(direction, "%q", line)
|
||||||
|
}
|
||||||
|
return len(p), nil
|
||||||
|
}
|
||||||
|
|
||||||
// Open a new connection to the FTP server.
|
// Open a new connection to the FTP server.
|
||||||
func (f *Fs) ftpConnection() (*ftp.ServerConn, error) {
|
func (f *Fs) ftpConnection(ctx context.Context) (*ftp.ServerConn, error) {
|
||||||
fs.Debugf(f, "Connecting to FTP server")
|
fs.Debugf(f, "Connecting to FTP server")
|
||||||
ftpConfig := []ftp.DialOption{ftp.DialWithTimeout(fs.Config.ConnectTimeout)}
|
ftpConfig := []ftp.DialOption{ftp.DialWithTimeout(f.ci.ConnectTimeout)}
|
||||||
if f.opt.TLS {
|
if f.opt.TLS && f.opt.ExplicitTLS {
|
||||||
|
fs.Errorf(f, "Implicit TLS and explicit TLS are mutually incompatible. Please revise your config")
|
||||||
|
return nil, errors.New("Implicit TLS and explicit TLS are mutually incompatible. Please revise your config")
|
||||||
|
} else if f.opt.TLS {
|
||||||
tlsConfig := &tls.Config{
|
tlsConfig := &tls.Config{
|
||||||
ServerName: f.opt.Host,
|
ServerName: f.opt.Host,
|
||||||
InsecureSkipVerify: f.opt.SkipVerifyTLSCert,
|
InsecureSkipVerify: f.opt.SkipVerifyTLSCert,
|
||||||
}
|
}
|
||||||
ftpConfig = append(ftpConfig, ftp.DialWithTLS(tlsConfig))
|
ftpConfig = append(ftpConfig, ftp.DialWithTLS(tlsConfig))
|
||||||
|
} else if f.opt.ExplicitTLS {
|
||||||
|
tlsConfig := &tls.Config{
|
||||||
|
ServerName: f.opt.Host,
|
||||||
|
InsecureSkipVerify: f.opt.SkipVerifyTLSCert,
|
||||||
|
}
|
||||||
|
ftpConfig = append(ftpConfig, ftp.DialWithExplicitTLS(tlsConfig))
|
||||||
}
|
}
|
||||||
if f.opt.DisableEPSV {
|
if f.opt.DisableEPSV {
|
||||||
ftpConfig = append(ftpConfig, ftp.DialWithDisabledEPSV(true))
|
ftpConfig = append(ftpConfig, ftp.DialWithDisabledEPSV(true))
|
||||||
}
|
}
|
||||||
|
if f.opt.DisableMLSD {
|
||||||
|
ftpConfig = append(ftpConfig, ftp.DialWithDisabledMLSD(true))
|
||||||
|
}
|
||||||
|
if f.ci.Dump&(fs.DumpHeaders|fs.DumpBodies|fs.DumpRequests|fs.DumpResponses) != 0 {
|
||||||
|
ftpConfig = append(ftpConfig, ftp.DialWithDebugOutput(&debugLog{auth: f.ci.Dump&fs.DumpAuth != 0}))
|
||||||
|
}
|
||||||
c, err := ftp.Dial(f.dialAddr, ftpConfig...)
|
c, err := ftp.Dial(f.dialAddr, ftpConfig...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fs.Errorf(f, "Error while Dialing %s: %s", f.dialAddr, err)
|
fs.Errorf(f, "Error while Dialing %s: %s", f.dialAddr, err)
|
||||||
@@ -168,10 +255,11 @@ func (f *Fs) ftpConnection() (*ftp.ServerConn, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Get an FTP connection from the pool, or open a new one
|
// Get an FTP connection from the pool, or open a new one
|
||||||
func (f *Fs) getFtpConnection() (c *ftp.ServerConn, err error) {
|
func (f *Fs) getFtpConnection(ctx context.Context) (c *ftp.ServerConn, err error) {
|
||||||
if f.opt.Concurrency > 0 {
|
if f.opt.Concurrency > 0 {
|
||||||
f.tokens.Get()
|
f.tokens.Get()
|
||||||
}
|
}
|
||||||
|
accounting.LimitTPS(ctx)
|
||||||
f.poolMu.Lock()
|
f.poolMu.Lock()
|
||||||
if len(f.pool) > 0 {
|
if len(f.pool) > 0 {
|
||||||
c = f.pool[0]
|
c = f.pool[0]
|
||||||
@@ -181,7 +269,11 @@ func (f *Fs) getFtpConnection() (c *ftp.ServerConn, err error) {
|
|||||||
if c != nil {
|
if c != nil {
|
||||||
return c, nil
|
return c, nil
|
||||||
}
|
}
|
||||||
return f.ftpConnection()
|
c, err = f.ftpConnection(ctx)
|
||||||
|
if err != nil && f.opt.Concurrency > 0 {
|
||||||
|
f.tokens.Put()
|
||||||
|
}
|
||||||
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Return an FTP connection to the pool
|
// Return an FTP connection to the pool
|
||||||
@@ -194,7 +286,13 @@ func (f *Fs) putFtpConnection(pc **ftp.ServerConn, err error) {
|
|||||||
if f.opt.Concurrency > 0 {
|
if f.opt.Concurrency > 0 {
|
||||||
defer f.tokens.Put()
|
defer f.tokens.Put()
|
||||||
}
|
}
|
||||||
|
if pc == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
c := *pc
|
c := *pc
|
||||||
|
if c == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
*pc = nil
|
*pc = nil
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// If not a regular FTP error code then check the connection
|
// If not a regular FTP error code then check the connection
|
||||||
@@ -214,8 +312,7 @@ func (f *Fs) putFtpConnection(pc **ftp.ServerConn, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// NewFs constructs an Fs from the path, container:path
|
// NewFs constructs an Fs from the path, container:path
|
||||||
func NewFs(name, root string, m configmap.Mapper) (ff fs.Fs, err error) {
|
func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (ff fs.Fs, err error) {
|
||||||
ctx := context.Background()
|
|
||||||
// defer fs.Trace(nil, "name=%q, root=%q", name, root)("fs=%v, err=%v", &ff, &err)
|
// defer fs.Trace(nil, "name=%q, root=%q", name, root)("fs=%v, err=%v", &ff, &err)
|
||||||
// Parse config into Options struct
|
// Parse config into Options struct
|
||||||
opt := new(Options)
|
opt := new(Options)
|
||||||
@@ -229,7 +326,7 @@ func NewFs(name, root string, m configmap.Mapper) (ff fs.Fs, err error) {
|
|||||||
}
|
}
|
||||||
user := opt.User
|
user := opt.User
|
||||||
if user == "" {
|
if user == "" {
|
||||||
user = os.Getenv("USER")
|
user = currentUser
|
||||||
}
|
}
|
||||||
port := opt.Port
|
port := opt.Port
|
||||||
if port == "" {
|
if port == "" {
|
||||||
@@ -242,10 +339,12 @@ func NewFs(name, root string, m configmap.Mapper) (ff fs.Fs, err error) {
|
|||||||
protocol = "ftps://"
|
protocol = "ftps://"
|
||||||
}
|
}
|
||||||
u := protocol + path.Join(dialAddr+"/", root)
|
u := protocol + path.Join(dialAddr+"/", root)
|
||||||
|
ci := fs.GetConfig(ctx)
|
||||||
f := &Fs{
|
f := &Fs{
|
||||||
name: name,
|
name: name,
|
||||||
root: root,
|
root: root,
|
||||||
opt: *opt,
|
opt: *opt,
|
||||||
|
ci: ci,
|
||||||
url: u,
|
url: u,
|
||||||
user: user,
|
user: user,
|
||||||
pass: pass,
|
pass: pass,
|
||||||
@@ -254,9 +353,9 @@ func NewFs(name, root string, m configmap.Mapper) (ff fs.Fs, err error) {
|
|||||||
}
|
}
|
||||||
f.features = (&fs.Features{
|
f.features = (&fs.Features{
|
||||||
CanHaveEmptyDirectories: true,
|
CanHaveEmptyDirectories: true,
|
||||||
}).Fill(f)
|
}).Fill(ctx, f)
|
||||||
// Make a connection and pool it to return errors early
|
// Make a connection and pool it to return errors early
|
||||||
c, err := f.getFtpConnection()
|
c, err := f.getFtpConnection(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "NewFs")
|
return nil, errors.Wrap(err, "NewFs")
|
||||||
}
|
}
|
||||||
@@ -308,26 +407,26 @@ func translateErrorDir(err error) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// entryToStandard converts an incoming ftp.Entry to Standard encoding
|
// entryToStandard converts an incoming ftp.Entry to Standard encoding
|
||||||
func entryToStandard(entry *ftp.Entry) {
|
func (f *Fs) entryToStandard(entry *ftp.Entry) {
|
||||||
// Skip . and .. as we don't want these encoded
|
// Skip . and .. as we don't want these encoded
|
||||||
if entry.Name == "." || entry.Name == ".." {
|
if entry.Name == "." || entry.Name == ".." {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
entry.Name = enc.ToStandardName(entry.Name)
|
entry.Name = f.opt.Enc.ToStandardName(entry.Name)
|
||||||
entry.Target = enc.ToStandardPath(entry.Target)
|
entry.Target = f.opt.Enc.ToStandardPath(entry.Target)
|
||||||
}
|
}
|
||||||
|
|
||||||
// dirFromStandardPath returns dir in encoded form.
|
// dirFromStandardPath returns dir in encoded form.
|
||||||
func dirFromStandardPath(dir string) string {
|
func (f *Fs) dirFromStandardPath(dir string) string {
|
||||||
// Skip . and .. as we don't want these encoded
|
// Skip . and .. as we don't want these encoded
|
||||||
if dir == "." || dir == ".." {
|
if dir == "." || dir == ".." {
|
||||||
return dir
|
return dir
|
||||||
}
|
}
|
||||||
return enc.FromStandardPath(dir)
|
return f.opt.Enc.FromStandardPath(dir)
|
||||||
}
|
}
|
||||||
|
|
||||||
// findItem finds a directory entry for the name in its parent directory
|
// findItem finds a directory entry for the name in its parent directory
|
||||||
func (f *Fs) findItem(remote string) (entry *ftp.Entry, err error) {
|
func (f *Fs) findItem(ctx context.Context, remote string) (entry *ftp.Entry, err error) {
|
||||||
// defer fs.Trace(remote, "")("o=%v, err=%v", &o, &err)
|
// defer fs.Trace(remote, "")("o=%v, err=%v", &o, &err)
|
||||||
fullPath := path.Join(f.root, remote)
|
fullPath := path.Join(f.root, remote)
|
||||||
if fullPath == "" || fullPath == "." || fullPath == "/" {
|
if fullPath == "" || fullPath == "." || fullPath == "/" {
|
||||||
@@ -341,17 +440,17 @@ func (f *Fs) findItem(remote string) (entry *ftp.Entry, err error) {
|
|||||||
dir := path.Dir(fullPath)
|
dir := path.Dir(fullPath)
|
||||||
base := path.Base(fullPath)
|
base := path.Base(fullPath)
|
||||||
|
|
||||||
c, err := f.getFtpConnection()
|
c, err := f.getFtpConnection(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "findItem")
|
return nil, errors.Wrap(err, "findItem")
|
||||||
}
|
}
|
||||||
files, err := c.List(dirFromStandardPath(dir))
|
files, err := c.List(f.dirFromStandardPath(dir))
|
||||||
f.putFtpConnection(&c, err)
|
f.putFtpConnection(&c, err)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, translateErrorFile(err)
|
return nil, translateErrorFile(err)
|
||||||
}
|
}
|
||||||
for _, file := range files {
|
for _, file := range files {
|
||||||
entryToStandard(file)
|
f.entryToStandard(file)
|
||||||
if file.Name == base {
|
if file.Name == base {
|
||||||
return file, nil
|
return file, nil
|
||||||
}
|
}
|
||||||
@@ -363,7 +462,7 @@ func (f *Fs) findItem(remote string) (entry *ftp.Entry, err error) {
|
|||||||
// it returns the error fs.ErrorObjectNotFound.
|
// it returns the error fs.ErrorObjectNotFound.
|
||||||
func (f *Fs) NewObject(ctx context.Context, remote string) (o fs.Object, err error) {
|
func (f *Fs) NewObject(ctx context.Context, remote string) (o fs.Object, err error) {
|
||||||
// defer fs.Trace(remote, "")("o=%v, err=%v", &o, &err)
|
// defer fs.Trace(remote, "")("o=%v, err=%v", &o, &err)
|
||||||
entry, err := f.findItem(remote)
|
entry, err := f.findItem(ctx, remote)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -385,8 +484,8 @@ func (f *Fs) NewObject(ctx context.Context, remote string) (o fs.Object, err err
|
|||||||
}
|
}
|
||||||
|
|
||||||
// dirExists checks the directory pointed to by remote exists or not
|
// dirExists checks the directory pointed to by remote exists or not
|
||||||
func (f *Fs) dirExists(remote string) (exists bool, err error) {
|
func (f *Fs) dirExists(ctx context.Context, remote string) (exists bool, err error) {
|
||||||
entry, err := f.findItem(remote)
|
entry, err := f.findItem(ctx, remote)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, errors.Wrap(err, "dirExists")
|
return false, errors.Wrap(err, "dirExists")
|
||||||
}
|
}
|
||||||
@@ -407,7 +506,7 @@ func (f *Fs) dirExists(remote string) (exists bool, err error) {
|
|||||||
// found.
|
// found.
|
||||||
func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) {
|
func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) {
|
||||||
// defer log.Trace(dir, "dir=%q", dir)("entries=%v, err=%v", &entries, &err)
|
// defer log.Trace(dir, "dir=%q", dir)("entries=%v, err=%v", &entries, &err)
|
||||||
c, err := f.getFtpConnection()
|
c, err := f.getFtpConnection(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "list")
|
return nil, errors.Wrap(err, "list")
|
||||||
}
|
}
|
||||||
@@ -418,7 +517,7 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
|
|||||||
resultchan := make(chan []*ftp.Entry, 1)
|
resultchan := make(chan []*ftp.Entry, 1)
|
||||||
errchan := make(chan error, 1)
|
errchan := make(chan error, 1)
|
||||||
go func() {
|
go func() {
|
||||||
result, err := c.List(dirFromStandardPath(path.Join(f.root, dir)))
|
result, err := c.List(f.dirFromStandardPath(path.Join(f.root, dir)))
|
||||||
f.putFtpConnection(&c, err)
|
f.putFtpConnection(&c, err)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
errchan <- err
|
errchan <- err
|
||||||
@@ -428,7 +527,7 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
|
|||||||
}()
|
}()
|
||||||
|
|
||||||
// Wait for List for up to Timeout seconds
|
// Wait for List for up to Timeout seconds
|
||||||
timer := time.NewTimer(fs.Config.Timeout)
|
timer := time.NewTimer(f.ci.Timeout)
|
||||||
select {
|
select {
|
||||||
case listErr = <-errchan:
|
case listErr = <-errchan:
|
||||||
timer.Stop()
|
timer.Stop()
|
||||||
@@ -445,7 +544,7 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
|
|||||||
// doesn't exist, so check it really doesn't exist if no
|
// doesn't exist, so check it really doesn't exist if no
|
||||||
// entries found.
|
// entries found.
|
||||||
if len(files) == 0 {
|
if len(files) == 0 {
|
||||||
exists, err := f.dirExists(dir)
|
exists, err := f.dirExists(ctx, dir)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "list")
|
return nil, errors.Wrap(err, "list")
|
||||||
}
|
}
|
||||||
@@ -455,7 +554,7 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
|
|||||||
}
|
}
|
||||||
for i := range files {
|
for i := range files {
|
||||||
object := files[i]
|
object := files[i]
|
||||||
entryToStandard(object)
|
f.entryToStandard(object)
|
||||||
newremote := path.Join(dir, object.Name)
|
newremote := path.Join(dir, object.Name)
|
||||||
switch object.Type {
|
switch object.Type {
|
||||||
case ftp.EntryTypeFolder:
|
case ftp.EntryTypeFolder:
|
||||||
@@ -498,7 +597,7 @@ func (f *Fs) Precision() time.Duration {
|
|||||||
// nil and the error
|
// nil and the error
|
||||||
func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
|
func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
|
||||||
// fs.Debugf(f, "Trying to put file %s", src.Remote())
|
// fs.Debugf(f, "Trying to put file %s", src.Remote())
|
||||||
err := f.mkParentDir(src.Remote())
|
err := f.mkParentDir(ctx, src.Remote())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "Put mkParentDir failed")
|
return nil, errors.Wrap(err, "Put mkParentDir failed")
|
||||||
}
|
}
|
||||||
@@ -516,16 +615,16 @@ func (f *Fs) PutStream(ctx context.Context, in io.Reader, src fs.ObjectInfo, opt
|
|||||||
}
|
}
|
||||||
|
|
||||||
// getInfo reads the FileInfo for a path
|
// getInfo reads the FileInfo for a path
|
||||||
func (f *Fs) getInfo(remote string) (fi *FileInfo, err error) {
|
func (f *Fs) getInfo(ctx context.Context, remote string) (fi *FileInfo, err error) {
|
||||||
// defer fs.Trace(remote, "")("fi=%v, err=%v", &fi, &err)
|
// defer fs.Trace(remote, "")("fi=%v, err=%v", &fi, &err)
|
||||||
dir := path.Dir(remote)
|
dir := path.Dir(remote)
|
||||||
base := path.Base(remote)
|
base := path.Base(remote)
|
||||||
|
|
||||||
c, err := f.getFtpConnection()
|
c, err := f.getFtpConnection(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "getInfo")
|
return nil, errors.Wrap(err, "getInfo")
|
||||||
}
|
}
|
||||||
files, err := c.List(dirFromStandardPath(dir))
|
files, err := c.List(f.dirFromStandardPath(dir))
|
||||||
f.putFtpConnection(&c, err)
|
f.putFtpConnection(&c, err)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, translateErrorFile(err)
|
return nil, translateErrorFile(err)
|
||||||
@@ -533,7 +632,7 @@ func (f *Fs) getInfo(remote string) (fi *FileInfo, err error) {
|
|||||||
|
|
||||||
for i := range files {
|
for i := range files {
|
||||||
file := files[i]
|
file := files[i]
|
||||||
entryToStandard(file)
|
f.entryToStandard(file)
|
||||||
if file.Name == base {
|
if file.Name == base {
|
||||||
info := &FileInfo{
|
info := &FileInfo{
|
||||||
Name: remote,
|
Name: remote,
|
||||||
@@ -548,12 +647,12 @@ func (f *Fs) getInfo(remote string) (fi *FileInfo, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// mkdir makes the directory and parents using unrooted paths
|
// mkdir makes the directory and parents using unrooted paths
|
||||||
func (f *Fs) mkdir(abspath string) error {
|
func (f *Fs) mkdir(ctx context.Context, abspath string) error {
|
||||||
abspath = path.Clean(abspath)
|
abspath = path.Clean(abspath)
|
||||||
if abspath == "." || abspath == "/" {
|
if abspath == "." || abspath == "/" {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
fi, err := f.getInfo(abspath)
|
fi, err := f.getInfo(ctx, abspath)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
if fi.IsDir {
|
if fi.IsDir {
|
||||||
return nil
|
return nil
|
||||||
@@ -563,15 +662,15 @@ func (f *Fs) mkdir(abspath string) error {
|
|||||||
return errors.Wrapf(err, "mkdir %q failed", abspath)
|
return errors.Wrapf(err, "mkdir %q failed", abspath)
|
||||||
}
|
}
|
||||||
parent := path.Dir(abspath)
|
parent := path.Dir(abspath)
|
||||||
err = f.mkdir(parent)
|
err = f.mkdir(ctx, parent)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
c, connErr := f.getFtpConnection()
|
c, connErr := f.getFtpConnection(ctx)
|
||||||
if connErr != nil {
|
if connErr != nil {
|
||||||
return errors.Wrap(connErr, "mkdir")
|
return errors.Wrap(connErr, "mkdir")
|
||||||
}
|
}
|
||||||
err = c.MakeDir(dirFromStandardPath(abspath))
|
err = c.MakeDir(f.dirFromStandardPath(abspath))
|
||||||
f.putFtpConnection(&c, err)
|
f.putFtpConnection(&c, err)
|
||||||
switch errX := err.(type) {
|
switch errX := err.(type) {
|
||||||
case *textproto.Error:
|
case *textproto.Error:
|
||||||
@@ -587,27 +686,27 @@ func (f *Fs) mkdir(abspath string) error {
|
|||||||
|
|
||||||
// mkParentDir makes the parent of remote if necessary and any
|
// mkParentDir makes the parent of remote if necessary and any
|
||||||
// directories above that
|
// directories above that
|
||||||
func (f *Fs) mkParentDir(remote string) error {
|
func (f *Fs) mkParentDir(ctx context.Context, remote string) error {
|
||||||
parent := path.Dir(remote)
|
parent := path.Dir(remote)
|
||||||
return f.mkdir(path.Join(f.root, parent))
|
return f.mkdir(ctx, path.Join(f.root, parent))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mkdir creates the directory if it doesn't exist
|
// Mkdir creates the directory if it doesn't exist
|
||||||
func (f *Fs) Mkdir(ctx context.Context, dir string) (err error) {
|
func (f *Fs) Mkdir(ctx context.Context, dir string) (err error) {
|
||||||
// defer fs.Trace(dir, "")("err=%v", &err)
|
// defer fs.Trace(dir, "")("err=%v", &err)
|
||||||
root := path.Join(f.root, dir)
|
root := path.Join(f.root, dir)
|
||||||
return f.mkdir(root)
|
return f.mkdir(ctx, root)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Rmdir removes the directory (container, bucket) if empty
|
// Rmdir removes the directory (container, bucket) if empty
|
||||||
//
|
//
|
||||||
// Return an error if it doesn't exist or isn't empty
|
// Return an error if it doesn't exist or isn't empty
|
||||||
func (f *Fs) Rmdir(ctx context.Context, dir string) error {
|
func (f *Fs) Rmdir(ctx context.Context, dir string) error {
|
||||||
c, err := f.getFtpConnection()
|
c, err := f.getFtpConnection(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.Wrap(translateErrorFile(err), "Rmdir")
|
return errors.Wrap(translateErrorFile(err), "Rmdir")
|
||||||
}
|
}
|
||||||
err = c.RemoveDir(dirFromStandardPath(path.Join(f.root, dir)))
|
err = c.RemoveDir(f.dirFromStandardPath(path.Join(f.root, dir)))
|
||||||
f.putFtpConnection(&c, err)
|
f.putFtpConnection(&c, err)
|
||||||
return translateErrorDir(err)
|
return translateErrorDir(err)
|
||||||
}
|
}
|
||||||
@@ -619,17 +718,17 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
fs.Debugf(src, "Can't move - not same remote type")
|
fs.Debugf(src, "Can't move - not same remote type")
|
||||||
return nil, fs.ErrorCantMove
|
return nil, fs.ErrorCantMove
|
||||||
}
|
}
|
||||||
err := f.mkParentDir(remote)
|
err := f.mkParentDir(ctx, remote)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "Move mkParentDir failed")
|
return nil, errors.Wrap(err, "Move mkParentDir failed")
|
||||||
}
|
}
|
||||||
c, err := f.getFtpConnection()
|
c, err := f.getFtpConnection(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "Move")
|
return nil, errors.Wrap(err, "Move")
|
||||||
}
|
}
|
||||||
err = c.Rename(
|
err = c.Rename(
|
||||||
enc.FromStandardPath(path.Join(srcObj.fs.root, srcObj.remote)),
|
f.opt.Enc.FromStandardPath(path.Join(srcObj.fs.root, srcObj.remote)),
|
||||||
enc.FromStandardPath(path.Join(f.root, remote)),
|
f.opt.Enc.FromStandardPath(path.Join(f.root, remote)),
|
||||||
)
|
)
|
||||||
f.putFtpConnection(&c, err)
|
f.putFtpConnection(&c, err)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -643,7 +742,7 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DirMove moves src, srcRemote to this remote at dstRemote
|
// DirMove moves src, srcRemote to this remote at dstRemote
|
||||||
// using server side move operations.
|
// using server-side move operations.
|
||||||
//
|
//
|
||||||
// Will only be called if src.Fs().Name() == f.Name()
|
// Will only be called if src.Fs().Name() == f.Name()
|
||||||
//
|
//
|
||||||
@@ -660,7 +759,7 @@ func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string
|
|||||||
dstPath := path.Join(f.root, dstRemote)
|
dstPath := path.Join(f.root, dstRemote)
|
||||||
|
|
||||||
// Check if destination exists
|
// Check if destination exists
|
||||||
fi, err := f.getInfo(dstPath)
|
fi, err := f.getInfo(ctx, dstPath)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
if fi.IsDir {
|
if fi.IsDir {
|
||||||
return fs.ErrorDirExists
|
return fs.ErrorDirExists
|
||||||
@@ -671,19 +770,19 @@ func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Make sure the parent directory exists
|
// Make sure the parent directory exists
|
||||||
err = f.mkdir(path.Dir(dstPath))
|
err = f.mkdir(ctx, path.Dir(dstPath))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.Wrap(err, "DirMove mkParentDir dst failed")
|
return errors.Wrap(err, "DirMove mkParentDir dst failed")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Do the move
|
// Do the move
|
||||||
c, err := f.getFtpConnection()
|
c, err := f.getFtpConnection(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.Wrap(err, "DirMove")
|
return errors.Wrap(err, "DirMove")
|
||||||
}
|
}
|
||||||
err = c.Rename(
|
err = c.Rename(
|
||||||
dirFromStandardPath(srcPath),
|
f.dirFromStandardPath(srcPath),
|
||||||
dirFromStandardPath(dstPath),
|
f.dirFromStandardPath(dstPath),
|
||||||
)
|
)
|
||||||
f.putFtpConnection(&c, err)
|
f.putFtpConnection(&c, err)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -769,19 +868,23 @@ func (f *ftpReadCloser) Close() error {
|
|||||||
case <-timer.C:
|
case <-timer.C:
|
||||||
// if timer fired assume no error but connection dead
|
// if timer fired assume no error but connection dead
|
||||||
fs.Errorf(f.f, "Timeout when waiting for connection Close")
|
fs.Errorf(f.f, "Timeout when waiting for connection Close")
|
||||||
|
f.f.putFtpConnection(nil, nil)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
// if errors while reading or closing, dump the connection
|
// if errors while reading or closing, dump the connection
|
||||||
if err != nil || f.err != nil {
|
if err != nil || f.err != nil {
|
||||||
_ = f.c.Quit()
|
_ = f.c.Quit()
|
||||||
|
f.f.putFtpConnection(nil, nil)
|
||||||
} else {
|
} else {
|
||||||
f.f.putFtpConnection(&f.c, nil)
|
f.f.putFtpConnection(&f.c, nil)
|
||||||
}
|
}
|
||||||
// mask the error if it was caused by a premature close
|
// mask the error if it was caused by a premature close
|
||||||
|
// NB StatusAboutToSend is to work around a bug in pureftpd
|
||||||
|
// See: https://github.com/rclone/rclone/issues/3445#issuecomment-521654257
|
||||||
switch errX := err.(type) {
|
switch errX := err.(type) {
|
||||||
case *textproto.Error:
|
case *textproto.Error:
|
||||||
switch errX.Code {
|
switch errX.Code {
|
||||||
case ftp.StatusTransfertAborted, ftp.StatusFileUnavailable:
|
case ftp.StatusTransfertAborted, ftp.StatusFileUnavailable, ftp.StatusAboutToSend:
|
||||||
err = nil
|
err = nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -805,11 +908,11 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (rc io.Read
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
c, err := o.fs.getFtpConnection()
|
c, err := o.fs.getFtpConnection(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "open")
|
return nil, errors.Wrap(err, "open")
|
||||||
}
|
}
|
||||||
fd, err := c.RetrFrom(enc.FromStandardPath(path), uint64(offset))
|
fd, err := c.RetrFrom(o.fs.opt.Enc.FromStandardPath(path), uint64(offset))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
o.fs.putFtpConnection(&c, err)
|
o.fs.putFtpConnection(&c, err)
|
||||||
return nil, errors.Wrap(err, "open")
|
return nil, errors.Wrap(err, "open")
|
||||||
@@ -840,18 +943,19 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
fs.Debugf(o, "Removed after failed upload: %v", err)
|
fs.Debugf(o, "Removed after failed upload: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
c, err := o.fs.getFtpConnection()
|
c, err := o.fs.getFtpConnection(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.Wrap(err, "Update")
|
return errors.Wrap(err, "Update")
|
||||||
}
|
}
|
||||||
err = c.Stor(enc.FromStandardPath(path), in)
|
err = c.Stor(o.fs.opt.Enc.FromStandardPath(path), in)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = c.Quit() // toss this connection to avoid sync errors
|
_ = c.Quit() // toss this connection to avoid sync errors
|
||||||
remove()
|
remove()
|
||||||
|
o.fs.putFtpConnection(nil, err)
|
||||||
return errors.Wrap(err, "update stor")
|
return errors.Wrap(err, "update stor")
|
||||||
}
|
}
|
||||||
o.fs.putFtpConnection(&c, nil)
|
o.fs.putFtpConnection(&c, nil)
|
||||||
o.info, err = o.fs.getInfo(path)
|
o.info, err = o.fs.getInfo(ctx, path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.Wrap(err, "update getinfo")
|
return errors.Wrap(err, "update getinfo")
|
||||||
}
|
}
|
||||||
@@ -863,18 +967,18 @@ func (o *Object) Remove(ctx context.Context) (err error) {
|
|||||||
// defer fs.Trace(o, "")("err=%v", &err)
|
// defer fs.Trace(o, "")("err=%v", &err)
|
||||||
path := path.Join(o.fs.root, o.remote)
|
path := path.Join(o.fs.root, o.remote)
|
||||||
// Check if it's a directory or a file
|
// Check if it's a directory or a file
|
||||||
info, err := o.fs.getInfo(path)
|
info, err := o.fs.getInfo(ctx, path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if info.IsDir {
|
if info.IsDir {
|
||||||
err = o.fs.Rmdir(ctx, o.remote)
|
err = o.fs.Rmdir(ctx, o.remote)
|
||||||
} else {
|
} else {
|
||||||
c, err := o.fs.getFtpConnection()
|
c, err := o.fs.getFtpConnection(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.Wrap(err, "Remove")
|
return errors.Wrap(err, "Remove")
|
||||||
}
|
}
|
||||||
err = c.Delete(enc.FromStandardPath(path))
|
err = c.Delete(o.fs.opt.Enc.FromStandardPath(path))
|
||||||
o.fs.putFtpConnection(&c, err)
|
o.fs.putFtpConnection(&c, err)
|
||||||
}
|
}
|
||||||
return err
|
return err
|
||||||
|
|||||||
+32
-1
@@ -5,13 +5,44 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/rclone/rclone/backend/ftp"
|
"github.com/rclone/rclone/backend/ftp"
|
||||||
|
"github.com/rclone/rclone/fstest"
|
||||||
"github.com/rclone/rclone/fstest/fstests"
|
"github.com/rclone/rclone/fstest/fstests"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TestIntegration runs integration tests against the remote
|
// TestIntegration runs integration tests against the remote
|
||||||
func TestIntegration(t *testing.T) {
|
func TestIntegration(t *testing.T) {
|
||||||
fstests.Run(t, &fstests.Opt{
|
fstests.Run(t, &fstests.Opt{
|
||||||
RemoteName: "TestFTP:",
|
RemoteName: "TestFTPProftpd:",
|
||||||
NilObject: (*ftp.Object)(nil),
|
NilObject: (*ftp.Object)(nil),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestIntegration2(t *testing.T) {
|
||||||
|
if *fstest.RemoteName != "" {
|
||||||
|
t.Skip("skipping as -remote is set")
|
||||||
|
}
|
||||||
|
fstests.Run(t, &fstests.Opt{
|
||||||
|
RemoteName: "TestFTPRclone:",
|
||||||
|
NilObject: (*ftp.Object)(nil),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIntegration3(t *testing.T) {
|
||||||
|
if *fstest.RemoteName != "" {
|
||||||
|
t.Skip("skipping as -remote is set")
|
||||||
|
}
|
||||||
|
fstests.Run(t, &fstests.Opt{
|
||||||
|
RemoteName: "TestFTPPureftpd:",
|
||||||
|
NilObject: (*ftp.Object)(nil),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// func TestIntegration4(t *testing.T) {
|
||||||
|
// if *fstest.RemoteName != "" {
|
||||||
|
// t.Skip("skipping as -remote is set")
|
||||||
|
// }
|
||||||
|
// fstests.Run(t, &fstests.Opt{
|
||||||
|
// RemoteName: "TestFTPVsftpd:",
|
||||||
|
// NilObject: (*ftp.Object)(nil),
|
||||||
|
// })
|
||||||
|
// }
|
||||||
@@ -21,7 +21,6 @@ import (
|
|||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
|
||||||
"path"
|
"path"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -32,12 +31,13 @@ import (
|
|||||||
"github.com/rclone/rclone/fs/config/configmap"
|
"github.com/rclone/rclone/fs/config/configmap"
|
||||||
"github.com/rclone/rclone/fs/config/configstruct"
|
"github.com/rclone/rclone/fs/config/configstruct"
|
||||||
"github.com/rclone/rclone/fs/config/obscure"
|
"github.com/rclone/rclone/fs/config/obscure"
|
||||||
"github.com/rclone/rclone/fs/encodings"
|
|
||||||
"github.com/rclone/rclone/fs/fserrors"
|
"github.com/rclone/rclone/fs/fserrors"
|
||||||
"github.com/rclone/rclone/fs/fshttp"
|
"github.com/rclone/rclone/fs/fshttp"
|
||||||
"github.com/rclone/rclone/fs/hash"
|
"github.com/rclone/rclone/fs/hash"
|
||||||
"github.com/rclone/rclone/fs/walk"
|
"github.com/rclone/rclone/fs/walk"
|
||||||
"github.com/rclone/rclone/lib/bucket"
|
"github.com/rclone/rclone/lib/bucket"
|
||||||
|
"github.com/rclone/rclone/lib/encoder"
|
||||||
|
"github.com/rclone/rclone/lib/env"
|
||||||
"github.com/rclone/rclone/lib/oauthutil"
|
"github.com/rclone/rclone/lib/oauthutil"
|
||||||
"github.com/rclone/rclone/lib/pacer"
|
"github.com/rclone/rclone/lib/pacer"
|
||||||
"golang.org/x/oauth2"
|
"golang.org/x/oauth2"
|
||||||
@@ -69,8 +69,6 @@ var (
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
const enc = encodings.GoogleCloudStorage
|
|
||||||
|
|
||||||
// Register with Fs
|
// Register with Fs
|
||||||
func init() {
|
func init() {
|
||||||
fs.Register(&fs.RegInfo{
|
fs.Register(&fs.RegInfo{
|
||||||
@@ -78,33 +76,32 @@ func init() {
|
|||||||
Prefix: "gcs",
|
Prefix: "gcs",
|
||||||
Description: "Google Cloud Storage (this is not Google Drive)",
|
Description: "Google Cloud Storage (this is not Google Drive)",
|
||||||
NewFs: NewFs,
|
NewFs: NewFs,
|
||||||
Config: func(name string, m configmap.Mapper) {
|
Config: func(ctx context.Context, name string, m configmap.Mapper) {
|
||||||
saFile, _ := m.Get("service_account_file")
|
saFile, _ := m.Get("service_account_file")
|
||||||
saCreds, _ := m.Get("service_account_credentials")
|
saCreds, _ := m.Get("service_account_credentials")
|
||||||
if saFile != "" || saCreds != "" {
|
anonymous, _ := m.Get("anonymous")
|
||||||
|
if saFile != "" || saCreds != "" || anonymous == "true" {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
err := oauthutil.Config("google cloud storage", name, m, storageConfig)
|
err := oauthutil.Config(ctx, "google cloud storage", name, m, storageConfig, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Failed to configure token: %v", err)
|
log.Fatalf("Failed to configure token: %v", err)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
Options: []fs.Option{{
|
Options: append(oauthutil.SharedOptions, []fs.Option{{
|
||||||
Name: config.ConfigClientID,
|
|
||||||
Help: "Google Application Client Id\nLeave blank normally.",
|
|
||||||
}, {
|
|
||||||
Name: config.ConfigClientSecret,
|
|
||||||
Help: "Google Application Client Secret\nLeave blank normally.",
|
|
||||||
}, {
|
|
||||||
Name: "project_number",
|
Name: "project_number",
|
||||||
Help: "Project number.\nOptional - needed only for list/create/delete buckets - see your developer console.",
|
Help: "Project number.\nOptional - needed only for list/create/delete buckets - see your developer console.",
|
||||||
}, {
|
}, {
|
||||||
Name: "service_account_file",
|
Name: "service_account_file",
|
||||||
Help: "Service Account Credentials JSON file path\nLeave blank normally.\nNeeded only if you want use SA instead of interactive login.",
|
Help: "Service Account Credentials JSON file path\nLeave blank normally.\nNeeded only if you want use SA instead of interactive login." + env.ShellExpandHelp,
|
||||||
}, {
|
}, {
|
||||||
Name: "service_account_credentials",
|
Name: "service_account_credentials",
|
||||||
Help: "Service Account Credentials JSON blob\nLeave blank normally.\nNeeded only if you want use SA instead of interactive login.",
|
Help: "Service Account Credentials JSON blob\nLeave blank normally.\nNeeded only if you want use SA instead of interactive login.",
|
||||||
Hide: fs.OptionHideBoth,
|
Hide: fs.OptionHideBoth,
|
||||||
|
}, {
|
||||||
|
Name: "anonymous",
|
||||||
|
Help: "Access public buckets and objects without credentials\nSet to 'true' if you just want to download files and don't configure credentials.",
|
||||||
|
Default: false,
|
||||||
}, {
|
}, {
|
||||||
Name: "object_acl",
|
Name: "object_acl",
|
||||||
Help: "Access Control List for new objects.",
|
Help: "Access Control List for new objects.",
|
||||||
@@ -244,24 +241,36 @@ Docs: https://cloud.google.com/storage/docs/bucket-policy-only
|
|||||||
}, {
|
}, {
|
||||||
Value: "COLDLINE",
|
Value: "COLDLINE",
|
||||||
Help: "Coldline storage class",
|
Help: "Coldline storage class",
|
||||||
|
}, {
|
||||||
|
Value: "ARCHIVE",
|
||||||
|
Help: "Archive storage class",
|
||||||
}, {
|
}, {
|
||||||
Value: "DURABLE_REDUCED_AVAILABILITY",
|
Value: "DURABLE_REDUCED_AVAILABILITY",
|
||||||
Help: "Durable reduced availability storage class",
|
Help: "Durable reduced availability storage class",
|
||||||
}},
|
}},
|
||||||
}},
|
}, {
|
||||||
|
Name: config.ConfigEncoding,
|
||||||
|
Help: config.ConfigEncodingHelp,
|
||||||
|
Advanced: true,
|
||||||
|
Default: (encoder.Base |
|
||||||
|
encoder.EncodeCrLf |
|
||||||
|
encoder.EncodeInvalidUtf8),
|
||||||
|
}}...),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Options defines the configuration for this backend
|
// Options defines the configuration for this backend
|
||||||
type Options struct {
|
type Options struct {
|
||||||
ProjectNumber string `config:"project_number"`
|
ProjectNumber string `config:"project_number"`
|
||||||
ServiceAccountFile string `config:"service_account_file"`
|
ServiceAccountFile string `config:"service_account_file"`
|
||||||
ServiceAccountCredentials string `config:"service_account_credentials"`
|
ServiceAccountCredentials string `config:"service_account_credentials"`
|
||||||
ObjectACL string `config:"object_acl"`
|
Anonymous bool `config:"anonymous"`
|
||||||
BucketACL string `config:"bucket_acl"`
|
ObjectACL string `config:"object_acl"`
|
||||||
BucketPolicyOnly bool `config:"bucket_policy_only"`
|
BucketACL string `config:"bucket_acl"`
|
||||||
Location string `config:"location"`
|
BucketPolicyOnly bool `config:"bucket_policy_only"`
|
||||||
StorageClass string `config:"storage_class"`
|
Location string `config:"location"`
|
||||||
|
StorageClass string `config:"storage_class"`
|
||||||
|
Enc encoder.MultiEncoder `config:"encoding"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fs represents a remote storage server
|
// Fs represents a remote storage server
|
||||||
@@ -353,7 +362,7 @@ func parsePath(path string) (root string) {
|
|||||||
// relative to f.root
|
// relative to f.root
|
||||||
func (f *Fs) split(rootRelativePath string) (bucketName, bucketPath string) {
|
func (f *Fs) split(rootRelativePath string) (bucketName, bucketPath string) {
|
||||||
bucketName, bucketPath = bucket.Split(path.Join(f.root, rootRelativePath))
|
bucketName, bucketPath = bucket.Split(path.Join(f.root, rootRelativePath))
|
||||||
return enc.FromStandardName(bucketName), enc.FromStandardPath(bucketPath)
|
return f.opt.Enc.FromStandardName(bucketName), f.opt.Enc.FromStandardPath(bucketPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
// split returns bucket and bucketPath from the object
|
// split returns bucket and bucketPath from the object
|
||||||
@@ -361,12 +370,12 @@ func (o *Object) split() (bucket, bucketPath string) {
|
|||||||
return o.fs.split(o.remote)
|
return o.fs.split(o.remote)
|
||||||
}
|
}
|
||||||
|
|
||||||
func getServiceAccountClient(credentialsData []byte) (*http.Client, error) {
|
func getServiceAccountClient(ctx context.Context, credentialsData []byte) (*http.Client, error) {
|
||||||
conf, err := google.JWTConfigFromJSON(credentialsData, storageConfig.Scopes...)
|
conf, err := google.JWTConfigFromJSON(credentialsData, storageConfig.Scopes...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "error processing credentials")
|
return nil, errors.Wrap(err, "error processing credentials")
|
||||||
}
|
}
|
||||||
ctxWithSpecialClient := oauthutil.Context(fshttp.NewClient(fs.Config))
|
ctxWithSpecialClient := oauthutil.Context(ctx, fshttp.NewClient(ctx))
|
||||||
return oauth2.NewClient(ctxWithSpecialClient, conf.TokenSource(ctxWithSpecialClient)), nil
|
return oauth2.NewClient(ctxWithSpecialClient, conf.TokenSource(ctxWithSpecialClient)), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -377,8 +386,7 @@ func (f *Fs) setRoot(root string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// NewFs constructs an Fs from the path, bucket:path
|
// NewFs constructs an Fs from the path, bucket:path
|
||||||
func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {
|
||||||
ctx := context.TODO()
|
|
||||||
var oAuthClient *http.Client
|
var oAuthClient *http.Client
|
||||||
|
|
||||||
// Parse config into Options struct
|
// Parse config into Options struct
|
||||||
@@ -396,19 +404,21 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
|
|
||||||
// try loading service account credentials from env variable, then from a file
|
// try loading service account credentials from env variable, then from a file
|
||||||
if opt.ServiceAccountCredentials == "" && opt.ServiceAccountFile != "" {
|
if opt.ServiceAccountCredentials == "" && opt.ServiceAccountFile != "" {
|
||||||
loadedCreds, err := ioutil.ReadFile(os.ExpandEnv(opt.ServiceAccountFile))
|
loadedCreds, err := ioutil.ReadFile(env.ShellExpand(opt.ServiceAccountFile))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "error opening service account credentials file")
|
return nil, errors.Wrap(err, "error opening service account credentials file")
|
||||||
}
|
}
|
||||||
opt.ServiceAccountCredentials = string(loadedCreds)
|
opt.ServiceAccountCredentials = string(loadedCreds)
|
||||||
}
|
}
|
||||||
if opt.ServiceAccountCredentials != "" {
|
if opt.Anonymous {
|
||||||
oAuthClient, err = getServiceAccountClient([]byte(opt.ServiceAccountCredentials))
|
oAuthClient = fshttp.NewClient(ctx)
|
||||||
|
} else if opt.ServiceAccountCredentials != "" {
|
||||||
|
oAuthClient, err = getServiceAccountClient(ctx, []byte(opt.ServiceAccountCredentials))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "failed configuring Google Cloud Storage Service Account")
|
return nil, errors.Wrap(err, "failed configuring Google Cloud Storage Service Account")
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
oAuthClient, _, err = oauthutil.NewClient(name, m, storageConfig)
|
oAuthClient, _, err = oauthutil.NewClient(ctx, name, m, storageConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
oAuthClient, err = google.DefaultClient(ctx, storage.DevstorageFullControlScope)
|
oAuthClient, err = google.DefaultClient(ctx, storage.DevstorageFullControlScope)
|
||||||
@@ -422,7 +432,7 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
name: name,
|
name: name,
|
||||||
root: root,
|
root: root,
|
||||||
opt: *opt,
|
opt: *opt,
|
||||||
pacer: fs.NewPacer(pacer.NewGoogleDrive(pacer.MinSleep(minSleep))),
|
pacer: fs.NewPacer(ctx, pacer.NewGoogleDrive(pacer.MinSleep(minSleep))),
|
||||||
cache: bucket.NewCache(),
|
cache: bucket.NewCache(),
|
||||||
}
|
}
|
||||||
f.setRoot(root)
|
f.setRoot(root)
|
||||||
@@ -431,7 +441,7 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
WriteMimeType: true,
|
WriteMimeType: true,
|
||||||
BucketBased: true,
|
BucketBased: true,
|
||||||
BucketBasedRootOK: true,
|
BucketBasedRootOK: true,
|
||||||
}).Fill(f)
|
}).Fill(ctx, f)
|
||||||
|
|
||||||
// Create a new authorized Drive client.
|
// Create a new authorized Drive client.
|
||||||
f.client = oAuthClient
|
f.client = oAuthClient
|
||||||
@@ -442,7 +452,7 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
|
|
||||||
if f.rootBucket != "" && f.rootDirectory != "" {
|
if f.rootBucket != "" && f.rootDirectory != "" {
|
||||||
// Check to see if the object exists
|
// Check to see if the object exists
|
||||||
encodedDirectory := enc.FromStandardPath(f.rootDirectory)
|
encodedDirectory := f.opt.Enc.FromStandardPath(f.rootDirectory)
|
||||||
err = f.pacer.Call(func() (bool, error) {
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
_, err = f.svc.Objects.Get(f.rootBucket, encodedDirectory).Context(ctx).Do()
|
_, err = f.svc.Objects.Get(f.rootBucket, encodedDirectory).Context(ctx).Do()
|
||||||
return shouldRetry(err)
|
return shouldRetry(err)
|
||||||
@@ -527,7 +537,7 @@ func (f *Fs) list(ctx context.Context, bucket, directory, prefix string, addBuck
|
|||||||
if !strings.HasSuffix(remote, "/") {
|
if !strings.HasSuffix(remote, "/") {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
remote = enc.ToStandardPath(remote)
|
remote = f.opt.Enc.ToStandardPath(remote)
|
||||||
if !strings.HasPrefix(remote, prefix) {
|
if !strings.HasPrefix(remote, prefix) {
|
||||||
fs.Logf(f, "Odd name received %q", remote)
|
fs.Logf(f, "Odd name received %q", remote)
|
||||||
continue
|
continue
|
||||||
@@ -543,18 +553,18 @@ func (f *Fs) list(ctx context.Context, bucket, directory, prefix string, addBuck
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
for _, object := range objects.Items {
|
for _, object := range objects.Items {
|
||||||
remote := enc.ToStandardPath(object.Name)
|
remote := f.opt.Enc.ToStandardPath(object.Name)
|
||||||
if !strings.HasPrefix(remote, prefix) {
|
if !strings.HasPrefix(remote, prefix) {
|
||||||
fs.Logf(f, "Odd name received %q", object.Name)
|
fs.Logf(f, "Odd name received %q", object.Name)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
remote = remote[len(prefix):]
|
remote = remote[len(prefix):]
|
||||||
isDirectory := strings.HasSuffix(remote, "/")
|
isDirectory := remote == "" || strings.HasSuffix(remote, "/")
|
||||||
if addBucket {
|
if addBucket {
|
||||||
remote = path.Join(bucket, remote)
|
remote = path.Join(bucket, remote)
|
||||||
}
|
}
|
||||||
// is this a directory marker?
|
// is this a directory marker?
|
||||||
if isDirectory && object.Size == 0 {
|
if isDirectory {
|
||||||
continue // skip directory marker
|
continue // skip directory marker
|
||||||
}
|
}
|
||||||
err = fn(remote, object, false)
|
err = fn(remote, object, false)
|
||||||
@@ -620,7 +630,7 @@ func (f *Fs) listBuckets(ctx context.Context) (entries fs.DirEntries, err error)
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
for _, bucket := range buckets.Items {
|
for _, bucket := range buckets.Items {
|
||||||
d := fs.NewDir(enc.ToStandardName(bucket.Name), time.Time{})
|
d := fs.NewDir(f.opt.Enc.ToStandardName(bucket.Name), time.Time{})
|
||||||
entries = append(entries, d)
|
entries = append(entries, d)
|
||||||
}
|
}
|
||||||
if buckets.NextPageToken == "" {
|
if buckets.NextPageToken == "" {
|
||||||
@@ -802,7 +812,7 @@ func (f *Fs) Precision() time.Duration {
|
|||||||
return time.Nanosecond
|
return time.Nanosecond
|
||||||
}
|
}
|
||||||
|
|
||||||
// Copy src to this remote using server side copy operations.
|
// Copy src to this remote using server-side copy operations.
|
||||||
//
|
//
|
||||||
// This is stored with the remote path given
|
// This is stored with the remote path given
|
||||||
//
|
//
|
||||||
@@ -830,20 +840,27 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
remote: remote,
|
remote: remote,
|
||||||
}
|
}
|
||||||
|
|
||||||
var newObject *storage.Object
|
rewriteRequest := f.svc.Objects.Rewrite(srcBucket, srcPath, dstBucket, dstPath, nil)
|
||||||
err = f.pacer.Call(func() (bool, error) {
|
if !f.opt.BucketPolicyOnly {
|
||||||
copyObject := f.svc.Objects.Copy(srcBucket, srcPath, dstBucket, dstPath, nil)
|
rewriteRequest.DestinationPredefinedAcl(f.opt.ObjectACL)
|
||||||
if !f.opt.BucketPolicyOnly {
|
}
|
||||||
copyObject.DestinationPredefinedAcl(f.opt.ObjectACL)
|
var rewriteResponse *storage.RewriteResponse
|
||||||
|
for {
|
||||||
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
|
rewriteResponse, err = rewriteRequest.Context(ctx).Do()
|
||||||
|
return shouldRetry(err)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
}
|
}
|
||||||
newObject, err = copyObject.Context(ctx).Do()
|
if rewriteResponse.Done {
|
||||||
return shouldRetry(err)
|
break
|
||||||
})
|
}
|
||||||
if err != nil {
|
rewriteRequest.RewriteToken(rewriteResponse.RewriteToken)
|
||||||
return nil, err
|
fs.Debugf(dstObj, "Continuing rewrite %d bytes done", rewriteResponse.TotalBytesRewritten)
|
||||||
}
|
}
|
||||||
// Set the metadata for the new object while we have it
|
// Set the metadata for the new object while we have it
|
||||||
dstObj.setMetaData(newObject)
|
dstObj.setMetaData(rewriteResponse.Resource)
|
||||||
return dstObj, nil
|
return dstObj, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1011,11 +1028,10 @@ func (o *Object) Storable() bool {
|
|||||||
|
|
||||||
// Open an object for read
|
// Open an object for read
|
||||||
func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.ReadCloser, err error) {
|
func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.ReadCloser, err error) {
|
||||||
req, err := http.NewRequest("GET", o.url, nil)
|
req, err := http.NewRequestWithContext(ctx, "GET", o.url, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
req = req.WithContext(ctx) // go1.13 can use NewRequestWithContext
|
|
||||||
fs.FixRangeOption(options, o.bytes)
|
fs.FixRangeOption(options, o.bytes)
|
||||||
fs.OpenOptionAddHTTPHeaders(req.Header, options)
|
fs.OpenOptionAddHTTPHeaders(req.Header, options)
|
||||||
var res *http.Response
|
var res *http.Response
|
||||||
@@ -1057,6 +1073,35 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
ContentType: fs.MimeType(ctx, src),
|
ContentType: fs.MimeType(ctx, src),
|
||||||
Metadata: metadataFromModTime(modTime),
|
Metadata: metadataFromModTime(modTime),
|
||||||
}
|
}
|
||||||
|
// Apply upload options
|
||||||
|
for _, option := range options {
|
||||||
|
key, value := option.Header()
|
||||||
|
lowerKey := strings.ToLower(key)
|
||||||
|
switch lowerKey {
|
||||||
|
case "":
|
||||||
|
// ignore
|
||||||
|
case "cache-control":
|
||||||
|
object.CacheControl = value
|
||||||
|
case "content-disposition":
|
||||||
|
object.ContentDisposition = value
|
||||||
|
case "content-encoding":
|
||||||
|
object.ContentEncoding = value
|
||||||
|
case "content-language":
|
||||||
|
object.ContentLanguage = value
|
||||||
|
case "content-type":
|
||||||
|
object.ContentType = value
|
||||||
|
case "x-goog-storage-class":
|
||||||
|
object.StorageClass = value
|
||||||
|
default:
|
||||||
|
const googMetaPrefix = "x-goog-meta-"
|
||||||
|
if strings.HasPrefix(lowerKey, googMetaPrefix) {
|
||||||
|
metaKey := lowerKey[len(googMetaPrefix):]
|
||||||
|
object.Metadata[metaKey] = value
|
||||||
|
} else {
|
||||||
|
fs.Errorf(o, "Don't know how to set key %q on upload", key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
var newObject *storage.Object
|
var newObject *storage.Object
|
||||||
err = o.fs.pacer.CallNoRetry(func() (bool, error) {
|
err = o.fs.pacer.CallNoRetry(func() (bool, error) {
|
||||||
insertObject := o.fs.svc.Objects.Insert(bucket, &object).Media(in, googleapi.ContentType("")).Name(object.Name)
|
insertObject := o.fs.svc.Objects.Insert(bucket, &object).Media(in, googleapi.ContentType("")).Name(object.Name)
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ func TestAlbumsAdd(t *testing.T) {
|
|||||||
albums.add(a1)
|
albums.add(a1)
|
||||||
|
|
||||||
assert.Equal(t, map[string][]*api.Album{
|
assert.Equal(t, map[string][]*api.Album{
|
||||||
"one": []*api.Album{a1},
|
"one": {a1},
|
||||||
}, albums.dupes)
|
}, albums.dupes)
|
||||||
assert.Equal(t, map[string]*api.Album{
|
assert.Equal(t, map[string]*api.Album{
|
||||||
"1": a1,
|
"1": a1,
|
||||||
@@ -39,7 +39,7 @@ func TestAlbumsAdd(t *testing.T) {
|
|||||||
"one": a1,
|
"one": a1,
|
||||||
}, albums.byTitle)
|
}, albums.byTitle)
|
||||||
assert.Equal(t, map[string][]string{
|
assert.Equal(t, map[string][]string{
|
||||||
"": []string{"one"},
|
"": {"one"},
|
||||||
}, albums.path)
|
}, albums.path)
|
||||||
|
|
||||||
a2 := &api.Album{
|
a2 := &api.Album{
|
||||||
@@ -49,8 +49,8 @@ func TestAlbumsAdd(t *testing.T) {
|
|||||||
albums.add(a2)
|
albums.add(a2)
|
||||||
|
|
||||||
assert.Equal(t, map[string][]*api.Album{
|
assert.Equal(t, map[string][]*api.Album{
|
||||||
"one": []*api.Album{a1},
|
"one": {a1},
|
||||||
"two": []*api.Album{a2},
|
"two": {a2},
|
||||||
}, albums.dupes)
|
}, albums.dupes)
|
||||||
assert.Equal(t, map[string]*api.Album{
|
assert.Equal(t, map[string]*api.Album{
|
||||||
"1": a1,
|
"1": a1,
|
||||||
@@ -61,7 +61,7 @@ func TestAlbumsAdd(t *testing.T) {
|
|||||||
"two": a2,
|
"two": a2,
|
||||||
}, albums.byTitle)
|
}, albums.byTitle)
|
||||||
assert.Equal(t, map[string][]string{
|
assert.Equal(t, map[string][]string{
|
||||||
"": []string{"one", "two"},
|
"": {"one", "two"},
|
||||||
}, albums.path)
|
}, albums.path)
|
||||||
|
|
||||||
// Add a duplicate
|
// Add a duplicate
|
||||||
@@ -72,8 +72,8 @@ func TestAlbumsAdd(t *testing.T) {
|
|||||||
albums.add(a2a)
|
albums.add(a2a)
|
||||||
|
|
||||||
assert.Equal(t, map[string][]*api.Album{
|
assert.Equal(t, map[string][]*api.Album{
|
||||||
"one": []*api.Album{a1},
|
"one": {a1},
|
||||||
"two": []*api.Album{a2, a2a},
|
"two": {a2, a2a},
|
||||||
}, albums.dupes)
|
}, albums.dupes)
|
||||||
assert.Equal(t, map[string]*api.Album{
|
assert.Equal(t, map[string]*api.Album{
|
||||||
"1": a1,
|
"1": a1,
|
||||||
@@ -86,7 +86,7 @@ func TestAlbumsAdd(t *testing.T) {
|
|||||||
"two {2a}": a2a,
|
"two {2a}": a2a,
|
||||||
}, albums.byTitle)
|
}, albums.byTitle)
|
||||||
assert.Equal(t, map[string][]string{
|
assert.Equal(t, map[string][]string{
|
||||||
"": []string{"one", "two {2}", "two {2a}"},
|
"": {"one", "two {2}", "two {2a}"},
|
||||||
}, albums.path)
|
}, albums.path)
|
||||||
|
|
||||||
// Add a sub directory
|
// Add a sub directory
|
||||||
@@ -97,9 +97,9 @@ func TestAlbumsAdd(t *testing.T) {
|
|||||||
albums.add(a1sub)
|
albums.add(a1sub)
|
||||||
|
|
||||||
assert.Equal(t, map[string][]*api.Album{
|
assert.Equal(t, map[string][]*api.Album{
|
||||||
"one": []*api.Album{a1},
|
"one": {a1},
|
||||||
"two": []*api.Album{a2, a2a},
|
"two": {a2, a2a},
|
||||||
"one/sub": []*api.Album{a1sub},
|
"one/sub": {a1sub},
|
||||||
}, albums.dupes)
|
}, albums.dupes)
|
||||||
assert.Equal(t, map[string]*api.Album{
|
assert.Equal(t, map[string]*api.Album{
|
||||||
"1": a1,
|
"1": a1,
|
||||||
@@ -114,8 +114,8 @@ func TestAlbumsAdd(t *testing.T) {
|
|||||||
"two {2a}": a2a,
|
"two {2a}": a2a,
|
||||||
}, albums.byTitle)
|
}, albums.byTitle)
|
||||||
assert.Equal(t, map[string][]string{
|
assert.Equal(t, map[string][]string{
|
||||||
"": []string{"one", "two {2}", "two {2a}"},
|
"": {"one", "two {2}", "two {2a}"},
|
||||||
"one": []string{"sub"},
|
"one": {"sub"},
|
||||||
}, albums.path)
|
}, albums.path)
|
||||||
|
|
||||||
// Add a weird path
|
// Add a weird path
|
||||||
@@ -126,10 +126,10 @@ func TestAlbumsAdd(t *testing.T) {
|
|||||||
albums.add(a0)
|
albums.add(a0)
|
||||||
|
|
||||||
assert.Equal(t, map[string][]*api.Album{
|
assert.Equal(t, map[string][]*api.Album{
|
||||||
"{0}": []*api.Album{a0},
|
"{0}": {a0},
|
||||||
"one": []*api.Album{a1},
|
"one": {a1},
|
||||||
"two": []*api.Album{a2, a2a},
|
"two": {a2, a2a},
|
||||||
"one/sub": []*api.Album{a1sub},
|
"one/sub": {a1sub},
|
||||||
}, albums.dupes)
|
}, albums.dupes)
|
||||||
assert.Equal(t, map[string]*api.Album{
|
assert.Equal(t, map[string]*api.Album{
|
||||||
"0": a0,
|
"0": a0,
|
||||||
@@ -146,8 +146,8 @@ func TestAlbumsAdd(t *testing.T) {
|
|||||||
"two {2a}": a2a,
|
"two {2a}": a2a,
|
||||||
}, albums.byTitle)
|
}, albums.byTitle)
|
||||||
assert.Equal(t, map[string][]string{
|
assert.Equal(t, map[string][]string{
|
||||||
"": []string{"one", "two {2}", "two {2a}", "{0}"},
|
"": {"one", "two {2}", "two {2a}", "{0}"},
|
||||||
"one": []string{"sub"},
|
"one": {"sub"},
|
||||||
}, albums.path)
|
}, albums.path)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -181,9 +181,9 @@ func TestAlbumsDel(t *testing.T) {
|
|||||||
albums.add(a1sub)
|
albums.add(a1sub)
|
||||||
|
|
||||||
assert.Equal(t, map[string][]*api.Album{
|
assert.Equal(t, map[string][]*api.Album{
|
||||||
"one": []*api.Album{a1},
|
"one": {a1},
|
||||||
"two": []*api.Album{a2, a2a},
|
"two": {a2, a2a},
|
||||||
"one/sub": []*api.Album{a1sub},
|
"one/sub": {a1sub},
|
||||||
}, albums.dupes)
|
}, albums.dupes)
|
||||||
assert.Equal(t, map[string]*api.Album{
|
assert.Equal(t, map[string]*api.Album{
|
||||||
"1": a1,
|
"1": a1,
|
||||||
@@ -198,16 +198,16 @@ func TestAlbumsDel(t *testing.T) {
|
|||||||
"two {2a}": a2a,
|
"two {2a}": a2a,
|
||||||
}, albums.byTitle)
|
}, albums.byTitle)
|
||||||
assert.Equal(t, map[string][]string{
|
assert.Equal(t, map[string][]string{
|
||||||
"": []string{"one", "two {2}", "two {2a}"},
|
"": {"one", "two {2}", "two {2a}"},
|
||||||
"one": []string{"sub"},
|
"one": {"sub"},
|
||||||
}, albums.path)
|
}, albums.path)
|
||||||
|
|
||||||
albums.del(a1)
|
albums.del(a1)
|
||||||
|
|
||||||
assert.Equal(t, map[string][]*api.Album{
|
assert.Equal(t, map[string][]*api.Album{
|
||||||
"one": []*api.Album{a1},
|
"one": {a1},
|
||||||
"two": []*api.Album{a2, a2a},
|
"two": {a2, a2a},
|
||||||
"one/sub": []*api.Album{a1sub},
|
"one/sub": {a1sub},
|
||||||
}, albums.dupes)
|
}, albums.dupes)
|
||||||
assert.Equal(t, map[string]*api.Album{
|
assert.Equal(t, map[string]*api.Album{
|
||||||
"2": a2,
|
"2": a2,
|
||||||
@@ -220,16 +220,16 @@ func TestAlbumsDel(t *testing.T) {
|
|||||||
"two {2a}": a2a,
|
"two {2a}": a2a,
|
||||||
}, albums.byTitle)
|
}, albums.byTitle)
|
||||||
assert.Equal(t, map[string][]string{
|
assert.Equal(t, map[string][]string{
|
||||||
"": []string{"one", "two {2}", "two {2a}"},
|
"": {"one", "two {2}", "two {2a}"},
|
||||||
"one": []string{"sub"},
|
"one": {"sub"},
|
||||||
}, albums.path)
|
}, albums.path)
|
||||||
|
|
||||||
albums.del(a2)
|
albums.del(a2)
|
||||||
|
|
||||||
assert.Equal(t, map[string][]*api.Album{
|
assert.Equal(t, map[string][]*api.Album{
|
||||||
"one": []*api.Album{a1},
|
"one": {a1},
|
||||||
"two": []*api.Album{a2, a2a},
|
"two": {a2, a2a},
|
||||||
"one/sub": []*api.Album{a1sub},
|
"one/sub": {a1sub},
|
||||||
}, albums.dupes)
|
}, albums.dupes)
|
||||||
assert.Equal(t, map[string]*api.Album{
|
assert.Equal(t, map[string]*api.Album{
|
||||||
"2a": a2a,
|
"2a": a2a,
|
||||||
@@ -240,16 +240,16 @@ func TestAlbumsDel(t *testing.T) {
|
|||||||
"two {2a}": a2a,
|
"two {2a}": a2a,
|
||||||
}, albums.byTitle)
|
}, albums.byTitle)
|
||||||
assert.Equal(t, map[string][]string{
|
assert.Equal(t, map[string][]string{
|
||||||
"": []string{"one", "two {2a}"},
|
"": {"one", "two {2a}"},
|
||||||
"one": []string{"sub"},
|
"one": {"sub"},
|
||||||
}, albums.path)
|
}, albums.path)
|
||||||
|
|
||||||
albums.del(a2a)
|
albums.del(a2a)
|
||||||
|
|
||||||
assert.Equal(t, map[string][]*api.Album{
|
assert.Equal(t, map[string][]*api.Album{
|
||||||
"one": []*api.Album{a1},
|
"one": {a1},
|
||||||
"two": []*api.Album{a2, a2a},
|
"two": {a2, a2a},
|
||||||
"one/sub": []*api.Album{a1sub},
|
"one/sub": {a1sub},
|
||||||
}, albums.dupes)
|
}, albums.dupes)
|
||||||
assert.Equal(t, map[string]*api.Album{
|
assert.Equal(t, map[string]*api.Album{
|
||||||
"1sub": a1sub,
|
"1sub": a1sub,
|
||||||
@@ -258,16 +258,16 @@ func TestAlbumsDel(t *testing.T) {
|
|||||||
"one/sub": a1sub,
|
"one/sub": a1sub,
|
||||||
}, albums.byTitle)
|
}, albums.byTitle)
|
||||||
assert.Equal(t, map[string][]string{
|
assert.Equal(t, map[string][]string{
|
||||||
"": []string{"one"},
|
"": {"one"},
|
||||||
"one": []string{"sub"},
|
"one": {"sub"},
|
||||||
}, albums.path)
|
}, albums.path)
|
||||||
|
|
||||||
albums.del(a1sub)
|
albums.del(a1sub)
|
||||||
|
|
||||||
assert.Equal(t, map[string][]*api.Album{
|
assert.Equal(t, map[string][]*api.Album{
|
||||||
"one": []*api.Album{a1},
|
"one": {a1},
|
||||||
"two": []*api.Album{a2, a2a},
|
"two": {a2, a2a},
|
||||||
"one/sub": []*api.Album{a1sub},
|
"one/sub": {a1sub},
|
||||||
}, albums.dupes)
|
}, albums.dupes)
|
||||||
assert.Equal(t, map[string]*api.Album{}, albums.byID)
|
assert.Equal(t, map[string]*api.Album{}, albums.byID)
|
||||||
assert.Equal(t, map[string]*api.Album{}, albums.byTitle)
|
assert.Equal(t, map[string]*api.Album{}, albums.byTitle)
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ type Error struct {
|
|||||||
Details ErrorDetails `json:"error"`
|
Details ErrorDetails `json:"error"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Error statisfies error interface
|
// Error satisfies error interface
|
||||||
func (e *Error) Error() string {
|
func (e *Error) Error() string {
|
||||||
return fmt.Sprintf("%s (%d %s)", e.Details.Message, e.Details.Code, e.Details.Status)
|
return fmt.Sprintf("%s (%d %s)", e.Details.Message, e.Details.Code, e.Details.Status)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ import (
|
|||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"github.com/rclone/rclone/backend/googlephotos/api"
|
"github.com/rclone/rclone/backend/googlephotos/api"
|
||||||
"github.com/rclone/rclone/fs"
|
"github.com/rclone/rclone/fs"
|
||||||
"github.com/rclone/rclone/fs/config"
|
|
||||||
"github.com/rclone/rclone/fs/config/configmap"
|
"github.com/rclone/rclone/fs/config/configmap"
|
||||||
"github.com/rclone/rclone/fs/config/configstruct"
|
"github.com/rclone/rclone/fs/config/configstruct"
|
||||||
"github.com/rclone/rclone/fs/config/obscure"
|
"github.com/rclone/rclone/fs/config/obscure"
|
||||||
@@ -79,7 +78,7 @@ func init() {
|
|||||||
Prefix: "gphotos",
|
Prefix: "gphotos",
|
||||||
Description: "Google Photos",
|
Description: "Google Photos",
|
||||||
NewFs: NewFs,
|
NewFs: NewFs,
|
||||||
Config: func(name string, m configmap.Mapper) {
|
Config: func(ctx context.Context, name string, m configmap.Mapper) {
|
||||||
// Parse config into Options struct
|
// Parse config into Options struct
|
||||||
opt := new(Options)
|
opt := new(Options)
|
||||||
err := configstruct.Set(m, opt)
|
err := configstruct.Set(m, opt)
|
||||||
@@ -96,7 +95,7 @@ func init() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Do the oauth
|
// Do the oauth
|
||||||
err = oauthutil.Config("google photos", name, m, oauthConfig)
|
err = oauthutil.Config(ctx, "google photos", name, m, oauthConfig, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
golog.Fatalf("Failed to configure token: %v", err)
|
golog.Fatalf("Failed to configure token: %v", err)
|
||||||
}
|
}
|
||||||
@@ -110,13 +109,7 @@ func init() {
|
|||||||
`)
|
`)
|
||||||
|
|
||||||
},
|
},
|
||||||
Options: []fs.Option{{
|
Options: append(oauthutil.SharedOptions, []fs.Option{{
|
||||||
Name: config.ConfigClientID,
|
|
||||||
Help: "Google Application Client Id\nLeave blank normally.",
|
|
||||||
}, {
|
|
||||||
Name: config.ConfigClientSecret,
|
|
||||||
Help: "Google Application Client Secret\nLeave blank normally.",
|
|
||||||
}, {
|
|
||||||
Name: "read_only",
|
Name: "read_only",
|
||||||
Default: false,
|
Default: false,
|
||||||
Help: `Set to make the Google Photos backend read only.
|
Help: `Set to make the Google Photos backend read only.
|
||||||
@@ -134,14 +127,38 @@ rclone mount needs to know the size of files in advance of reading
|
|||||||
them, so setting this flag when using rclone mount is recommended if
|
them, so setting this flag when using rclone mount is recommended if
|
||||||
you want to read the media.`,
|
you want to read the media.`,
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
}},
|
}, {
|
||||||
|
Name: "start_year",
|
||||||
|
Default: 2000,
|
||||||
|
Help: `Year limits the photos to be downloaded to those which are uploaded after the given year`,
|
||||||
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: "include_archived",
|
||||||
|
Default: false,
|
||||||
|
Help: `Also view and download archived media.
|
||||||
|
|
||||||
|
By default rclone does not request archived media. Thus, when syncing,
|
||||||
|
archived media is not visible in directory listings or transferred.
|
||||||
|
|
||||||
|
Note that media in albums is always visible and synced, no matter
|
||||||
|
their archive status.
|
||||||
|
|
||||||
|
With this flag, archived media are always visible in directory
|
||||||
|
listings and transferred.
|
||||||
|
|
||||||
|
Without this flag, archived media will not be visible in directory
|
||||||
|
listings and won't be transferred.`,
|
||||||
|
Advanced: true,
|
||||||
|
}}...),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Options defines the configuration for this backend
|
// Options defines the configuration for this backend
|
||||||
type Options struct {
|
type Options struct {
|
||||||
ReadOnly bool `config:"read_only"`
|
ReadOnly bool `config:"read_only"`
|
||||||
ReadSize bool `config:"read_size"`
|
ReadSize bool `config:"read_size"`
|
||||||
|
StartYear int `config:"start_year"`
|
||||||
|
IncludeArchived bool `config:"include_archived"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fs represents a remote storage server
|
// Fs represents a remote storage server
|
||||||
@@ -202,6 +219,15 @@ func (f *Fs) dirTime() time.Time {
|
|||||||
return f.startTime
|
return f.startTime
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// startYear returns the start year
|
||||||
|
func (f *Fs) startYear() int {
|
||||||
|
return f.opt.StartYear
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fs) includeArchived() bool {
|
||||||
|
return f.opt.IncludeArchived
|
||||||
|
}
|
||||||
|
|
||||||
// retryErrorCodes is a slice of error codes that we will retry
|
// retryErrorCodes is a slice of error codes that we will retry
|
||||||
var retryErrorCodes = []int{
|
var retryErrorCodes = []int{
|
||||||
429, // Too Many Requests.
|
429, // Too Many Requests.
|
||||||
@@ -224,6 +250,10 @@ func errorHandler(resp *http.Response) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
body = nil
|
body = nil
|
||||||
}
|
}
|
||||||
|
// Google sends 404 messages as images so be prepared for that
|
||||||
|
if strings.HasPrefix(resp.Header.Get("Content-Type"), "image/") {
|
||||||
|
body = []byte("Image not found or broken")
|
||||||
|
}
|
||||||
var e = api.Error{
|
var e = api.Error{
|
||||||
Details: api.ErrorDetails{
|
Details: api.ErrorDetails{
|
||||||
Code: resp.StatusCode,
|
Code: resp.StatusCode,
|
||||||
@@ -238,7 +268,7 @@ func errorHandler(resp *http.Response) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// NewFs constructs an Fs from the path, bucket:path
|
// NewFs constructs an Fs from the path, bucket:path
|
||||||
func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {
|
||||||
// Parse config into Options struct
|
// Parse config into Options struct
|
||||||
opt := new(Options)
|
opt := new(Options)
|
||||||
err := configstruct.Set(m, opt)
|
err := configstruct.Set(m, opt)
|
||||||
@@ -246,8 +276,8 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
baseClient := fshttp.NewClient(fs.Config)
|
baseClient := fshttp.NewClient(ctx)
|
||||||
oAuthClient, ts, err := oauthutil.NewClientWithBaseClient(name, m, oauthConfig, baseClient)
|
oAuthClient, ts, err := oauthutil.NewClientWithBaseClient(ctx, name, m, oauthConfig, baseClient)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "failed to configure Box")
|
return nil, errors.Wrap(err, "failed to configure Box")
|
||||||
}
|
}
|
||||||
@@ -264,14 +294,14 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
unAuth: rest.NewClient(baseClient),
|
unAuth: rest.NewClient(baseClient),
|
||||||
srv: rest.NewClient(oAuthClient).SetRoot(rootURL),
|
srv: rest.NewClient(oAuthClient).SetRoot(rootURL),
|
||||||
ts: ts,
|
ts: ts,
|
||||||
pacer: fs.NewPacer(pacer.NewGoogleDrive(pacer.MinSleep(minSleep))),
|
pacer: fs.NewPacer(ctx, pacer.NewGoogleDrive(pacer.MinSleep(minSleep))),
|
||||||
startTime: time.Now(),
|
startTime: time.Now(),
|
||||||
albums: map[bool]*albums{},
|
albums: map[bool]*albums{},
|
||||||
uploaded: dirtree.New(),
|
uploaded: dirtree.New(),
|
||||||
}
|
}
|
||||||
f.features = (&fs.Features{
|
f.features = (&fs.Features{
|
||||||
ReadMimeType: true,
|
ReadMimeType: true,
|
||||||
}).Fill(f)
|
}).Fill(ctx, f)
|
||||||
f.srv.SetErrorHandler(errorHandler)
|
f.srv.SetErrorHandler(errorHandler)
|
||||||
|
|
||||||
_, _, pattern := patterns.match(f.root, "", true)
|
_, _, pattern := patterns.match(f.root, "", true)
|
||||||
@@ -280,7 +310,7 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
var leaf string
|
var leaf string
|
||||||
f.root, leaf = path.Split(f.root)
|
f.root, leaf = path.Split(f.root)
|
||||||
f.root = strings.TrimRight(f.root, "/")
|
f.root = strings.TrimRight(f.root, "/")
|
||||||
_, err := f.NewObject(context.TODO(), leaf)
|
_, err := f.NewObject(ctx, leaf)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return f, fs.ErrorIsFile
|
return f, fs.ErrorIsFile
|
||||||
}
|
}
|
||||||
@@ -489,6 +519,12 @@ func (f *Fs) list(ctx context.Context, filter api.SearchFilter, fn listFn) (err
|
|||||||
}
|
}
|
||||||
filter.PageSize = listChunks
|
filter.PageSize = listChunks
|
||||||
filter.PageToken = ""
|
filter.PageToken = ""
|
||||||
|
if filter.AlbumID == "" { // album ID and filters cannot be set together, else error 400 INVALID_ARGUMENT
|
||||||
|
if filter.Filters == nil {
|
||||||
|
filter.Filters = &api.Filters{}
|
||||||
|
}
|
||||||
|
filter.Filters.IncludeArchivedMedia = &f.opt.IncludeArchived
|
||||||
|
}
|
||||||
lastID := ""
|
lastID := ""
|
||||||
for {
|
for {
|
||||||
var result api.MediaItems
|
var result api.MediaItems
|
||||||
@@ -943,8 +979,9 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
|
|
||||||
// Upload the media item in exchange for an UploadToken
|
// Upload the media item in exchange for an UploadToken
|
||||||
opts := rest.Opts{
|
opts := rest.Opts{
|
||||||
Method: "POST",
|
Method: "POST",
|
||||||
Path: "/uploads",
|
Path: "/uploads",
|
||||||
|
Options: options,
|
||||||
ExtraHeaders: map[string]string{
|
ExtraHeaders: map[string]string{
|
||||||
"X-Goog-Upload-File-Name": fileName,
|
"X-Goog-Upload-File-Name": fileName,
|
||||||
"X-Goog-Upload-Protocol": "raw",
|
"X-Goog-Upload-Protocol": "raw",
|
||||||
@@ -1003,7 +1040,9 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
|
|
||||||
// Add upload to internal storage
|
// Add upload to internal storage
|
||||||
if pattern.isUpload {
|
if pattern.isUpload {
|
||||||
|
o.fs.uploadedMu.Lock()
|
||||||
o.fs.uploaded.AddEntry(o)
|
o.fs.uploaded.AddEntry(o)
|
||||||
|
o.fs.uploadedMu.Unlock()
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import (
|
|||||||
_ "github.com/rclone/rclone/backend/local"
|
_ "github.com/rclone/rclone/backend/local"
|
||||||
"github.com/rclone/rclone/fs"
|
"github.com/rclone/rclone/fs"
|
||||||
"github.com/rclone/rclone/fs/hash"
|
"github.com/rclone/rclone/fs/hash"
|
||||||
|
"github.com/rclone/rclone/fs/operations"
|
||||||
"github.com/rclone/rclone/fstest"
|
"github.com/rclone/rclone/fstest"
|
||||||
"github.com/rclone/rclone/lib/random"
|
"github.com/rclone/rclone/lib/random"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
@@ -26,17 +27,6 @@ const (
|
|||||||
fileNameUpload = "rclone-test-image2.jpg"
|
fileNameUpload = "rclone-test-image2.jpg"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Wrapper to override the remote for an object
|
|
||||||
type overrideRemoteObject struct {
|
|
||||||
fs.Object
|
|
||||||
remote string
|
|
||||||
}
|
|
||||||
|
|
||||||
// Remote returns the overridden remote name
|
|
||||||
func (o *overrideRemoteObject) Remote() string {
|
|
||||||
return o.remote
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestIntegration(t *testing.T) {
|
func TestIntegration(t *testing.T) {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
fstest.Initialise()
|
fstest.Initialise()
|
||||||
@@ -45,14 +35,14 @@ func TestIntegration(t *testing.T) {
|
|||||||
if *fstest.RemoteName == "" {
|
if *fstest.RemoteName == "" {
|
||||||
*fstest.RemoteName = "TestGooglePhotos:"
|
*fstest.RemoteName = "TestGooglePhotos:"
|
||||||
}
|
}
|
||||||
f, err := fs.NewFs(*fstest.RemoteName)
|
f, err := fs.NewFs(ctx, *fstest.RemoteName)
|
||||||
if err == fs.ErrorNotFoundInConfigFile {
|
if err == fs.ErrorNotFoundInConfigFile {
|
||||||
t.Skip(fmt.Sprintf("Couldn't create google photos backend - skipping tests: %v", err))
|
t.Skip(fmt.Sprintf("Couldn't create google photos backend - skipping tests: %v", err))
|
||||||
}
|
}
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
// Create local Fs pointing at testfiles
|
// Create local Fs pointing at testfiles
|
||||||
localFs, err := fs.NewFs("testfiles")
|
localFs, err := fs.NewFs(ctx, "testfiles")
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
t.Run("CreateAlbum", func(t *testing.T) {
|
t.Run("CreateAlbum", func(t *testing.T) {
|
||||||
@@ -66,7 +56,7 @@ func TestIntegration(t *testing.T) {
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
in, err := srcObj.Open(ctx)
|
in, err := srcObj.Open(ctx)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
dstObj, err := f.Put(ctx, in, &overrideRemoteObject{srcObj, remote})
|
dstObj, err := f.Put(ctx, in, operations.NewOverrideRemote(srcObj, remote))
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
assert.Equal(t, remote, dstObj.Remote())
|
assert.Equal(t, remote, dstObj.Remote())
|
||||||
_ = in.Close()
|
_ = in.Close()
|
||||||
@@ -125,7 +115,7 @@ func TestIntegration(t *testing.T) {
|
|||||||
assert.Equal(t, "2013-07-26 08:57:21 +0000 UTC", entries[0].ModTime(ctx).String())
|
assert.Equal(t, "2013-07-26 08:57:21 +0000 UTC", entries[0].ModTime(ctx).String())
|
||||||
})
|
})
|
||||||
|
|
||||||
// Check it is there in the date/month/year heirachy
|
// Check it is there in the date/month/year hierarchy
|
||||||
// 2013-07-13 is the creation date of the folder
|
// 2013-07-13 is the creation date of the folder
|
||||||
checkPresent := func(t *testing.T, objPath string) {
|
checkPresent := func(t *testing.T, objPath string) {
|
||||||
entries, err := f.List(ctx, objPath)
|
entries, err := f.List(ctx, objPath)
|
||||||
@@ -165,7 +155,7 @@ func TestIntegration(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
t.Run("NewFsIsFile", func(t *testing.T) {
|
t.Run("NewFsIsFile", func(t *testing.T) {
|
||||||
fNew, err := fs.NewFs(*fstest.RemoteName + remote)
|
fNew, err := fs.NewFs(ctx, *fstest.RemoteName+remote)
|
||||||
assert.Equal(t, fs.ErrorIsFile, err)
|
assert.Equal(t, fs.ErrorIsFile, err)
|
||||||
leaf := path.Base(remote)
|
leaf := path.Base(remote)
|
||||||
o, err := fNew.NewObject(ctx, leaf)
|
o, err := fNew.NewObject(ctx, leaf)
|
||||||
@@ -231,7 +221,7 @@ func TestIntegration(t *testing.T) {
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
in, err := srcObj.Open(ctx)
|
in, err := srcObj.Open(ctx)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
dstObj, err := f.Put(ctx, in, &overrideRemoteObject{srcObj, remote})
|
dstObj, err := f.Put(ctx, in, operations.NewOverrideRemote(srcObj, remote))
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
assert.Equal(t, remote, dstObj.Remote())
|
assert.Equal(t, remote, dstObj.Remote())
|
||||||
_ = in.Close()
|
_ = in.Close()
|
||||||
|
|||||||
@@ -23,6 +23,8 @@ type lister interface {
|
|||||||
listAlbums(ctx context.Context, shared bool) (all *albums, err error)
|
listAlbums(ctx context.Context, shared bool) (all *albums, err error)
|
||||||
listUploads(ctx context.Context, dir string) (entries fs.DirEntries, err error)
|
listUploads(ctx context.Context, dir string) (entries fs.DirEntries, err error)
|
||||||
dirTime() time.Time
|
dirTime() time.Time
|
||||||
|
startYear() int
|
||||||
|
includeArchived() bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// dirPattern describes a single directory pattern
|
// dirPattern describes a single directory pattern
|
||||||
@@ -52,6 +54,7 @@ var patterns = dirPatterns{
|
|||||||
fs.NewDir(prefix+"album", f.dirTime()),
|
fs.NewDir(prefix+"album", f.dirTime()),
|
||||||
fs.NewDir(prefix+"shared-album", f.dirTime()),
|
fs.NewDir(prefix+"shared-album", f.dirTime()),
|
||||||
fs.NewDir(prefix+"upload", f.dirTime()),
|
fs.NewDir(prefix+"upload", f.dirTime()),
|
||||||
|
fs.NewDir(prefix+"feature", f.dirTime()),
|
||||||
}, nil
|
}, nil
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -189,6 +192,28 @@ var patterns = dirPatterns{
|
|||||||
re: `^shared-album/(.+?)/([^/]+)$`,
|
re: `^shared-album/(.+?)/([^/]+)$`,
|
||||||
isFile: true,
|
isFile: true,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
re: `^feature$`,
|
||||||
|
toEntries: func(ctx context.Context, f lister, prefix string, match []string) (entries fs.DirEntries, err error) {
|
||||||
|
return fs.DirEntries{
|
||||||
|
fs.NewDir(prefix+"favorites", f.dirTime()),
|
||||||
|
}, nil
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
re: `^feature/favorites$`,
|
||||||
|
toEntries: func(ctx context.Context, f lister, prefix string, match []string) (entries fs.DirEntries, err error) {
|
||||||
|
filter := featureFilter(ctx, f, match)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return f.listDir(ctx, prefix, filter)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
re: `^feature/favorites/([^/]+)$`,
|
||||||
|
isFile: true,
|
||||||
|
},
|
||||||
}.mustCompile()
|
}.mustCompile()
|
||||||
|
|
||||||
// mustCompile compiles the regexps in the dirPatterns
|
// mustCompile compiles the regexps in the dirPatterns
|
||||||
@@ -200,7 +225,7 @@ func (ds dirPatterns) mustCompile() dirPatterns {
|
|||||||
return ds
|
return ds
|
||||||
}
|
}
|
||||||
|
|
||||||
// match finds the path passed in in the matching structure and
|
// match finds the path passed in the matching structure and
|
||||||
// returns the parameters and a pointer to the match, or nil.
|
// returns the parameters and a pointer to the match, or nil.
|
||||||
func (ds dirPatterns) match(root string, itemPath string, isFile bool) (match []string, prefix string, pattern *dirPattern) {
|
func (ds dirPatterns) match(root string, itemPath string, isFile bool) (match []string, prefix string, pattern *dirPattern) {
|
||||||
itemPath = strings.Trim(itemPath, "/")
|
itemPath = strings.Trim(itemPath, "/")
|
||||||
@@ -222,11 +247,10 @@ func (ds dirPatterns) match(root string, itemPath string, isFile bool) (match []
|
|||||||
return nil, "", nil
|
return nil, "", nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Return the years from 2000 to today
|
// Return the years from startYear to today
|
||||||
// FIXME make configurable?
|
|
||||||
func years(ctx context.Context, f lister, prefix string, match []string) (entries fs.DirEntries, err error) {
|
func years(ctx context.Context, f lister, prefix string, match []string) (entries fs.DirEntries, err error) {
|
||||||
currentYear := f.dirTime().Year()
|
currentYear := f.dirTime().Year()
|
||||||
for year := 2000; year <= currentYear; year++ {
|
for year := f.startYear(); year <= currentYear; year++ {
|
||||||
entries = append(entries, fs.NewDir(prefix+fmt.Sprint(year), f.dirTime()))
|
entries = append(entries, fs.NewDir(prefix+fmt.Sprint(year), f.dirTime()))
|
||||||
}
|
}
|
||||||
return entries, nil
|
return entries, nil
|
||||||
@@ -290,6 +314,24 @@ func yearMonthDayFilter(ctx context.Context, f lister, match []string) (sf api.S
|
|||||||
return sf, nil
|
return sf, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// featureFilter creates a filter for the Feature enum
|
||||||
|
//
|
||||||
|
// The API only supports one feature, FAVORITES, so hardcode that feature
|
||||||
|
//
|
||||||
|
// https://developers.google.com/photos/library/reference/rest/v1/mediaItems/search#FeatureFilter
|
||||||
|
func featureFilter(ctx context.Context, f lister, match []string) (sf api.SearchFilter) {
|
||||||
|
sf = api.SearchFilter{
|
||||||
|
Filters: &api.Filters{
|
||||||
|
FeatureFilter: &api.FeatureFilter{
|
||||||
|
IncludedFeatures: []string{
|
||||||
|
"FAVORITES",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return sf
|
||||||
|
}
|
||||||
|
|
||||||
// Turns an albumPath into entries
|
// Turns an albumPath into entries
|
||||||
//
|
//
|
||||||
// These can either be synthetic directory entries if the album path
|
// These can either be synthetic directory entries if the album path
|
||||||
|
|||||||
@@ -59,6 +59,16 @@ func (f *testLister) dirTime() time.Time {
|
|||||||
return startTime
|
return startTime
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// mock startYear for testing
|
||||||
|
func (f *testLister) startYear() int {
|
||||||
|
return 2000
|
||||||
|
}
|
||||||
|
|
||||||
|
// mock includeArchived for testing
|
||||||
|
func (f *testLister) includeArchived() bool {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
func TestPatternMatch(t *testing.T) {
|
func TestPatternMatch(t *testing.T) {
|
||||||
for testNumber, test := range []struct {
|
for testNumber, test := range []struct {
|
||||||
// input
|
// input
|
||||||
@@ -150,6 +160,38 @@ func TestPatternMatch(t *testing.T) {
|
|||||||
wantPrefix: "file.jpg/",
|
wantPrefix: "file.jpg/",
|
||||||
wantPattern: &patterns[5],
|
wantPattern: &patterns[5],
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
root: "",
|
||||||
|
itemPath: "feature",
|
||||||
|
isFile: false,
|
||||||
|
wantMatch: []string{"feature"},
|
||||||
|
wantPrefix: "feature/",
|
||||||
|
wantPattern: &patterns[23],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
root: "feature/favorites",
|
||||||
|
itemPath: "",
|
||||||
|
isFile: false,
|
||||||
|
wantMatch: []string{"feature/favorites"},
|
||||||
|
wantPrefix: "",
|
||||||
|
wantPattern: &patterns[24],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
root: "feature",
|
||||||
|
itemPath: "favorites",
|
||||||
|
isFile: false,
|
||||||
|
wantMatch: []string{"feature/favorites"},
|
||||||
|
wantPrefix: "favorites/",
|
||||||
|
wantPattern: &patterns[24],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
root: "feature/favorites",
|
||||||
|
itemPath: "file.jpg",
|
||||||
|
isFile: true,
|
||||||
|
wantMatch: []string{"feature/favorites/file.jpg", "file.jpg"},
|
||||||
|
wantPrefix: "file.jpg/",
|
||||||
|
wantPattern: &patterns[25],
|
||||||
|
},
|
||||||
} {
|
} {
|
||||||
t.Run(fmt.Sprintf("#%d,root=%q,itemPath=%q,isFile=%v", testNumber, test.root, test.itemPath, test.isFile), func(t *testing.T) {
|
t.Run(fmt.Sprintf("#%d,root=%q,itemPath=%q,isFile=%v", testNumber, test.root, test.itemPath, test.isFile), func(t *testing.T) {
|
||||||
gotMatch, gotPrefix, gotPattern := patterns.match(test.root, test.itemPath, test.isFile)
|
gotMatch, gotPrefix, gotPattern := patterns.match(test.root, test.itemPath, test.isFile)
|
||||||
|
|||||||
@@ -0,0 +1,320 @@
|
|||||||
|
// +build !plan9
|
||||||
|
|
||||||
|
package hdfs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"os/user"
|
||||||
|
"path"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/colinmarc/hdfs/v2"
|
||||||
|
krb "github.com/jcmturner/gokrb5/v8/client"
|
||||||
|
"github.com/jcmturner/gokrb5/v8/config"
|
||||||
|
"github.com/jcmturner/gokrb5/v8/credentials"
|
||||||
|
"github.com/rclone/rclone/fs"
|
||||||
|
"github.com/rclone/rclone/fs/config/configmap"
|
||||||
|
"github.com/rclone/rclone/fs/config/configstruct"
|
||||||
|
"github.com/rclone/rclone/fs/hash"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Fs represents a HDFS server
|
||||||
|
type Fs struct {
|
||||||
|
name string
|
||||||
|
root string
|
||||||
|
features *fs.Features // optional features
|
||||||
|
opt Options // options for this backend
|
||||||
|
ci *fs.ConfigInfo // global config
|
||||||
|
client *hdfs.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
// copy-paste from https://github.com/colinmarc/hdfs/blob/master/cmd/hdfs/kerberos.go
|
||||||
|
func getKerberosClient() (*krb.Client, error) {
|
||||||
|
configPath := os.Getenv("KRB5_CONFIG")
|
||||||
|
if configPath == "" {
|
||||||
|
configPath = "/etc/krb5.conf"
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg, err := config.Load(configPath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Determine the ccache location from the environment, falling back to the
|
||||||
|
// default location.
|
||||||
|
ccachePath := os.Getenv("KRB5CCNAME")
|
||||||
|
if strings.Contains(ccachePath, ":") {
|
||||||
|
if strings.HasPrefix(ccachePath, "FILE:") {
|
||||||
|
ccachePath = strings.SplitN(ccachePath, ":", 2)[1]
|
||||||
|
} else {
|
||||||
|
return nil, fmt.Errorf("unusable ccache: %s", ccachePath)
|
||||||
|
}
|
||||||
|
} else if ccachePath == "" {
|
||||||
|
u, err := user.Current()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
ccachePath = fmt.Sprintf("/tmp/krb5cc_%s", u.Uid)
|
||||||
|
}
|
||||||
|
|
||||||
|
ccache, err := credentials.LoadCCache(ccachePath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
client, err := krb.NewFromCCache(ccache, cfg)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return client, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewFs constructs an Fs from the path
|
||||||
|
func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {
|
||||||
|
opt := new(Options)
|
||||||
|
err := configstruct.Set(m, opt)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
options := hdfs.ClientOptions{
|
||||||
|
Addresses: []string{opt.Namenode},
|
||||||
|
UseDatanodeHostname: false,
|
||||||
|
}
|
||||||
|
|
||||||
|
if opt.ServicePrincipalName != "" {
|
||||||
|
options.KerberosClient, err = getKerberosClient()
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("Problem with kerberos authentication: %s", err)
|
||||||
|
}
|
||||||
|
options.KerberosServicePrincipleName = opt.ServicePrincipalName
|
||||||
|
|
||||||
|
if opt.DataTransferProtection != "" {
|
||||||
|
options.DataTransferProtection = opt.DataTransferProtection
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
options.User = opt.Username
|
||||||
|
}
|
||||||
|
|
||||||
|
client, err := hdfs.NewClient(options)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
f := &Fs{
|
||||||
|
name: name,
|
||||||
|
root: root,
|
||||||
|
opt: *opt,
|
||||||
|
ci: fs.GetConfig(ctx),
|
||||||
|
client: client,
|
||||||
|
}
|
||||||
|
|
||||||
|
f.features = (&fs.Features{
|
||||||
|
CanHaveEmptyDirectories: true,
|
||||||
|
}).Fill(ctx, f)
|
||||||
|
|
||||||
|
info, err := f.client.Stat(f.realpath(""))
|
||||||
|
if err == nil && !info.IsDir() {
|
||||||
|
f.root = path.Dir(f.root)
|
||||||
|
return f, fs.ErrorIsFile
|
||||||
|
}
|
||||||
|
|
||||||
|
return f, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Name of this fs
|
||||||
|
func (f *Fs) Name() string {
|
||||||
|
return f.name
|
||||||
|
}
|
||||||
|
|
||||||
|
// Root of the remote (as passed into NewFs)
|
||||||
|
func (f *Fs) Root() string {
|
||||||
|
return f.root
|
||||||
|
}
|
||||||
|
|
||||||
|
// String returns a description of the FS
|
||||||
|
func (f *Fs) String() string {
|
||||||
|
return fmt.Sprintf("hdfs://%s", f.opt.Namenode)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Features returns the optional features of this Fs
|
||||||
|
func (f *Fs) Features() *fs.Features {
|
||||||
|
return f.features
|
||||||
|
}
|
||||||
|
|
||||||
|
// Precision return the precision of this Fs
|
||||||
|
func (f *Fs) Precision() time.Duration {
|
||||||
|
return time.Second
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hashes are not supported
|
||||||
|
func (f *Fs) Hashes() hash.Set {
|
||||||
|
return hash.Set(hash.None)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewObject finds file at remote or return fs.ErrorObjectNotFound
|
||||||
|
func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) {
|
||||||
|
realpath := f.realpath(remote)
|
||||||
|
fs.Debugf(f, "new [%s]", realpath)
|
||||||
|
|
||||||
|
info, err := f.ensureFile(realpath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Object{
|
||||||
|
fs: f,
|
||||||
|
remote: remote,
|
||||||
|
size: info.Size(),
|
||||||
|
modTime: info.ModTime(),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// List the objects and directories in dir into entries.
|
||||||
|
func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) {
|
||||||
|
realpath := f.realpath(dir)
|
||||||
|
fs.Debugf(f, "list [%s]", realpath)
|
||||||
|
|
||||||
|
err = f.ensureDirectory(realpath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
list, err := f.client.ReadDir(realpath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for _, x := range list {
|
||||||
|
stdName := f.opt.Enc.ToStandardName(x.Name())
|
||||||
|
remote := path.Join(dir, stdName)
|
||||||
|
if x.IsDir() {
|
||||||
|
entries = append(entries, fs.NewDir(remote, x.ModTime()))
|
||||||
|
} else {
|
||||||
|
entries = append(entries, &Object{
|
||||||
|
fs: f,
|
||||||
|
remote: remote,
|
||||||
|
size: x.Size(),
|
||||||
|
modTime: x.ModTime()})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return entries, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Put the object
|
||||||
|
func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
|
||||||
|
o := &Object{
|
||||||
|
fs: f,
|
||||||
|
remote: src.Remote(),
|
||||||
|
}
|
||||||
|
err := o.Update(ctx, in, src, options...)
|
||||||
|
return o, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// PutStream uploads to the remote path with the modTime given of indeterminate size
|
||||||
|
func (f *Fs) PutStream(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
|
||||||
|
return f.Put(ctx, in, src, options...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mkdir makes a directory
|
||||||
|
func (f *Fs) Mkdir(ctx context.Context, dir string) error {
|
||||||
|
fs.Debugf(f, "mkdir [%s]", f.realpath(dir))
|
||||||
|
return f.client.MkdirAll(f.realpath(dir), 0755)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rmdir deletes the directory
|
||||||
|
func (f *Fs) Rmdir(ctx context.Context, dir string) error {
|
||||||
|
realpath := f.realpath(dir)
|
||||||
|
fs.Debugf(f, "rmdir [%s]", realpath)
|
||||||
|
|
||||||
|
err := f.ensureDirectory(realpath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// do not remove empty directory
|
||||||
|
list, err := f.client.ReadDir(realpath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(list) > 0 {
|
||||||
|
return fs.ErrorDirectoryNotEmpty
|
||||||
|
}
|
||||||
|
|
||||||
|
return f.client.Remove(realpath)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Purge deletes all the files in the directory
|
||||||
|
func (f *Fs) Purge(ctx context.Context, dir string) error {
|
||||||
|
realpath := f.realpath(dir)
|
||||||
|
fs.Debugf(f, "purge [%s]", realpath)
|
||||||
|
|
||||||
|
err := f.ensureDirectory(realpath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return f.client.RemoveAll(realpath)
|
||||||
|
}
|
||||||
|
|
||||||
|
// About gets quota information from the Fs
|
||||||
|
func (f *Fs) About(ctx context.Context) (*fs.Usage, error) {
|
||||||
|
info, err := f.client.StatFs()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &fs.Usage{
|
||||||
|
Total: fs.NewUsageValue(int64(info.Capacity)),
|
||||||
|
Used: fs.NewUsageValue(int64(info.Used)),
|
||||||
|
Free: fs.NewUsageValue(int64(info.Remaining)),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fs) ensureDirectory(realpath string) error {
|
||||||
|
info, err := f.client.Stat(realpath)
|
||||||
|
|
||||||
|
if e, ok := err.(*os.PathError); ok && e.Err == os.ErrNotExist {
|
||||||
|
return fs.ErrorDirNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !info.IsDir() {
|
||||||
|
return fs.ErrorDirNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fs) ensureFile(realpath string) (os.FileInfo, error) {
|
||||||
|
info, err := f.client.Stat(realpath)
|
||||||
|
|
||||||
|
if e, ok := err.(*os.PathError); ok && e.Err == os.ErrNotExist {
|
||||||
|
return nil, fs.ErrorObjectNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if info.IsDir() {
|
||||||
|
return nil, fs.ErrorObjectNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
return info, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fs) realpath(dir string) string {
|
||||||
|
return f.opt.Enc.FromStandardPath(xPath(f.Root(), dir))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check the interfaces are satisfied
|
||||||
|
var (
|
||||||
|
_ fs.Fs = (*Fs)(nil)
|
||||||
|
_ fs.Purger = (*Fs)(nil)
|
||||||
|
_ fs.PutStreamer = (*Fs)(nil)
|
||||||
|
_ fs.Abouter = (*Fs)(nil)
|
||||||
|
)
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
// +build !plan9
|
||||||
|
|
||||||
|
package hdfs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"path"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/rclone/rclone/fs"
|
||||||
|
"github.com/rclone/rclone/fs/config"
|
||||||
|
"github.com/rclone/rclone/lib/encoder"
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
fsi := &fs.RegInfo{
|
||||||
|
Name: "hdfs",
|
||||||
|
Description: "Hadoop distributed file system",
|
||||||
|
NewFs: NewFs,
|
||||||
|
Options: []fs.Option{{
|
||||||
|
Name: "namenode",
|
||||||
|
Help: "hadoop name node and port",
|
||||||
|
Required: true,
|
||||||
|
Examples: []fs.OptionExample{{
|
||||||
|
Value: "namenode:8020",
|
||||||
|
Help: "Connect to host namenode at port 8020",
|
||||||
|
}},
|
||||||
|
}, {
|
||||||
|
Name: "username",
|
||||||
|
Help: "hadoop user name",
|
||||||
|
Required: false,
|
||||||
|
Examples: []fs.OptionExample{{
|
||||||
|
Value: "root",
|
||||||
|
Help: "Connect to hdfs as root",
|
||||||
|
}},
|
||||||
|
}, {
|
||||||
|
Name: "service_principal_name",
|
||||||
|
Help: `Kerberos service principal name for the namenode
|
||||||
|
|
||||||
|
Enables KERBEROS authentication. Specifies the Service Principal Name
|
||||||
|
(<SERVICE>/<FQDN>) for the namenode.`,
|
||||||
|
Required: false,
|
||||||
|
Examples: []fs.OptionExample{{
|
||||||
|
Value: "hdfs/namenode.hadoop.docker",
|
||||||
|
Help: "Namenode running as service 'hdfs' with FQDN 'namenode.hadoop.docker'.",
|
||||||
|
}},
|
||||||
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: "data_transfer_protection",
|
||||||
|
Help: `Kerberos data transfer protection: authentication|integrity|privacy
|
||||||
|
|
||||||
|
Specifies whether or not authentication, data signature integrity
|
||||||
|
checks, and wire encryption is required when communicating the the
|
||||||
|
datanodes. Possible values are 'authentication', 'integrity' and
|
||||||
|
'privacy'. Used only with KERBEROS enabled.`,
|
||||||
|
Required: false,
|
||||||
|
Examples: []fs.OptionExample{{
|
||||||
|
Value: "privacy",
|
||||||
|
Help: "Ensure authentication, integrity and encryption enabled.",
|
||||||
|
}},
|
||||||
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: config.ConfigEncoding,
|
||||||
|
Help: config.ConfigEncodingHelp,
|
||||||
|
Advanced: true,
|
||||||
|
Default: (encoder.Display | encoder.EncodeInvalidUtf8 | encoder.EncodeColon),
|
||||||
|
}},
|
||||||
|
}
|
||||||
|
fs.Register(fsi)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Options for this backend
|
||||||
|
type Options struct {
|
||||||
|
Namenode string `config:"namenode"`
|
||||||
|
Username string `config:"username"`
|
||||||
|
ServicePrincipalName string `config:"service_principal_name"`
|
||||||
|
DataTransferProtection string `config:"data_transfer_protection"`
|
||||||
|
Enc encoder.MultiEncoder `config:"encoding"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// xPath make correct file path with leading '/'
|
||||||
|
func xPath(root string, tail string) string {
|
||||||
|
if !strings.HasPrefix(root, "/") {
|
||||||
|
root = "/" + root
|
||||||
|
}
|
||||||
|
return path.Join(root, tail)
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
// Test HDFS filesystem interface
|
||||||
|
|
||||||
|
// +build !plan9
|
||||||
|
|
||||||
|
package hdfs_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/rclone/rclone/backend/hdfs"
|
||||||
|
"github.com/rclone/rclone/fstest/fstests"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestIntegration runs integration tests against the remote
|
||||||
|
func TestIntegration(t *testing.T) {
|
||||||
|
fstests.Run(t, &fstests.Opt{
|
||||||
|
RemoteName: "TestHdfs:",
|
||||||
|
NilObject: (*hdfs.Object)(nil),
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
// Build for hdfs for unsupported platforms to stop go complaining
|
||||||
|
// about "no buildable Go source files "
|
||||||
|
|
||||||
|
// +build plan9
|
||||||
|
|
||||||
|
package hdfs
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
// +build !plan9
|
||||||
|
|
||||||
|
package hdfs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
"path"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/rclone/rclone/fs"
|
||||||
|
"github.com/rclone/rclone/fs/hash"
|
||||||
|
"github.com/rclone/rclone/lib/readers"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Object describes an HDFS file
|
||||||
|
type Object struct {
|
||||||
|
fs *Fs
|
||||||
|
remote string
|
||||||
|
size int64
|
||||||
|
modTime time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fs returns the parent Fs
|
||||||
|
func (o *Object) Fs() fs.Info {
|
||||||
|
return o.fs
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remote returns the remote path
|
||||||
|
func (o *Object) Remote() string {
|
||||||
|
return o.remote
|
||||||
|
}
|
||||||
|
|
||||||
|
// Size returns the size of an object in bytes
|
||||||
|
func (o *Object) Size() int64 {
|
||||||
|
return o.size
|
||||||
|
}
|
||||||
|
|
||||||
|
// ModTime returns the modification time of the object
|
||||||
|
func (o *Object) ModTime(ctx context.Context) time.Time {
|
||||||
|
return o.modTime
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetModTime sets the modification time of the local fs object
|
||||||
|
func (o *Object) SetModTime(ctx context.Context, modTime time.Time) error {
|
||||||
|
realpath := o.fs.realpath(o.Remote())
|
||||||
|
err := o.fs.client.Chtimes(realpath, modTime, modTime)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
o.modTime = modTime
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Storable returns whether this object is storable
|
||||||
|
func (o *Object) Storable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return a string version
|
||||||
|
func (o *Object) String() string {
|
||||||
|
if o == nil {
|
||||||
|
return "<nil>"
|
||||||
|
}
|
||||||
|
return o.Remote()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hash is not supported
|
||||||
|
func (o *Object) Hash(ctx context.Context, r hash.Type) (string, error) {
|
||||||
|
return "", hash.ErrUnsupported
|
||||||
|
}
|
||||||
|
|
||||||
|
// Open an object for read
|
||||||
|
func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.ReadCloser, err error) {
|
||||||
|
realpath := o.realpath()
|
||||||
|
fs.Debugf(o.fs, "open [%s]", realpath)
|
||||||
|
f, err := o.fs.client.Open(realpath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var offset, limit int64 = 0, -1
|
||||||
|
for _, option := range options {
|
||||||
|
switch x := option.(type) {
|
||||||
|
case *fs.SeekOption:
|
||||||
|
offset = x.Offset
|
||||||
|
case *fs.RangeOption:
|
||||||
|
offset, limit = x.Decode(o.Size())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = f.Seek(offset, io.SeekStart)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if limit != -1 {
|
||||||
|
in = readers.NewLimitedReadCloser(f, limit)
|
||||||
|
} else {
|
||||||
|
in = f
|
||||||
|
}
|
||||||
|
|
||||||
|
return in, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update object
|
||||||
|
func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) error {
|
||||||
|
realpath := o.fs.realpath(src.Remote())
|
||||||
|
dirname := path.Dir(realpath)
|
||||||
|
fs.Debugf(o.fs, "update [%s]", realpath)
|
||||||
|
|
||||||
|
err := o.fs.client.MkdirAll(dirname, 755)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
info, err := o.fs.client.Stat(realpath)
|
||||||
|
if err == nil {
|
||||||
|
err = o.fs.client.Remove(realpath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
out, err := o.fs.client.Create(realpath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
cleanup := func() {
|
||||||
|
rerr := o.fs.client.Remove(realpath)
|
||||||
|
if rerr != nil {
|
||||||
|
fs.Errorf(o.fs, "failed to remove [%v]: %v", realpath, rerr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = io.Copy(out, in)
|
||||||
|
if err != nil {
|
||||||
|
cleanup()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = out.Close()
|
||||||
|
if err != nil {
|
||||||
|
cleanup()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
info, err = o.fs.client.Stat(realpath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = o.SetModTime(ctx, src.ModTime(ctx))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
o.size = info.Size()
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove an object
|
||||||
|
func (o *Object) Remove(ctx context.Context) error {
|
||||||
|
realpath := o.fs.realpath(o.remote)
|
||||||
|
fs.Debugf(o.fs, "remove [%s]", realpath)
|
||||||
|
return o.fs.client.Remove(realpath)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o *Object) realpath() string {
|
||||||
|
return o.fs.opt.Enc.FromStandardPath(xPath(o.Fs().Root(), o.remote))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check the interfaces are satisfied
|
||||||
|
var (
|
||||||
|
_ fs.Object = (*Object)(nil)
|
||||||
|
)
|
||||||
+17
-18
@@ -58,7 +58,7 @@ The input format is comma separated list of key,value pairs. Standard
|
|||||||
|
|
||||||
For example to set a Cookie use 'Cookie,name=value', or '"Cookie","name=value"'.
|
For example to set a Cookie use 'Cookie,name=value', or '"Cookie","name=value"'.
|
||||||
|
|
||||||
You can set multiple headers, eg '"Cookie","name=value","Authorization","xxx"'.
|
You can set multiple headers, e.g. '"Cookie","name=value","Authorization","xxx"'.
|
||||||
`,
|
`,
|
||||||
Default: fs.CommaSepList{},
|
Default: fs.CommaSepList{},
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
@@ -115,8 +115,9 @@ type Options struct {
|
|||||||
type Fs struct {
|
type Fs struct {
|
||||||
name string
|
name string
|
||||||
root string
|
root string
|
||||||
features *fs.Features // optional features
|
features *fs.Features // optional features
|
||||||
opt Options // options for this backend
|
opt Options // options for this backend
|
||||||
|
ci *fs.ConfigInfo // global config
|
||||||
endpoint *url.URL
|
endpoint *url.URL
|
||||||
endpointURL string // endpoint as a string
|
endpointURL string // endpoint as a string
|
||||||
httpClient *http.Client
|
httpClient *http.Client
|
||||||
@@ -145,8 +146,7 @@ func statusError(res *http.Response, err error) error {
|
|||||||
|
|
||||||
// NewFs creates a new Fs object from the name and root. It connects to
|
// NewFs creates a new Fs object from the name and root. It connects to
|
||||||
// the host specified in the config file.
|
// the host specified in the config file.
|
||||||
func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {
|
||||||
ctx := context.TODO()
|
|
||||||
// Parse config into Options struct
|
// Parse config into Options struct
|
||||||
opt := new(Options)
|
opt := new(Options)
|
||||||
err := configstruct.Set(m, opt)
|
err := configstruct.Set(m, opt)
|
||||||
@@ -172,7 +172,7 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
client := fshttp.NewClient(fs.Config)
|
client := fshttp.NewClient(ctx)
|
||||||
|
|
||||||
var isFile = false
|
var isFile = false
|
||||||
if !strings.HasSuffix(u.String(), "/") {
|
if !strings.HasSuffix(u.String(), "/") {
|
||||||
@@ -183,9 +183,8 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
return http.ErrUseLastResponse
|
return http.ErrUseLastResponse
|
||||||
}
|
}
|
||||||
// check to see if points to a file
|
// check to see if points to a file
|
||||||
req, err := http.NewRequest("HEAD", u.String(), nil)
|
req, err := http.NewRequestWithContext(ctx, "HEAD", u.String(), nil)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
req = req.WithContext(ctx) // go1.13 can use NewRequestWithContext
|
|
||||||
addHeaders(req, opt)
|
addHeaders(req, opt)
|
||||||
res, err := noRedir.Do(req)
|
res, err := noRedir.Do(req)
|
||||||
err = statusError(res, err)
|
err = statusError(res, err)
|
||||||
@@ -210,17 +209,19 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ci := fs.GetConfig(ctx)
|
||||||
f := &Fs{
|
f := &Fs{
|
||||||
name: name,
|
name: name,
|
||||||
root: root,
|
root: root,
|
||||||
opt: *opt,
|
opt: *opt,
|
||||||
|
ci: ci,
|
||||||
httpClient: client,
|
httpClient: client,
|
||||||
endpoint: u,
|
endpoint: u,
|
||||||
endpointURL: u.String(),
|
endpointURL: u.String(),
|
||||||
}
|
}
|
||||||
f.features = (&fs.Features{
|
f.features = (&fs.Features{
|
||||||
CanHaveEmptyDirectories: true,
|
CanHaveEmptyDirectories: true,
|
||||||
}).Fill(f)
|
}).Fill(ctx, f)
|
||||||
if isFile {
|
if isFile {
|
||||||
return f, fs.ErrorIsFile
|
return f, fs.ErrorIsFile
|
||||||
}
|
}
|
||||||
@@ -389,11 +390,10 @@ func (f *Fs) readDir(ctx context.Context, dir string) (names []string, err error
|
|||||||
return nil, errors.Errorf("internal error: readDir URL %q didn't end in /", URL)
|
return nil, errors.Errorf("internal error: readDir URL %q didn't end in /", URL)
|
||||||
}
|
}
|
||||||
// Do the request
|
// Do the request
|
||||||
req, err := http.NewRequest("GET", URL, nil)
|
req, err := http.NewRequestWithContext(ctx, "GET", URL, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "readDir failed")
|
return nil, errors.Wrap(err, "readDir failed")
|
||||||
}
|
}
|
||||||
req = req.WithContext(ctx) // go1.13 can use NewRequestWithContext
|
|
||||||
f.addHeaders(req)
|
f.addHeaders(req)
|
||||||
res, err := f.httpClient.Do(req)
|
res, err := f.httpClient.Do(req)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
@@ -440,14 +440,15 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
|
|||||||
var (
|
var (
|
||||||
entriesMu sync.Mutex // to protect entries
|
entriesMu sync.Mutex // to protect entries
|
||||||
wg sync.WaitGroup
|
wg sync.WaitGroup
|
||||||
in = make(chan string, fs.Config.Checkers)
|
checkers = f.ci.Checkers
|
||||||
|
in = make(chan string, checkers)
|
||||||
)
|
)
|
||||||
add := func(entry fs.DirEntry) {
|
add := func(entry fs.DirEntry) {
|
||||||
entriesMu.Lock()
|
entriesMu.Lock()
|
||||||
entries = append(entries, entry)
|
entries = append(entries, entry)
|
||||||
entriesMu.Unlock()
|
entriesMu.Unlock()
|
||||||
}
|
}
|
||||||
for i := 0; i < fs.Config.Checkers; i++ {
|
for i := 0; i < checkers; i++ {
|
||||||
wg.Add(1)
|
wg.Add(1)
|
||||||
go func() {
|
go func() {
|
||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
@@ -544,11 +545,10 @@ func (o *Object) stat(ctx context.Context) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
url := o.url()
|
url := o.url()
|
||||||
req, err := http.NewRequest("HEAD", url, nil)
|
req, err := http.NewRequestWithContext(ctx, "HEAD", url, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.Wrap(err, "stat failed")
|
return errors.Wrap(err, "stat failed")
|
||||||
}
|
}
|
||||||
req = req.WithContext(ctx) // go1.13 can use NewRequestWithContext
|
|
||||||
o.fs.addHeaders(req)
|
o.fs.addHeaders(req)
|
||||||
res, err := o.fs.httpClient.Do(req)
|
res, err := o.fs.httpClient.Do(req)
|
||||||
if err == nil && res.StatusCode == http.StatusNotFound {
|
if err == nil && res.StatusCode == http.StatusNotFound {
|
||||||
@@ -585,7 +585,7 @@ func (o *Object) SetModTime(ctx context.Context, modTime time.Time) error {
|
|||||||
return errorReadOnly
|
return errorReadOnly
|
||||||
}
|
}
|
||||||
|
|
||||||
// Storable returns whether the remote http file is a regular file (not a directory, symbolic link, block device, character device, named pipe, etc)
|
// Storable returns whether the remote http file is a regular file (not a directory, symbolic link, block device, character device, named pipe, etc.)
|
||||||
func (o *Object) Storable() bool {
|
func (o *Object) Storable() bool {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@@ -593,11 +593,10 @@ func (o *Object) Storable() bool {
|
|||||||
// Open a remote http file object for reading. Seek is supported
|
// Open a remote http file object for reading. Seek is supported
|
||||||
func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.ReadCloser, err error) {
|
func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.ReadCloser, err error) {
|
||||||
url := o.url()
|
url := o.url()
|
||||||
req, err := http.NewRequest("GET", url, nil)
|
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "Open failed")
|
return nil, errors.Wrap(err, "Open failed")
|
||||||
}
|
}
|
||||||
req = req.WithContext(ctx) // go1.13 can use NewRequestWithContext
|
|
||||||
|
|
||||||
// Add optional headers
|
// Add optional headers
|
||||||
for k, v := range fs.OpenOptionHeaders(options) {
|
for k, v := range fs.OpenOptionHeaders(options) {
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ func prepareServer(t *testing.T) (configmap.Simple, func()) {
|
|||||||
ts := httptest.NewServer(handler)
|
ts := httptest.NewServer(handler)
|
||||||
|
|
||||||
// Configure the remote
|
// Configure the remote
|
||||||
config.LoadConfig()
|
config.LoadConfig(context.Background())
|
||||||
// fs.Config.LogLevel = fs.LogLevelDebug
|
// fs.Config.LogLevel = fs.LogLevelDebug
|
||||||
// fs.Config.DumpHeaders = true
|
// fs.Config.DumpHeaders = true
|
||||||
// fs.Config.DumpBodies = true
|
// fs.Config.DumpBodies = true
|
||||||
@@ -69,7 +69,7 @@ func prepare(t *testing.T) (fs.Fs, func()) {
|
|||||||
m, tidy := prepareServer(t)
|
m, tidy := prepareServer(t)
|
||||||
|
|
||||||
// Instantiate it
|
// Instantiate it
|
||||||
f, err := NewFs(remoteName, "", m)
|
f, err := NewFs(context.Background(), remoteName, "", m)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
return f, tidy
|
return f, tidy
|
||||||
@@ -166,8 +166,7 @@ func TestNewObject(t *testing.T) {
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
tFile := fi.ModTime()
|
tFile := fi.ModTime()
|
||||||
|
|
||||||
dt, ok := fstest.CheckTimeEqualWithPrecision(tObj, tFile, time.Second)
|
fstest.AssertTimeEqualWithPrecision(t, o.Remote(), tFile, tObj, time.Second)
|
||||||
assert.True(t, ok, fmt.Sprintf("%s: Modification time difference too big |%s| > %s (%s vs %s) (precision %s)", o.Remote(), dt, time.Second, tObj, tFile, time.Second))
|
|
||||||
|
|
||||||
// check object not found
|
// check object not found
|
||||||
o, err = f.NewObject(context.Background(), "not found.txt")
|
o, err = f.NewObject(context.Background(), "not found.txt")
|
||||||
@@ -215,7 +214,7 @@ func TestIsAFileRoot(t *testing.T) {
|
|||||||
m, tidy := prepareServer(t)
|
m, tidy := prepareServer(t)
|
||||||
defer tidy()
|
defer tidy()
|
||||||
|
|
||||||
f, err := NewFs(remoteName, "one%.txt", m)
|
f, err := NewFs(context.Background(), remoteName, "one%.txt", m)
|
||||||
assert.Equal(t, err, fs.ErrorIsFile)
|
assert.Equal(t, err, fs.ErrorIsFile)
|
||||||
|
|
||||||
testListRoot(t, f, false)
|
testListRoot(t, f, false)
|
||||||
@@ -225,7 +224,7 @@ func TestIsAFileSubDir(t *testing.T) {
|
|||||||
m, tidy := prepareServer(t)
|
m, tidy := prepareServer(t)
|
||||||
defer tidy()
|
defer tidy()
|
||||||
|
|
||||||
f, err := NewFs(remoteName, "three/underthree.txt", m)
|
f, err := NewFs(context.Background(), remoteName, "three/underthree.txt", m)
|
||||||
assert.Equal(t, err, fs.ErrorIsFile)
|
assert.Equal(t, err, fs.ErrorIsFile)
|
||||||
|
|
||||||
entries, err := f.List(context.Background(), "")
|
entries, err := f.List(context.Background(), "")
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/ncw/swift"
|
"github.com/ncw/swift/v2"
|
||||||
"github.com/rclone/rclone/fs"
|
"github.com/rclone/rclone/fs"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -21,10 +21,10 @@ func newAuth(f *Fs) *auth {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Request constructs a http.Request for authentication
|
// Request constructs an http.Request for authentication
|
||||||
//
|
//
|
||||||
// returns nil for not needed
|
// returns nil for not needed
|
||||||
func (a *auth) Request(*swift.Connection) (r *http.Request, err error) {
|
func (a *auth) Request(ctx context.Context, c *swift.Connection) (r *http.Request, err error) {
|
||||||
const retries = 10
|
const retries = 10
|
||||||
for try := 1; try <= retries; try++ {
|
for try := 1; try <= retries; try++ {
|
||||||
err = a.f.getCredentials(context.TODO())
|
err = a.f.getCredentials(context.TODO())
|
||||||
@@ -38,7 +38,7 @@ func (a *auth) Request(*swift.Connection) (r *http.Request, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Response parses the result of an http request
|
// Response parses the result of an http request
|
||||||
func (a *auth) Response(resp *http.Response) error {
|
func (a *auth) Response(ctx context.Context, resp *http.Response) error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+18
-25
@@ -4,7 +4,7 @@ package hubic
|
|||||||
|
|
||||||
// This uses the normal swift mechanism to update the credentials and
|
// This uses the normal swift mechanism to update the credentials and
|
||||||
// ignores the expires field returned by the Hubic API. This may need
|
// ignores the expires field returned by the Hubic API. This may need
|
||||||
// to be revisted after some actual experience.
|
// to be revisited after some actual experience.
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -16,11 +16,10 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
swiftLib "github.com/ncw/swift"
|
swiftLib "github.com/ncw/swift/v2"
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"github.com/rclone/rclone/backend/swift"
|
"github.com/rclone/rclone/backend/swift"
|
||||||
"github.com/rclone/rclone/fs"
|
"github.com/rclone/rclone/fs"
|
||||||
"github.com/rclone/rclone/fs/config"
|
|
||||||
"github.com/rclone/rclone/fs/config/configmap"
|
"github.com/rclone/rclone/fs/config/configmap"
|
||||||
"github.com/rclone/rclone/fs/config/configstruct"
|
"github.com/rclone/rclone/fs/config/configstruct"
|
||||||
"github.com/rclone/rclone/fs/config/obscure"
|
"github.com/rclone/rclone/fs/config/obscure"
|
||||||
@@ -39,7 +38,7 @@ var (
|
|||||||
// Description of how to auth for this app
|
// Description of how to auth for this app
|
||||||
oauthConfig = &oauth2.Config{
|
oauthConfig = &oauth2.Config{
|
||||||
Scopes: []string{
|
Scopes: []string{
|
||||||
"credentials.r", // Read Openstack credentials
|
"credentials.r", // Read OpenStack credentials
|
||||||
},
|
},
|
||||||
Endpoint: oauth2.Endpoint{
|
Endpoint: oauth2.Endpoint{
|
||||||
AuthURL: "https://api.hubic.com/oauth/auth/",
|
AuthURL: "https://api.hubic.com/oauth/auth/",
|
||||||
@@ -57,28 +56,22 @@ func init() {
|
|||||||
Name: "hubic",
|
Name: "hubic",
|
||||||
Description: "Hubic",
|
Description: "Hubic",
|
||||||
NewFs: NewFs,
|
NewFs: NewFs,
|
||||||
Config: func(name string, m configmap.Mapper) {
|
Config: func(ctx context.Context, name string, m configmap.Mapper) {
|
||||||
err := oauthutil.Config("hubic", name, m, oauthConfig)
|
err := oauthutil.Config(ctx, "hubic", name, m, oauthConfig, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Failed to configure token: %v", err)
|
log.Fatalf("Failed to configure token: %v", err)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
Options: append([]fs.Option{{
|
Options: append(oauthutil.SharedOptions, swift.SharedOptions...),
|
||||||
Name: config.ConfigClientID,
|
|
||||||
Help: "Hubic Client Id\nLeave blank normally.",
|
|
||||||
}, {
|
|
||||||
Name: config.ConfigClientSecret,
|
|
||||||
Help: "Hubic Client Secret\nLeave blank normally.",
|
|
||||||
}}, swift.SharedOptions...),
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// credentials is the JSON returned from the Hubic API to read the
|
// credentials is the JSON returned from the Hubic API to read the
|
||||||
// OpenStack credentials
|
// OpenStack credentials
|
||||||
type credentials struct {
|
type credentials struct {
|
||||||
Token string `json:"token"` // Openstack token
|
Token string `json:"token"` // OpenStack token
|
||||||
Endpoint string `json:"endpoint"` // Openstack endpoint
|
Endpoint string `json:"endpoint"` // OpenStack endpoint
|
||||||
Expires string `json:"expires"` // Expires date - eg "2015-11-09T14:24:56+01:00"
|
Expires string `json:"expires"` // Expires date - e.g. "2015-11-09T14:24:56+01:00"
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fs represents a remote hubic
|
// Fs represents a remote hubic
|
||||||
@@ -117,11 +110,10 @@ func (f *Fs) String() string {
|
|||||||
//
|
//
|
||||||
// The credentials are read into the Fs
|
// The credentials are read into the Fs
|
||||||
func (f *Fs) getCredentials(ctx context.Context) (err error) {
|
func (f *Fs) getCredentials(ctx context.Context) (err error) {
|
||||||
req, err := http.NewRequest("GET", "https://api.hubic.com/1.0/account/credentials", nil)
|
req, err := http.NewRequestWithContext(ctx, "GET", "https://api.hubic.com/1.0/account/credentials", nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
req = req.WithContext(ctx) // go1.13 can use NewRequestWithContext
|
|
||||||
resp, err := f.client.Do(req)
|
resp, err := f.client.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -153,8 +145,8 @@ func (f *Fs) getCredentials(ctx context.Context) (err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// NewFs constructs an Fs from the path, container:path
|
// NewFs constructs an Fs from the path, container:path
|
||||||
func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {
|
||||||
client, _, err := oauthutil.NewClient(name, m, oauthConfig)
|
client, _, err := oauthutil.NewClient(ctx, name, m, oauthConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "failed to configure Hubic")
|
return nil, errors.Wrap(err, "failed to configure Hubic")
|
||||||
}
|
}
|
||||||
@@ -164,13 +156,14 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Make the swift Connection
|
// Make the swift Connection
|
||||||
|
ci := fs.GetConfig(ctx)
|
||||||
c := &swiftLib.Connection{
|
c := &swiftLib.Connection{
|
||||||
Auth: newAuth(f),
|
Auth: newAuth(f),
|
||||||
ConnectTimeout: 10 * fs.Config.ConnectTimeout, // Use the timeouts in the transport
|
ConnectTimeout: 10 * ci.ConnectTimeout, // Use the timeouts in the transport
|
||||||
Timeout: 10 * fs.Config.Timeout, // Use the timeouts in the transport
|
Timeout: 10 * ci.Timeout, // Use the timeouts in the transport
|
||||||
Transport: fshttp.NewTransport(fs.Config),
|
Transport: fshttp.NewTransport(ctx),
|
||||||
}
|
}
|
||||||
err = c.Authenticate()
|
err = c.Authenticate(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "error authenticating swift connection")
|
return nil, errors.Wrap(err, "error authenticating swift connection")
|
||||||
}
|
}
|
||||||
@@ -183,7 +176,7 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Make inner swift Fs from the connection
|
// Make inner swift Fs from the connection
|
||||||
swiftFs, err := swift.NewFsWithConnection(opt, name, root, c, true)
|
swiftFs, err := swift.NewFsWithConnection(ctx, opt, name, root, c, true)
|
||||||
if err != nil && err != fs.ErrorIsFile {
|
if err != nil && err != fs.ErrorIsFile {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -153,9 +153,9 @@ type CustomerInfo struct {
|
|||||||
AccountType string `json:"account_type"`
|
AccountType string `json:"account_type"`
|
||||||
SubscriptionType string `json:"subscription_type"`
|
SubscriptionType string `json:"subscription_type"`
|
||||||
Usage int64 `json:"usage"`
|
Usage int64 `json:"usage"`
|
||||||
Qouta int64 `json:"quota"`
|
Quota int64 `json:"quota"`
|
||||||
BusinessUsage int64 `json:"business_usage"`
|
BusinessUsage int64 `json:"business_usage"`
|
||||||
BusinessQouta int64 `json:"business_quota"`
|
BusinessQuota int64 `json:"business_quota"`
|
||||||
WriteLocked bool `json:"write_locked"`
|
WriteLocked bool `json:"write_locked"`
|
||||||
ReadLocked bool `json:"read_locked"`
|
ReadLocked bool `json:"read_locked"`
|
||||||
LockedCause interface{} `json:"locked_cause"`
|
LockedCause interface{} `json:"locked_cause"`
|
||||||
@@ -164,6 +164,12 @@ type CustomerInfo struct {
|
|||||||
IOSHash string `json:"ios_hash"`
|
IOSHash string `json:"ios_hash"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TrashResponse is returned when emptying the Trash
|
||||||
|
type TrashResponse struct {
|
||||||
|
Folders int64 `json:"folders"`
|
||||||
|
Files int64 `json:"files"`
|
||||||
|
}
|
||||||
|
|
||||||
// XML structures returned by the old API
|
// XML structures returned by the old API
|
||||||
|
|
||||||
// Flag is a hacky type for checking if an attribute is present
|
// Flag is a hacky type for checking if an attribute is present
|
||||||
@@ -380,7 +386,7 @@ type Error struct {
|
|||||||
Cause string `xml:"cause"`
|
Cause string `xml:"cause"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Error returns a string for the error and statistifes the error interface
|
// Error returns a string for the error and satisfies the error interface
|
||||||
func (e *Error) Error() string {
|
func (e *Error) Error() string {
|
||||||
out := fmt.Sprintf("error %d", e.StatusCode)
|
out := fmt.Sprintf("error %d", e.StatusCode)
|
||||||
if e.Message != "" {
|
if e.Message != "" {
|
||||||
|
|||||||
+409
-116
@@ -11,6 +11,7 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"log"
|
"log"
|
||||||
|
"math/rand"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
@@ -26,41 +27,51 @@ import (
|
|||||||
"github.com/rclone/rclone/fs/config"
|
"github.com/rclone/rclone/fs/config"
|
||||||
"github.com/rclone/rclone/fs/config/configmap"
|
"github.com/rclone/rclone/fs/config/configmap"
|
||||||
"github.com/rclone/rclone/fs/config/configstruct"
|
"github.com/rclone/rclone/fs/config/configstruct"
|
||||||
"github.com/rclone/rclone/fs/encodings"
|
"github.com/rclone/rclone/fs/config/obscure"
|
||||||
"github.com/rclone/rclone/fs/fserrors"
|
"github.com/rclone/rclone/fs/fserrors"
|
||||||
"github.com/rclone/rclone/fs/fshttp"
|
"github.com/rclone/rclone/fs/fshttp"
|
||||||
"github.com/rclone/rclone/fs/hash"
|
"github.com/rclone/rclone/fs/hash"
|
||||||
"github.com/rclone/rclone/fs/walk"
|
"github.com/rclone/rclone/fs/walk"
|
||||||
|
"github.com/rclone/rclone/lib/encoder"
|
||||||
"github.com/rclone/rclone/lib/oauthutil"
|
"github.com/rclone/rclone/lib/oauthutil"
|
||||||
"github.com/rclone/rclone/lib/pacer"
|
"github.com/rclone/rclone/lib/pacer"
|
||||||
"github.com/rclone/rclone/lib/rest"
|
"github.com/rclone/rclone/lib/rest"
|
||||||
"golang.org/x/oauth2"
|
"golang.org/x/oauth2"
|
||||||
)
|
)
|
||||||
|
|
||||||
const enc = encodings.JottaCloud
|
|
||||||
|
|
||||||
// Globals
|
// Globals
|
||||||
const (
|
const (
|
||||||
minSleep = 10 * time.Millisecond
|
minSleep = 10 * time.Millisecond
|
||||||
maxSleep = 2 * time.Second
|
maxSleep = 2 * time.Second
|
||||||
decayConstant = 2 // bigger for slower decay, exponential
|
decayConstant = 2 // bigger for slower decay, exponential
|
||||||
defaultDevice = "Jotta"
|
defaultDevice = "Jotta"
|
||||||
defaultMountpoint = "Archive"
|
defaultMountpoint = "Archive"
|
||||||
rootURL = "https://www.jottacloud.com/jfs/"
|
rootURL = "https://jfs.jottacloud.com/jfs/"
|
||||||
apiURL = "https://api.jottacloud.com/"
|
apiURL = "https://api.jottacloud.com/"
|
||||||
baseURL = "https://www.jottacloud.com/"
|
baseURL = "https://www.jottacloud.com/"
|
||||||
defaultTokenURL = "https://id.jottacloud.com/auth/realms/jottacloud/protocol/openid-connect/token"
|
defaultTokenURL = "https://id.jottacloud.com/auth/realms/jottacloud/protocol/openid-connect/token"
|
||||||
cachePrefix = "rclone-jcmd5-"
|
cachePrefix = "rclone-jcmd5-"
|
||||||
configDevice = "device"
|
configDevice = "device"
|
||||||
configMountpoint = "mountpoint"
|
configMountpoint = "mountpoint"
|
||||||
configTokenURL = "tokenURL"
|
configTokenURL = "tokenURL"
|
||||||
configVersion = 1
|
configClientID = "client_id"
|
||||||
|
configClientSecret = "client_secret"
|
||||||
|
configVersion = 1
|
||||||
|
|
||||||
|
v1tokenURL = "https://api.jottacloud.com/auth/v1/token"
|
||||||
|
v1registerURL = "https://api.jottacloud.com/auth/v1/register"
|
||||||
|
v1ClientID = "nibfk8biu12ju7hpqomr8b1e40"
|
||||||
|
v1EncryptedClientSecret = "Vp8eAv7eVElMnQwN-kgU9cbhgApNDaMqWdlDi5qFydlQoji4JBxrGMF2"
|
||||||
|
v1configVersion = 0
|
||||||
|
|
||||||
|
teliaCloudTokenURL = "https://cloud-auth.telia.se/auth/realms/telia_se/protocol/openid-connect/token"
|
||||||
|
teliaCloudAuthURL = "https://cloud-auth.telia.se/auth/realms/telia_se/protocol/openid-connect/auth"
|
||||||
|
teliaCloudClientID = "desktop"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
// Description of how to auth for this app for a personal account
|
// Description of how to auth for this app for a personal account
|
||||||
oauthConfig = &oauth2.Config{
|
oauthConfig = &oauth2.Config{
|
||||||
ClientID: "jottacli",
|
|
||||||
Endpoint: oauth2.Endpoint{
|
Endpoint: oauth2.Endpoint{
|
||||||
AuthURL: defaultTokenURL,
|
AuthURL: defaultTokenURL,
|
||||||
TokenURL: defaultTokenURL,
|
TokenURL: defaultTokenURL,
|
||||||
@@ -74,18 +85,16 @@ func init() {
|
|||||||
// needs to be done early so we can use oauth during config
|
// needs to be done early so we can use oauth during config
|
||||||
fs.Register(&fs.RegInfo{
|
fs.Register(&fs.RegInfo{
|
||||||
Name: "jottacloud",
|
Name: "jottacloud",
|
||||||
Description: "JottaCloud",
|
Description: "Jottacloud",
|
||||||
NewFs: NewFs,
|
NewFs: NewFs,
|
||||||
Config: func(name string, m configmap.Mapper) {
|
Config: func(ctx context.Context, name string, m configmap.Mapper) {
|
||||||
ctx := context.TODO()
|
|
||||||
|
|
||||||
refresh := false
|
refresh := false
|
||||||
if version, ok := m.Get("configVersion"); ok {
|
if version, ok := m.Get("configVersion"); ok {
|
||||||
ver, err := strconv.Atoi(version)
|
ver, err := strconv.Atoi(version)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Failed to parse config version - corrupted config")
|
log.Fatalf("Failed to parse config version - corrupted config")
|
||||||
}
|
}
|
||||||
refresh = ver != configVersion
|
refresh = (ver != configVersion) && (ver != v1configVersion)
|
||||||
}
|
}
|
||||||
|
|
||||||
if refresh {
|
if refresh {
|
||||||
@@ -100,42 +109,19 @@ func init() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
clientConfig := *fs.Config
|
fmt.Printf("Choose authentication type:\n" +
|
||||||
clientConfig.UserAgent = "JottaCli 0.6.18626 windows-amd64"
|
"1: Standard authentication - use this if you're a normal Jottacloud user.\n" +
|
||||||
srv := rest.NewClient(fshttp.NewClient(&clientConfig))
|
"2: Legacy authentication - this is only required for certain whitelabel versions of Jottacloud and not recommended for normal users.\n" +
|
||||||
|
"3: Telia Cloud authentication - use this if you are using Telia Cloud.\n")
|
||||||
|
|
||||||
fmt.Printf("Generate a personal login token here: https://www.jottacloud.com/web/secure\n")
|
switch config.ChooseNumber("Your choice", 1, 3) {
|
||||||
fmt.Printf("Login Token> ")
|
case 1:
|
||||||
loginToken := config.ReadLine()
|
v2config(ctx, name, m)
|
||||||
|
case 2:
|
||||||
token, err := doAuth(ctx, srv, loginToken, m)
|
v1config(ctx, name, m)
|
||||||
if err != nil {
|
case 3:
|
||||||
log.Fatalf("Failed to get oauth token: %s", err)
|
teliaCloudConfig(ctx, name, m)
|
||||||
}
|
}
|
||||||
err = oauthutil.PutToken(name, m, &token, true)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("Error while saving token: %s", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
fmt.Printf("\nDo you want to use a non standard device/mountpoint e.g. for accessing files uploaded using the official Jottacloud client?\n\n")
|
|
||||||
if config.Confirm(false) {
|
|
||||||
oAuthClient, _, err := oauthutil.NewClient(name, m, oauthConfig)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("Failed to load oAuthClient: %s", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
srv = rest.NewClient(oAuthClient).SetRoot(rootURL)
|
|
||||||
apiSrv := rest.NewClient(oAuthClient).SetRoot(apiURL)
|
|
||||||
|
|
||||||
device, mountpoint, err := setupMountpoint(ctx, srv, apiSrv)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("Failed to setup mountpoint: %s", err)
|
|
||||||
}
|
|
||||||
m.Set(configDevice, device)
|
|
||||||
m.Set(configMountpoint, mountpoint)
|
|
||||||
}
|
|
||||||
|
|
||||||
m.Set("configVersion", strconv.Itoa(configVersion))
|
|
||||||
},
|
},
|
||||||
Options: []fs.Option{{
|
Options: []fs.Option{{
|
||||||
Name: "md5_memory_limit",
|
Name: "md5_memory_limit",
|
||||||
@@ -143,13 +129,13 @@ func init() {
|
|||||||
Default: fs.SizeSuffix(10 * 1024 * 1024),
|
Default: fs.SizeSuffix(10 * 1024 * 1024),
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
}, {
|
}, {
|
||||||
Name: "hard_delete",
|
Name: "trashed_only",
|
||||||
Help: "Delete files permanently rather than putting them into the trash.",
|
Help: "Only show files that are in the trash.\nThis will show trashed files in their original directory structure.",
|
||||||
Default: false,
|
Default: false,
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
}, {
|
}, {
|
||||||
Name: "unlink",
|
Name: "hard_delete",
|
||||||
Help: "Remove existing public link to file/folder with link command rather than creating.\nDefault is false, meaning link command will create or retrieve public link.",
|
Help: "Delete files permanently rather than putting them into the trash.",
|
||||||
Default: false,
|
Default: false,
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
}, {
|
}, {
|
||||||
@@ -157,18 +143,29 @@ func init() {
|
|||||||
Help: "Files bigger than this can be resumed if the upload fail's.",
|
Help: "Files bigger than this can be resumed if the upload fail's.",
|
||||||
Default: fs.SizeSuffix(10 * 1024 * 1024),
|
Default: fs.SizeSuffix(10 * 1024 * 1024),
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: config.ConfigEncoding,
|
||||||
|
Help: config.ConfigEncodingHelp,
|
||||||
|
Advanced: true,
|
||||||
|
// Encode invalid UTF-8 bytes as xml doesn't handle them properly.
|
||||||
|
//
|
||||||
|
// Also: '*', '/', ':', '<', '>', '?', '\"', '\x00', '|'
|
||||||
|
Default: (encoder.Display |
|
||||||
|
encoder.EncodeWin | // :?"*<>|
|
||||||
|
encoder.EncodeInvalidUtf8),
|
||||||
}},
|
}},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Options defines the configuration for this backend
|
// Options defines the configuration for this backend
|
||||||
type Options struct {
|
type Options struct {
|
||||||
Device string `config:"device"`
|
Device string `config:"device"`
|
||||||
Mountpoint string `config:"mountpoint"`
|
Mountpoint string `config:"mountpoint"`
|
||||||
MD5MemoryThreshold fs.SizeSuffix `config:"md5_memory_limit"`
|
MD5MemoryThreshold fs.SizeSuffix `config:"md5_memory_limit"`
|
||||||
HardDelete bool `config:"hard_delete"`
|
TrashedOnly bool `config:"trashed_only"`
|
||||||
Unlink bool `config:"unlink"`
|
HardDelete bool `config:"hard_delete"`
|
||||||
UploadThreshold fs.SizeSuffix `config:"upload_resume_limit"`
|
UploadThreshold fs.SizeSuffix `config:"upload_resume_limit"`
|
||||||
|
Enc encoder.MultiEncoder `config:"encoding"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fs represents a remote jottacloud
|
// Fs represents a remote jottacloud
|
||||||
@@ -220,7 +217,7 @@ func (f *Fs) Features() *fs.Features {
|
|||||||
return f.features
|
return f.features
|
||||||
}
|
}
|
||||||
|
|
||||||
// parsePath parses an box 'url'
|
// parsePath parses a box 'url'
|
||||||
func parsePath(path string) (root string) {
|
func parsePath(path string) (root string) {
|
||||||
root = strings.Trim(path, "/")
|
root = strings.Trim(path, "/")
|
||||||
return
|
return
|
||||||
@@ -242,9 +239,224 @@ func shouldRetry(resp *http.Response, err error) (bool, error) {
|
|||||||
return fserrors.ShouldRetry(err) || fserrors.ShouldRetryHTTP(resp, retryErrorCodes), err
|
return fserrors.ShouldRetry(err) || fserrors.ShouldRetryHTTP(resp, retryErrorCodes), err
|
||||||
}
|
}
|
||||||
|
|
||||||
// doAuth runs the actual token request
|
func teliaCloudConfig(ctx context.Context, name string, m configmap.Mapper) {
|
||||||
func doAuth(ctx context.Context, srv *rest.Client, loginTokenBase64 string, m configmap.Mapper) (token oauth2.Token, err error) {
|
teliaCloudOauthConfig := &oauth2.Config{
|
||||||
loginTokenBytes, err := base64.StdEncoding.DecodeString(loginTokenBase64)
|
Endpoint: oauth2.Endpoint{
|
||||||
|
AuthURL: teliaCloudAuthURL,
|
||||||
|
TokenURL: teliaCloudTokenURL,
|
||||||
|
},
|
||||||
|
ClientID: teliaCloudClientID,
|
||||||
|
Scopes: []string{"openid", "jotta-default", "offline_access"},
|
||||||
|
RedirectURL: oauthutil.RedirectLocalhostURL,
|
||||||
|
}
|
||||||
|
|
||||||
|
err := oauthutil.Config(ctx, "jottacloud", name, m, teliaCloudOauthConfig, nil)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to configure token: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("\nDo you want to use a non standard device/mountpoint e.g. for accessing files uploaded using the official Jottacloud client?\n\n")
|
||||||
|
if config.Confirm(false) {
|
||||||
|
oAuthClient, _, err := oauthutil.NewClient(ctx, name, m, teliaCloudOauthConfig)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to load oAuthClient: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
srv := rest.NewClient(oAuthClient).SetRoot(rootURL)
|
||||||
|
apiSrv := rest.NewClient(oAuthClient).SetRoot(apiURL)
|
||||||
|
|
||||||
|
device, mountpoint, err := setupMountpoint(ctx, srv, apiSrv)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to setup mountpoint: %s", err)
|
||||||
|
}
|
||||||
|
m.Set(configDevice, device)
|
||||||
|
m.Set(configMountpoint, mountpoint)
|
||||||
|
}
|
||||||
|
|
||||||
|
m.Set("configVersion", strconv.Itoa(configVersion))
|
||||||
|
m.Set(configClientID, teliaCloudClientID)
|
||||||
|
m.Set(configTokenURL, teliaCloudTokenURL)
|
||||||
|
}
|
||||||
|
|
||||||
|
// v1config configure a jottacloud backend using legacy authentication
|
||||||
|
func v1config(ctx context.Context, name string, m configmap.Mapper) {
|
||||||
|
srv := rest.NewClient(fshttp.NewClient(ctx))
|
||||||
|
|
||||||
|
fmt.Printf("\nDo you want to create a machine specific API key?\n\nRclone has it's own Jottacloud API KEY which works fine as long as one only uses rclone on a single machine. When you want to use rclone with this account on more than one machine it's recommended to create a machine specific API key. These keys can NOT be shared between machines.\n\n")
|
||||||
|
if config.Confirm(false) {
|
||||||
|
deviceRegistration, err := registerDevice(ctx, srv)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to register device: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
m.Set(configClientID, deviceRegistration.ClientID)
|
||||||
|
m.Set(configClientSecret, obscure.MustObscure(deviceRegistration.ClientSecret))
|
||||||
|
fs.Debugf(nil, "Got clientID '%s' and clientSecret '%s'", deviceRegistration.ClientID, deviceRegistration.ClientSecret)
|
||||||
|
}
|
||||||
|
|
||||||
|
clientID, ok := m.Get(configClientID)
|
||||||
|
if !ok {
|
||||||
|
clientID = v1ClientID
|
||||||
|
}
|
||||||
|
clientSecret, ok := m.Get(configClientSecret)
|
||||||
|
if !ok {
|
||||||
|
clientSecret = v1EncryptedClientSecret
|
||||||
|
}
|
||||||
|
oauthConfig.ClientID = clientID
|
||||||
|
oauthConfig.ClientSecret = obscure.MustReveal(clientSecret)
|
||||||
|
|
||||||
|
oauthConfig.Endpoint.AuthURL = v1tokenURL
|
||||||
|
oauthConfig.Endpoint.TokenURL = v1tokenURL
|
||||||
|
|
||||||
|
fmt.Printf("Username> ")
|
||||||
|
username := config.ReadLine()
|
||||||
|
password := config.GetPassword("Your Jottacloud password is only required during setup and will not be stored.")
|
||||||
|
|
||||||
|
token, err := doAuthV1(ctx, srv, username, password)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to get oauth token: %s", err)
|
||||||
|
}
|
||||||
|
err = oauthutil.PutToken(name, m, &token, true)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Error while saving token: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("\nDo you want to use a non standard device/mountpoint e.g. for accessing files uploaded using the official Jottacloud client?\n\n")
|
||||||
|
if config.Confirm(false) {
|
||||||
|
oAuthClient, _, err := oauthutil.NewClient(ctx, name, m, oauthConfig)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to load oAuthClient: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
srv = rest.NewClient(oAuthClient).SetRoot(rootURL)
|
||||||
|
apiSrv := rest.NewClient(oAuthClient).SetRoot(apiURL)
|
||||||
|
|
||||||
|
device, mountpoint, err := setupMountpoint(ctx, srv, apiSrv)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to setup mountpoint: %s", err)
|
||||||
|
}
|
||||||
|
m.Set(configDevice, device)
|
||||||
|
m.Set(configMountpoint, mountpoint)
|
||||||
|
}
|
||||||
|
|
||||||
|
m.Set("configVersion", strconv.Itoa(v1configVersion))
|
||||||
|
}
|
||||||
|
|
||||||
|
// registerDevice register a new device for use with the jottacloud API
|
||||||
|
func registerDevice(ctx context.Context, srv *rest.Client) (reg *api.DeviceRegistrationResponse, err error) {
|
||||||
|
// random generator to generate random device names
|
||||||
|
seededRand := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||||
|
randonDeviceNamePartLength := 21
|
||||||
|
randomDeviceNamePart := make([]byte, randonDeviceNamePartLength)
|
||||||
|
charset := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||||
|
for i := range randomDeviceNamePart {
|
||||||
|
randomDeviceNamePart[i] = charset[seededRand.Intn(len(charset))]
|
||||||
|
}
|
||||||
|
randomDeviceName := "rclone-" + string(randomDeviceNamePart)
|
||||||
|
fs.Debugf(nil, "Trying to register device '%s'", randomDeviceName)
|
||||||
|
|
||||||
|
values := url.Values{}
|
||||||
|
values.Set("device_id", randomDeviceName)
|
||||||
|
|
||||||
|
opts := rest.Opts{
|
||||||
|
Method: "POST",
|
||||||
|
RootURL: v1registerURL,
|
||||||
|
ContentType: "application/x-www-form-urlencoded",
|
||||||
|
ExtraHeaders: map[string]string{"Authorization": "Bearer c2xrZmpoYWRsZmFramhkc2xma2phaHNkbGZramhhc2xkZmtqaGFzZGxrZmpobGtq"},
|
||||||
|
Parameters: values,
|
||||||
|
}
|
||||||
|
|
||||||
|
var deviceRegistration *api.DeviceRegistrationResponse
|
||||||
|
_, err = srv.CallJSON(ctx, &opts, nil, &deviceRegistration)
|
||||||
|
return deviceRegistration, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// doAuthV1 runs the actual token request for V1 authentication
|
||||||
|
func doAuthV1(ctx context.Context, srv *rest.Client, username, password string) (token oauth2.Token, err error) {
|
||||||
|
// prepare out token request with username and password
|
||||||
|
values := url.Values{}
|
||||||
|
values.Set("grant_type", "PASSWORD")
|
||||||
|
values.Set("password", password)
|
||||||
|
values.Set("username", username)
|
||||||
|
values.Set("client_id", oauthConfig.ClientID)
|
||||||
|
values.Set("client_secret", oauthConfig.ClientSecret)
|
||||||
|
opts := rest.Opts{
|
||||||
|
Method: "POST",
|
||||||
|
RootURL: oauthConfig.Endpoint.AuthURL,
|
||||||
|
ContentType: "application/x-www-form-urlencoded",
|
||||||
|
Parameters: values,
|
||||||
|
}
|
||||||
|
|
||||||
|
// do the first request
|
||||||
|
var jsonToken api.TokenJSON
|
||||||
|
resp, err := srv.CallJSON(ctx, &opts, nil, &jsonToken)
|
||||||
|
if err != nil {
|
||||||
|
// if 2fa is enabled the first request is expected to fail. We will do another request with the 2fa code as an additional http header
|
||||||
|
if resp != nil {
|
||||||
|
if resp.Header.Get("X-JottaCloud-OTP") == "required; SMS" {
|
||||||
|
fmt.Printf("This account uses 2 factor authentication you will receive a verification code via SMS.\n")
|
||||||
|
fmt.Printf("Enter verification code> ")
|
||||||
|
authCode := config.ReadLine()
|
||||||
|
|
||||||
|
authCode = strings.Replace(authCode, "-", "", -1) // remove any "-" contained in the code so we have a 6 digit number
|
||||||
|
opts.ExtraHeaders = make(map[string]string)
|
||||||
|
opts.ExtraHeaders["X-Jottacloud-Otp"] = authCode
|
||||||
|
_, err = srv.CallJSON(ctx, &opts, nil, &jsonToken)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
token.AccessToken = jsonToken.AccessToken
|
||||||
|
token.RefreshToken = jsonToken.RefreshToken
|
||||||
|
token.TokenType = jsonToken.TokenType
|
||||||
|
token.Expiry = time.Now().Add(time.Duration(jsonToken.ExpiresIn) * time.Second)
|
||||||
|
return token, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// v2config configure a jottacloud backend using the modern JottaCli token based authentication
|
||||||
|
func v2config(ctx context.Context, name string, m configmap.Mapper) {
|
||||||
|
srv := rest.NewClient(fshttp.NewClient(ctx))
|
||||||
|
|
||||||
|
fmt.Printf("Generate a personal login token here: https://www.jottacloud.com/web/secure\n")
|
||||||
|
fmt.Printf("Login Token> ")
|
||||||
|
loginToken := config.ReadLine()
|
||||||
|
|
||||||
|
m.Set(configClientID, "jottacli")
|
||||||
|
m.Set(configClientSecret, "")
|
||||||
|
|
||||||
|
token, err := doAuthV2(ctx, srv, loginToken, m)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to get oauth token: %s", err)
|
||||||
|
}
|
||||||
|
err = oauthutil.PutToken(name, m, &token, true)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Error while saving token: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("\nDo you want to use a non standard device/mountpoint e.g. for accessing files uploaded using the official Jottacloud client?\n\n")
|
||||||
|
if config.Confirm(false) {
|
||||||
|
oAuthClient, _, err := oauthutil.NewClient(ctx, name, m, oauthConfig)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to load oAuthClient: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
srv = rest.NewClient(oAuthClient).SetRoot(rootURL)
|
||||||
|
apiSrv := rest.NewClient(oAuthClient).SetRoot(apiURL)
|
||||||
|
device, mountpoint, err := setupMountpoint(ctx, srv, apiSrv)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to setup mountpoint: %s", err)
|
||||||
|
}
|
||||||
|
m.Set(configDevice, device)
|
||||||
|
m.Set(configMountpoint, mountpoint)
|
||||||
|
}
|
||||||
|
|
||||||
|
m.Set("configVersion", strconv.Itoa(configVersion))
|
||||||
|
}
|
||||||
|
|
||||||
|
// doAuthV2 runs the actual token request for V2 authentication
|
||||||
|
func doAuthV2(ctx context.Context, srv *rest.Client, loginTokenBase64 string, m configmap.Mapper) (token oauth2.Token, err error) {
|
||||||
|
loginTokenBytes, err := base64.RawURLEncoding.DecodeString(loginTokenBase64)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return token, err
|
return token, err
|
||||||
}
|
}
|
||||||
@@ -390,7 +602,7 @@ func (f *Fs) setEndpointURL() {
|
|||||||
if f.opt.Mountpoint == "" {
|
if f.opt.Mountpoint == "" {
|
||||||
f.opt.Mountpoint = defaultMountpoint
|
f.opt.Mountpoint = defaultMountpoint
|
||||||
}
|
}
|
||||||
f.endpointURL = urlPathEscape(path.Join(f.user, f.opt.Device, f.opt.Mountpoint))
|
f.endpointURL = path.Join(f.user, f.opt.Device, f.opt.Mountpoint)
|
||||||
}
|
}
|
||||||
|
|
||||||
// readMetaDataForPath reads the metadata from the path
|
// readMetaDataForPath reads the metadata from the path
|
||||||
@@ -439,24 +651,46 @@ func errorHandler(resp *http.Response) error {
|
|||||||
return errResponse
|
return errResponse
|
||||||
}
|
}
|
||||||
|
|
||||||
// Jottacloud want's '+' to be URL encoded even though the RFC states it's not reserved
|
// Jottacloud wants '+' to be URL encoded even though the RFC states it's not reserved
|
||||||
func urlPathEscape(in string) string {
|
func urlPathEscape(in string) string {
|
||||||
return strings.Replace(rest.URLPathEscape(in), "+", "%2B", -1)
|
return strings.Replace(rest.URLPathEscape(in), "+", "%2B", -1)
|
||||||
}
|
}
|
||||||
|
|
||||||
// filePathRaw returns an unescaped file path (f.root, file)
|
// filePathRaw returns an unescaped file path (f.root, file)
|
||||||
func (f *Fs) filePathRaw(file string) string {
|
func (f *Fs) filePathRaw(file string) string {
|
||||||
return path.Join(f.endpointURL, enc.FromStandardPath(path.Join(f.root, file)))
|
return path.Join(f.endpointURL, f.opt.Enc.FromStandardPath(path.Join(f.root, file)))
|
||||||
}
|
}
|
||||||
|
|
||||||
// filePath returns a escaped file path (f.root, file)
|
// filePath returns an escaped file path (f.root, file)
|
||||||
func (f *Fs) filePath(file string) string {
|
func (f *Fs) filePath(file string) string {
|
||||||
return urlPathEscape(f.filePathRaw(file))
|
return urlPathEscape(f.filePathRaw(file))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Jottacloud requires the grant_type 'refresh_token' string
|
||||||
|
// to be uppercase and throws a 400 Bad Request if we use the
|
||||||
|
// lower case used by the oauth2 module
|
||||||
|
//
|
||||||
|
// This filter catches all refresh requests, reads the body,
|
||||||
|
// changes the case and then sends it on
|
||||||
|
func grantTypeFilter(req *http.Request) {
|
||||||
|
if v1tokenURL == req.URL.String() {
|
||||||
|
// read the entire body
|
||||||
|
refreshBody, err := ioutil.ReadAll(req.Body)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_ = req.Body.Close()
|
||||||
|
|
||||||
|
// make the refresh token upper case
|
||||||
|
refreshBody = []byte(strings.Replace(string(refreshBody), "grant_type=refresh_token", "grant_type=REFRESH_TOKEN", 1))
|
||||||
|
|
||||||
|
// set the new ReadCloser (with a dummy Close())
|
||||||
|
req.Body = ioutil.NopCloser(bytes.NewReader(refreshBody))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// NewFs constructs an Fs from the path, container:path
|
// NewFs constructs an Fs from the path, container:path
|
||||||
func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {
|
||||||
ctx := context.TODO()
|
|
||||||
// Parse config into Options struct
|
// Parse config into Options struct
|
||||||
opt := new(Options)
|
opt := new(Options)
|
||||||
err := configstruct.Set(m, opt)
|
err := configstruct.Set(m, opt)
|
||||||
@@ -465,29 +699,56 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Check config version
|
// Check config version
|
||||||
var ok bool
|
var ver int
|
||||||
var version string
|
version, ok := m.Get("configVersion")
|
||||||
if version, ok = m.Get("configVersion"); ok {
|
if ok {
|
||||||
ver, err := strconv.Atoi(version)
|
ver, err = strconv.Atoi(version)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.New("Failed to parse config version")
|
return nil, errors.New("Failed to parse config version")
|
||||||
}
|
}
|
||||||
ok = ver == configVersion
|
ok = (ver == configVersion) || (ver == v1configVersion)
|
||||||
}
|
}
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, errors.New("Outdated config - please reconfigure this backend")
|
return nil, errors.New("Outdated config - please reconfigure this backend")
|
||||||
}
|
}
|
||||||
|
|
||||||
// if custome endpoints are set use them else stick with defaults
|
baseClient := fshttp.NewClient(ctx)
|
||||||
if tokenURL, ok := m.Get(configTokenURL); ok {
|
|
||||||
oauthConfig.Endpoint.TokenURL = tokenURL
|
if ver == configVersion {
|
||||||
// jottacloud is weird. we need to use the tokenURL as authURL
|
oauthConfig.ClientID = "jottacli"
|
||||||
oauthConfig.Endpoint.AuthURL = tokenURL
|
// if custom endpoints are set use them else stick with defaults
|
||||||
|
if tokenURL, ok := m.Get(configTokenURL); ok {
|
||||||
|
oauthConfig.Endpoint.TokenURL = tokenURL
|
||||||
|
// jottacloud is weird. we need to use the tokenURL as authURL
|
||||||
|
oauthConfig.Endpoint.AuthURL = tokenURL
|
||||||
|
}
|
||||||
|
} else if ver == v1configVersion {
|
||||||
|
clientID, ok := m.Get(configClientID)
|
||||||
|
if !ok {
|
||||||
|
clientID = v1ClientID
|
||||||
|
}
|
||||||
|
clientSecret, ok := m.Get(configClientSecret)
|
||||||
|
if !ok {
|
||||||
|
clientSecret = v1EncryptedClientSecret
|
||||||
|
}
|
||||||
|
oauthConfig.ClientID = clientID
|
||||||
|
oauthConfig.ClientSecret = obscure.MustReveal(clientSecret)
|
||||||
|
|
||||||
|
oauthConfig.Endpoint.TokenURL = v1tokenURL
|
||||||
|
oauthConfig.Endpoint.AuthURL = v1tokenURL
|
||||||
|
|
||||||
|
// add the request filter to fix token refresh
|
||||||
|
if do, ok := baseClient.Transport.(interface {
|
||||||
|
SetRequestFilter(f func(req *http.Request))
|
||||||
|
}); ok {
|
||||||
|
do.SetRequestFilter(grantTypeFilter)
|
||||||
|
} else {
|
||||||
|
fs.Debugf(name+":", "Couldn't add request filter - uploads will fail")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create OAuth Client
|
// Create OAuth Client
|
||||||
baseClient := fshttp.NewClient(fs.Config)
|
oAuthClient, ts, err := oauthutil.NewClientWithBaseClient(ctx, name, m, oauthConfig, baseClient)
|
||||||
oAuthClient, ts, err := oauthutil.NewClientWithBaseClient(name, m, oauthConfig, baseClient)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "Failed to configure Jottacloud oauth client")
|
return nil, errors.Wrap(err, "Failed to configure Jottacloud oauth client")
|
||||||
}
|
}
|
||||||
@@ -501,19 +762,25 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
opt: *opt,
|
opt: *opt,
|
||||||
srv: rest.NewClient(oAuthClient).SetRoot(rootURL),
|
srv: rest.NewClient(oAuthClient).SetRoot(rootURL),
|
||||||
apiSrv: rest.NewClient(oAuthClient).SetRoot(apiURL),
|
apiSrv: rest.NewClient(oAuthClient).SetRoot(apiURL),
|
||||||
pacer: fs.NewPacer(pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
|
pacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
|
||||||
}
|
}
|
||||||
f.features = (&fs.Features{
|
f.features = (&fs.Features{
|
||||||
CaseInsensitive: true,
|
CaseInsensitive: true,
|
||||||
CanHaveEmptyDirectories: true,
|
CanHaveEmptyDirectories: true,
|
||||||
ReadMimeType: true,
|
ReadMimeType: true,
|
||||||
WriteMimeType: true,
|
WriteMimeType: false,
|
||||||
}).Fill(f)
|
}).Fill(ctx, f)
|
||||||
f.srv.SetErrorHandler(errorHandler)
|
f.srv.SetErrorHandler(errorHandler)
|
||||||
|
if opt.TrashedOnly { // we cannot support showing Trashed Files when using ListR right now
|
||||||
|
f.features.ListR = nil
|
||||||
|
}
|
||||||
|
|
||||||
// Renew the token in the background
|
// Renew the token in the background
|
||||||
f.tokenRenewer = oauthutil.NewRenew(f.String(), ts, func() error {
|
f.tokenRenewer = oauthutil.NewRenew(f.String(), ts, func() error {
|
||||||
_, err := f.readMetaDataForPath(ctx, "")
|
_, err := f.readMetaDataForPath(ctx, "")
|
||||||
|
if err == fs.ErrorNotAFile {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
return err
|
return err
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -629,26 +896,32 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
|
|||||||
return nil, errors.Wrap(err, "couldn't list files")
|
return nil, errors.Wrap(err, "couldn't list files")
|
||||||
}
|
}
|
||||||
|
|
||||||
if result.Deleted {
|
if bool(result.Deleted) && !f.opt.TrashedOnly {
|
||||||
return nil, fs.ErrorDirNotFound
|
return nil, fs.ErrorDirNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
for i := range result.Folders {
|
for i := range result.Folders {
|
||||||
item := &result.Folders[i]
|
item := &result.Folders[i]
|
||||||
if item.Deleted {
|
if !f.opt.TrashedOnly && bool(item.Deleted) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
remote := path.Join(dir, enc.ToStandardName(item.Name))
|
remote := path.Join(dir, f.opt.Enc.ToStandardName(item.Name))
|
||||||
d := fs.NewDir(remote, time.Time(item.ModifiedAt))
|
d := fs.NewDir(remote, time.Time(item.ModifiedAt))
|
||||||
entries = append(entries, d)
|
entries = append(entries, d)
|
||||||
}
|
}
|
||||||
|
|
||||||
for i := range result.Files {
|
for i := range result.Files {
|
||||||
item := &result.Files[i]
|
item := &result.Files[i]
|
||||||
if item.Deleted || item.State != "COMPLETED" {
|
if f.opt.TrashedOnly {
|
||||||
continue
|
if !item.Deleted || item.State != "COMPLETED" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if item.Deleted || item.State != "COMPLETED" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
}
|
}
|
||||||
remote := path.Join(dir, enc.ToStandardName(item.Name))
|
remote := path.Join(dir, f.opt.Enc.ToStandardName(item.Name))
|
||||||
o, err := f.newObjectWithInfo(ctx, remote, item)
|
o, err := f.newObjectWithInfo(ctx, remote, item)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
@@ -673,7 +946,7 @@ func (f *Fs) listFileDir(ctx context.Context, remoteStartPath string, startFolde
|
|||||||
if folder.Deleted {
|
if folder.Deleted {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
folderPath := enc.ToStandardPath(path.Join(folder.Path, folder.Name))
|
folderPath := f.opt.Enc.ToStandardPath(path.Join(folder.Path, folder.Name))
|
||||||
folderPathLength := len(folderPath)
|
folderPathLength := len(folderPath)
|
||||||
var remoteDir string
|
var remoteDir string
|
||||||
if folderPathLength > pathPrefixLength {
|
if folderPathLength > pathPrefixLength {
|
||||||
@@ -691,7 +964,7 @@ func (f *Fs) listFileDir(ctx context.Context, remoteStartPath string, startFolde
|
|||||||
if file.Deleted || file.State != "COMPLETED" {
|
if file.Deleted || file.State != "COMPLETED" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
remoteFile := path.Join(remoteDir, enc.ToStandardName(file.Name))
|
remoteFile := path.Join(remoteDir, f.opt.Enc.ToStandardName(file.Name))
|
||||||
o, err := f.newObjectWithInfo(ctx, remoteFile, file)
|
o, err := f.newObjectWithInfo(ctx, remoteFile, file)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -850,8 +1123,8 @@ func (f *Fs) Precision() time.Duration {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Purge deletes all the files and the container
|
// Purge deletes all the files and the container
|
||||||
func (f *Fs) Purge(ctx context.Context) error {
|
func (f *Fs) Purge(ctx context.Context, dir string) error {
|
||||||
return f.purgeCheck(ctx, "", false)
|
return f.purgeCheck(ctx, dir, false)
|
||||||
}
|
}
|
||||||
|
|
||||||
// copyOrMoves copies or moves directories or files depending on the method parameter
|
// copyOrMoves copies or moves directories or files depending on the method parameter
|
||||||
@@ -862,7 +1135,7 @@ func (f *Fs) copyOrMove(ctx context.Context, method, src, dest string) (info *ap
|
|||||||
Parameters: url.Values{},
|
Parameters: url.Values{},
|
||||||
}
|
}
|
||||||
|
|
||||||
opts.Parameters.Set(method, "/"+path.Join(f.endpointURL, enc.FromStandardPath(path.Join(f.root, dest))))
|
opts.Parameters.Set(method, "/"+path.Join(f.endpointURL, f.opt.Enc.FromStandardPath(path.Join(f.root, dest))))
|
||||||
|
|
||||||
var resp *http.Response
|
var resp *http.Response
|
||||||
err = f.pacer.Call(func() (bool, error) {
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
@@ -875,7 +1148,7 @@ func (f *Fs) copyOrMove(ctx context.Context, method, src, dest string) (info *ap
|
|||||||
return info, nil
|
return info, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Copy src to this remote using server side copy operations.
|
// Copy src to this remote using server-side copy operations.
|
||||||
//
|
//
|
||||||
// This is stored with the remote path given
|
// This is stored with the remote path given
|
||||||
//
|
//
|
||||||
@@ -905,7 +1178,7 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
//return f.newObjectWithInfo(remote, &result)
|
//return f.newObjectWithInfo(remote, &result)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Move src to this remote using server side move operations.
|
// Move src to this remote using server-side move operations.
|
||||||
//
|
//
|
||||||
// This is stored with the remote path given
|
// This is stored with the remote path given
|
||||||
//
|
//
|
||||||
@@ -936,7 +1209,7 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DirMove moves src, srcRemote to this remote at dstRemote
|
// DirMove moves src, srcRemote to this remote at dstRemote
|
||||||
// using server side move operations.
|
// using server-side move operations.
|
||||||
//
|
//
|
||||||
// Will only be called if src.Fs().Name() == f.Name()
|
// Will only be called if src.Fs().Name() == f.Name()
|
||||||
//
|
//
|
||||||
@@ -969,7 +1242,7 @@ func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string
|
|||||||
return fs.ErrorDirExists
|
return fs.ErrorDirExists
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err = f.copyOrMove(ctx, "mvDir", path.Join(f.endpointURL, enc.FromStandardPath(srcPath))+"/", dstRemote)
|
_, err = f.copyOrMove(ctx, "mvDir", path.Join(f.endpointURL, f.opt.Enc.FromStandardPath(srcPath))+"/", dstRemote)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.Wrap(err, "couldn't move directory")
|
return errors.Wrap(err, "couldn't move directory")
|
||||||
@@ -978,14 +1251,14 @@ func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string
|
|||||||
}
|
}
|
||||||
|
|
||||||
// PublicLink generates a public link to the remote path (usually readable by anyone)
|
// PublicLink generates a public link to the remote path (usually readable by anyone)
|
||||||
func (f *Fs) PublicLink(ctx context.Context, remote string) (link string, err error) {
|
func (f *Fs) PublicLink(ctx context.Context, remote string, expire fs.Duration, unlink bool) (link string, err error) {
|
||||||
opts := rest.Opts{
|
opts := rest.Opts{
|
||||||
Method: "GET",
|
Method: "GET",
|
||||||
Path: f.filePath(remote),
|
Path: f.filePath(remote),
|
||||||
Parameters: url.Values{},
|
Parameters: url.Values{},
|
||||||
}
|
}
|
||||||
|
|
||||||
if f.opt.Unlink {
|
if unlink {
|
||||||
opts.Parameters.Set("mode", "disableShare")
|
opts.Parameters.Set("mode", "disableShare")
|
||||||
} else {
|
} else {
|
||||||
opts.Parameters.Set("mode", "enableShare")
|
opts.Parameters.Set("mode", "enableShare")
|
||||||
@@ -1005,12 +1278,12 @@ func (f *Fs) PublicLink(ctx context.Context, remote string) (link string, err er
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if f.opt.Unlink {
|
if unlink {
|
||||||
return "", errors.Wrap(err, "couldn't remove public link")
|
return "", errors.Wrap(err, "couldn't remove public link")
|
||||||
}
|
}
|
||||||
return "", errors.Wrap(err, "couldn't create public link")
|
return "", errors.Wrap(err, "couldn't create public link")
|
||||||
}
|
}
|
||||||
if f.opt.Unlink {
|
if unlink {
|
||||||
if result.PublicSharePath != "" {
|
if result.PublicSharePath != "" {
|
||||||
return "", errors.Errorf("couldn't remove public link - %q", result.PublicSharePath)
|
return "", errors.Errorf("couldn't remove public link - %q", result.PublicSharePath)
|
||||||
}
|
}
|
||||||
@@ -1040,6 +1313,22 @@ func (f *Fs) About(ctx context.Context) (*fs.Usage, error) {
|
|||||||
return usage, nil
|
return usage, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CleanUp empties the trash
|
||||||
|
func (f *Fs) CleanUp(ctx context.Context) error {
|
||||||
|
opts := rest.Opts{
|
||||||
|
Method: "POST",
|
||||||
|
Path: "files/v1/purge_trash",
|
||||||
|
}
|
||||||
|
|
||||||
|
var info api.TrashResponse
|
||||||
|
_, err := f.apiSrv.CallJSON(ctx, &opts, nil, &info)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "couldn't empty trash")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// Hashes returns the supported hash sets.
|
// Hashes returns the supported hash sets.
|
||||||
func (f *Fs) Hashes() hash.Set {
|
func (f *Fs) Hashes() hash.Set {
|
||||||
return hash.Set(hash.MD5)
|
return hash.Set(hash.MD5)
|
||||||
@@ -1065,7 +1354,7 @@ func (o *Object) Remote() string {
|
|||||||
return o.remote
|
return o.remote
|
||||||
}
|
}
|
||||||
|
|
||||||
// filePath returns a escaped file path (f.root, remote)
|
// filePath returns an escaped file path (f.root, remote)
|
||||||
func (o *Object) filePath() string {
|
func (o *Object) filePath() string {
|
||||||
return o.fs.filePath(o.remote)
|
return o.fs.filePath(o.remote)
|
||||||
}
|
}
|
||||||
@@ -1113,7 +1402,7 @@ func (o *Object) readMetaData(ctx context.Context, force bool) (err error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if info.Deleted {
|
if bool(info.Deleted) && !o.fs.opt.TrashedOnly {
|
||||||
return fs.ErrorObjectNotFound
|
return fs.ErrorObjectNotFound
|
||||||
}
|
}
|
||||||
return o.setMetaData(info)
|
return o.setMetaData(info)
|
||||||
@@ -1170,7 +1459,7 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.Read
|
|||||||
// The cleanup function should be called when out is finished with
|
// The cleanup function should be called when out is finished with
|
||||||
// regardless of whether this function returned an error or not.
|
// regardless of whether this function returned an error or not.
|
||||||
func readMD5(in io.Reader, size, threshold int64) (md5sum string, out io.Reader, cleanup func(), err error) {
|
func readMD5(in io.Reader, size, threshold int64) (md5sum string, out io.Reader, cleanup func(), err error) {
|
||||||
// we need a MD5
|
// we need an MD5
|
||||||
md5Hasher := md5.New()
|
md5Hasher := md5.New()
|
||||||
// use the teeReader to write to the local file AND calculate the MD5 while doing so
|
// use the teeReader to write to the local file AND calculate the MD5 while doing so
|
||||||
teeReader := io.TeeReader(in, md5Hasher)
|
teeReader := io.TeeReader(in, md5Hasher)
|
||||||
@@ -1228,6 +1517,8 @@ func readMD5(in io.Reader, size, threshold int64) (md5sum string, out io.Reader,
|
|||||||
//
|
//
|
||||||
// The new object may have been created if an error is returned
|
// The new object may have been created if an error is returned
|
||||||
func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (err error) {
|
func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (err error) {
|
||||||
|
o.fs.tokenRenewer.Start()
|
||||||
|
defer o.fs.tokenRenewer.Stop()
|
||||||
size := src.Size()
|
size := src.Size()
|
||||||
md5String, err := src.Hash(ctx, hash.MD5)
|
md5String, err := src.Hash(ctx, hash.MD5)
|
||||||
if err != nil || md5String == "" {
|
if err != nil || md5String == "" {
|
||||||
@@ -1250,6 +1541,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
opts := rest.Opts{
|
opts := rest.Opts{
|
||||||
Method: "POST",
|
Method: "POST",
|
||||||
Path: "files/v1/allocate",
|
Path: "files/v1/allocate",
|
||||||
|
Options: options,
|
||||||
ExtraHeaders: make(map[string]string),
|
ExtraHeaders: make(map[string]string),
|
||||||
}
|
}
|
||||||
fileDate := api.Time(src.ModTime(ctx)).APIString()
|
fileDate := api.Time(src.ModTime(ctx)).APIString()
|
||||||
@@ -1260,7 +1552,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
Created: fileDate,
|
Created: fileDate,
|
||||||
Modified: fileDate,
|
Modified: fileDate,
|
||||||
Md5: md5String,
|
Md5: md5String,
|
||||||
Path: path.Join(o.fs.opt.Mountpoint, enc.FromStandardPath(path.Join(o.fs.root, o.remote))),
|
Path: path.Join(o.fs.opt.Mountpoint, o.fs.opt.Enc.FromStandardPath(path.Join(o.fs.root, o.remote))),
|
||||||
}
|
}
|
||||||
|
|
||||||
// send it
|
// send it
|
||||||
@@ -1273,7 +1565,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// If the file state is INCOMPLETE and CORRPUT, try to upload a then
|
// If the file state is INCOMPLETE and CORRUPT, try to upload a then
|
||||||
if response.State != "COMPLETED" {
|
if response.State != "COMPLETED" {
|
||||||
// how much do we still have to upload?
|
// how much do we still have to upload?
|
||||||
remainingBytes := size - response.ResumePos
|
remainingBytes := size - response.ResumePos
|
||||||
@@ -1346,6 +1638,7 @@ var (
|
|||||||
_ fs.ListRer = (*Fs)(nil)
|
_ fs.ListRer = (*Fs)(nil)
|
||||||
_ fs.PublicLinker = (*Fs)(nil)
|
_ fs.PublicLinker = (*Fs)(nil)
|
||||||
_ fs.Abouter = (*Fs)(nil)
|
_ fs.Abouter = (*Fs)(nil)
|
||||||
|
_ fs.CleanUpper = (*Fs)(nil)
|
||||||
_ fs.Object = (*Object)(nil)
|
_ fs.Object = (*Object)(nil)
|
||||||
_ fs.MimeTyper = (*Object)(nil)
|
_ fs.MimeTyper = (*Object)(nil)
|
||||||
)
|
)
|
||||||
+54
-48
@@ -12,68 +12,74 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/rclone/rclone/fs"
|
"github.com/rclone/rclone/fs"
|
||||||
|
"github.com/rclone/rclone/fs/config"
|
||||||
"github.com/rclone/rclone/fs/config/configmap"
|
"github.com/rclone/rclone/fs/config/configmap"
|
||||||
"github.com/rclone/rclone/fs/config/configstruct"
|
"github.com/rclone/rclone/fs/config/configstruct"
|
||||||
"github.com/rclone/rclone/fs/config/obscure"
|
"github.com/rclone/rclone/fs/config/obscure"
|
||||||
"github.com/rclone/rclone/fs/encodings"
|
|
||||||
"github.com/rclone/rclone/fs/fshttp"
|
"github.com/rclone/rclone/fs/fshttp"
|
||||||
"github.com/rclone/rclone/fs/hash"
|
"github.com/rclone/rclone/fs/hash"
|
||||||
|
"github.com/rclone/rclone/lib/encoder"
|
||||||
|
|
||||||
httpclient "github.com/koofr/go-httpclient"
|
httpclient "github.com/koofr/go-httpclient"
|
||||||
koofrclient "github.com/koofr/go-koofrclient"
|
koofrclient "github.com/koofr/go-koofrclient"
|
||||||
)
|
)
|
||||||
|
|
||||||
const enc = encodings.Koofr
|
|
||||||
|
|
||||||
// Register Fs with rclone
|
// Register Fs with rclone
|
||||||
func init() {
|
func init() {
|
||||||
fs.Register(&fs.RegInfo{
|
fs.Register(&fs.RegInfo{
|
||||||
Name: "koofr",
|
Name: "koofr",
|
||||||
Description: "Koofr",
|
Description: "Koofr",
|
||||||
NewFs: NewFs,
|
NewFs: NewFs,
|
||||||
Options: []fs.Option{
|
Options: []fs.Option{{
|
||||||
{
|
Name: "endpoint",
|
||||||
Name: "endpoint",
|
Help: "The Koofr API endpoint to use",
|
||||||
Help: "The Koofr API endpoint to use",
|
Default: "https://app.koofr.net",
|
||||||
Default: "https://app.koofr.net",
|
Required: true,
|
||||||
Required: true,
|
Advanced: true,
|
||||||
Advanced: true,
|
}, {
|
||||||
}, {
|
Name: "mountid",
|
||||||
Name: "mountid",
|
Help: "Mount ID of the mount to use. If omitted, the primary mount is used.",
|
||||||
Help: "Mount ID of the mount to use. If omitted, the primary mount is used.",
|
Required: false,
|
||||||
Required: false,
|
Default: "",
|
||||||
Default: "",
|
Advanced: true,
|
||||||
Advanced: true,
|
}, {
|
||||||
}, {
|
Name: "setmtime",
|
||||||
Name: "setmtime",
|
Help: "Does the backend support setting modification time. Set this to false if you use a mount ID that points to a Dropbox or Amazon Drive backend.",
|
||||||
Help: "Does the backend support setting modification time. Set this to false if you use a mount ID that points to a Dropbox or Amazon Drive backend.",
|
Default: true,
|
||||||
Default: true,
|
Required: true,
|
||||||
Required: true,
|
Advanced: true,
|
||||||
Advanced: true,
|
}, {
|
||||||
}, {
|
Name: "user",
|
||||||
Name: "user",
|
Help: "Your Koofr user name",
|
||||||
Help: "Your Koofr user name",
|
Required: true,
|
||||||
Required: true,
|
}, {
|
||||||
}, {
|
Name: "password",
|
||||||
Name: "password",
|
Help: "Your Koofr password for rclone (generate one at https://app.koofr.net/app/admin/preferences/password)",
|
||||||
Help: "Your Koofr password for rclone (generate one at https://app.koofr.net/app/admin/preferences/password)",
|
IsPassword: true,
|
||||||
IsPassword: true,
|
Required: true,
|
||||||
Required: true,
|
}, {
|
||||||
},
|
Name: config.ConfigEncoding,
|
||||||
},
|
Help: config.ConfigEncodingHelp,
|
||||||
|
Advanced: true,
|
||||||
|
// Encode invalid UTF-8 bytes as json doesn't handle them properly.
|
||||||
|
Default: (encoder.Display |
|
||||||
|
encoder.EncodeBackSlash |
|
||||||
|
encoder.EncodeInvalidUtf8),
|
||||||
|
}},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Options represent the configuration of the Koofr backend
|
// Options represent the configuration of the Koofr backend
|
||||||
type Options struct {
|
type Options struct {
|
||||||
Endpoint string `config:"endpoint"`
|
Endpoint string `config:"endpoint"`
|
||||||
MountID string `config:"mountid"`
|
MountID string `config:"mountid"`
|
||||||
User string `config:"user"`
|
User string `config:"user"`
|
||||||
Password string `config:"password"`
|
Password string `config:"password"`
|
||||||
SetMTime bool `config:"setmtime"`
|
SetMTime bool `config:"setmtime"`
|
||||||
|
Enc encoder.MultiEncoder `config:"encoding"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// A Fs is a representation of a remote Koofr Fs
|
// An Fs is a representation of a remote Koofr Fs
|
||||||
type Fs struct {
|
type Fs struct {
|
||||||
name string
|
name string
|
||||||
mountID string
|
mountID string
|
||||||
@@ -244,13 +250,13 @@ func (f *Fs) Hashes() hash.Set {
|
|||||||
return hash.Set(hash.MD5)
|
return hash.Set(hash.MD5)
|
||||||
}
|
}
|
||||||
|
|
||||||
// fullPath constructs a full, absolute path from a Fs root relative path,
|
// fullPath constructs a full, absolute path from an Fs root relative path,
|
||||||
func (f *Fs) fullPath(part string) string {
|
func (f *Fs) fullPath(part string) string {
|
||||||
return enc.FromStandardPath(path.Join("/", f.root, part))
|
return f.opt.Enc.FromStandardPath(path.Join("/", f.root, part))
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewFs constructs a new filesystem given a root path and configuration options
|
// NewFs constructs a new filesystem given a root path and configuration options
|
||||||
func NewFs(name, root string, m configmap.Mapper) (ff fs.Fs, err error) {
|
func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (ff fs.Fs, err error) {
|
||||||
opt := new(Options)
|
opt := new(Options)
|
||||||
err = configstruct.Set(m, opt)
|
err = configstruct.Set(m, opt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -261,7 +267,7 @@ func NewFs(name, root string, m configmap.Mapper) (ff fs.Fs, err error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
httpClient := httpclient.New()
|
httpClient := httpclient.New()
|
||||||
httpClient.Client = fshttp.NewClient(fs.Config)
|
httpClient.Client = fshttp.NewClient(ctx)
|
||||||
client := koofrclient.NewKoofrClientWithHTTPClient(opt.Endpoint, httpClient)
|
client := koofrclient.NewKoofrClientWithHTTPClient(opt.Endpoint, httpClient)
|
||||||
basicAuth := fmt.Sprintf("Basic %s",
|
basicAuth := fmt.Sprintf("Basic %s",
|
||||||
base64.StdEncoding.EncodeToString([]byte(opt.User+":"+pass)))
|
base64.StdEncoding.EncodeToString([]byte(opt.User+":"+pass)))
|
||||||
@@ -281,7 +287,7 @@ func NewFs(name, root string, m configmap.Mapper) (ff fs.Fs, err error) {
|
|||||||
DuplicateFiles: false,
|
DuplicateFiles: false,
|
||||||
BucketBased: false,
|
BucketBased: false,
|
||||||
CanHaveEmptyDirectories: true,
|
CanHaveEmptyDirectories: true,
|
||||||
}).Fill(f)
|
}).Fill(ctx, f)
|
||||||
for _, m := range mounts {
|
for _, m := range mounts {
|
||||||
if opt.MountID != "" {
|
if opt.MountID != "" {
|
||||||
if m.Id == opt.MountID {
|
if m.Id == opt.MountID {
|
||||||
@@ -299,7 +305,7 @@ func NewFs(name, root string, m configmap.Mapper) (ff fs.Fs, err error) {
|
|||||||
}
|
}
|
||||||
return nil, errors.New("Failed to find mount " + opt.MountID)
|
return nil, errors.New("Failed to find mount " + opt.MountID)
|
||||||
}
|
}
|
||||||
rootFile, err := f.client.FilesInfo(f.mountID, enc.FromStandardPath("/"+f.root))
|
rootFile, err := f.client.FilesInfo(f.mountID, f.opt.Enc.FromStandardPath("/"+f.root))
|
||||||
if err == nil && rootFile.Type != "dir" {
|
if err == nil && rootFile.Type != "dir" {
|
||||||
f.root = dir(f.root)
|
f.root = dir(f.root)
|
||||||
err = fs.ErrorIsFile
|
err = fs.ErrorIsFile
|
||||||
@@ -317,7 +323,7 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
|
|||||||
}
|
}
|
||||||
entries = make([]fs.DirEntry, len(files))
|
entries = make([]fs.DirEntry, len(files))
|
||||||
for i, file := range files {
|
for i, file := range files {
|
||||||
remote := path.Join(dir, enc.ToStandardName(file.Name))
|
remote := path.Join(dir, f.opt.Enc.ToStandardName(file.Name))
|
||||||
if file.Type == "dir" {
|
if file.Type == "dir" {
|
||||||
entries[i] = fs.NewDir(remote, time.Unix(0, 0))
|
entries[i] = fs.NewDir(remote, time.Unix(0, 0))
|
||||||
} else {
|
} else {
|
||||||
@@ -415,7 +421,7 @@ func translateErrorsObject(err error) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// mkdir creates a directory at the given remote path. Creates ancestors if
|
// mkdir creates a directory at the given remote path. Creates ancestors if
|
||||||
// neccessary
|
// necessary
|
||||||
func (f *Fs) mkdir(fullPath string) error {
|
func (f *Fs) mkdir(fullPath string) error {
|
||||||
if fullPath == "/" {
|
if fullPath == "/" {
|
||||||
return nil
|
return nil
|
||||||
@@ -597,7 +603,7 @@ func createLink(c *koofrclient.KoofrClient, mountID string, path string) (*link,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// PublicLink creates a public link to the remote path
|
// PublicLink creates a public link to the remote path
|
||||||
func (f *Fs) PublicLink(ctx context.Context, remote string) (string, error) {
|
func (f *Fs) PublicLink(ctx context.Context, remote string, expire fs.Duration, unlink bool) (string, error) {
|
||||||
linkData, err := createLink(f.client, f.mountID, f.fullPath(remote))
|
linkData, err := createLink(f.client, f.mountID, f.fullPath(remote))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", translateErrorsDir(err)
|
return "", translateErrorsDir(err)
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ package local
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"os"
|
||||||
"syscall"
|
"syscall"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
@@ -15,6 +16,9 @@ func (f *Fs) About(ctx context.Context) (*fs.Usage, error) {
|
|||||||
var s syscall.Statfs_t
|
var s syscall.Statfs_t
|
||||||
err := syscall.Statfs(f.root, &s)
|
err := syscall.Statfs(f.root, &s)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
return nil, fs.ErrorDirNotFound
|
||||||
|
}
|
||||||
return nil, errors.Wrap(err, "failed to read disk usage")
|
return nil, errors.Wrap(err, "failed to read disk usage")
|
||||||
}
|
}
|
||||||
bs := int64(s.Bsize) // nolint: unconvert
|
bs := int64(s.Bsize) // nolint: unconvert
|
||||||
|
|||||||
@@ -2,8 +2,10 @@
|
|||||||
|
|
||||||
package local
|
package local
|
||||||
|
|
||||||
import (
|
import "github.com/rclone/rclone/lib/encoder"
|
||||||
"github.com/rclone/rclone/fs/encodings"
|
|
||||||
)
|
|
||||||
|
|
||||||
const enc = encodings.LocalMacOS
|
// This is the encoding used by the local backend for macOS
|
||||||
|
//
|
||||||
|
// macOS can't store invalid UTF-8, it converts them into %XX encoding
|
||||||
|
const defaultEnc = (encoder.Base |
|
||||||
|
encoder.EncodeInvalidUtf8)
|
||||||
@@ -2,8 +2,7 @@
|
|||||||
|
|
||||||
package local
|
package local
|
||||||
|
|
||||||
import (
|
import "github.com/rclone/rclone/lib/encoder"
|
||||||
"github.com/rclone/rclone/fs/encodings"
|
|
||||||
)
|
|
||||||
|
|
||||||
const enc = encodings.LocalUnix
|
// This is the encoding used by the local backend for non windows platforms
|
||||||
|
const defaultEnc = encoder.Base
|
||||||
@@ -2,8 +2,32 @@
|
|||||||
|
|
||||||
package local
|
package local
|
||||||
|
|
||||||
import (
|
import "github.com/rclone/rclone/lib/encoder"
|
||||||
"github.com/rclone/rclone/fs/encodings"
|
|
||||||
)
|
|
||||||
|
|
||||||
const enc = encodings.LocalWindows
|
// This is the encoding used by the local backend for windows platforms
|
||||||
|
//
|
||||||
|
// List of replaced characters:
|
||||||
|
// < (less than) -> '<' // FULLWIDTH LESS-THAN SIGN
|
||||||
|
// > (greater than) -> '>' // FULLWIDTH GREATER-THAN SIGN
|
||||||
|
// : (colon) -> ':' // FULLWIDTH COLON
|
||||||
|
// " (double quote) -> '"' // FULLWIDTH QUOTATION MARK
|
||||||
|
// \ (backslash) -> '\' // FULLWIDTH REVERSE SOLIDUS
|
||||||
|
// | (vertical line) -> '|' // FULLWIDTH VERTICAL LINE
|
||||||
|
// ? (question mark) -> '?' // FULLWIDTH QUESTION MARK
|
||||||
|
// * (asterisk) -> '*' // FULLWIDTH ASTERISK
|
||||||
|
//
|
||||||
|
// Additionally names can't end with a period (.) or space ( ).
|
||||||
|
// List of replaced characters:
|
||||||
|
// . (period) -> '.' // FULLWIDTH FULL STOP
|
||||||
|
// (space) -> '␠' // SYMBOL FOR SPACE
|
||||||
|
//
|
||||||
|
// Also encode invalid UTF-8 bytes as Go can't convert them to UTF-16.
|
||||||
|
//
|
||||||
|
// https://docs.microsoft.com/de-de/windows/desktop/FileIO/naming-a-file#naming-conventions
|
||||||
|
const defaultEnc = (encoder.Base |
|
||||||
|
encoder.EncodeWin |
|
||||||
|
encoder.EncodeBackSlash |
|
||||||
|
encoder.EncodeCtl |
|
||||||
|
encoder.EncodeRightSpace |
|
||||||
|
encoder.EncodeRightPeriod |
|
||||||
|
encoder.EncodeInvalidUtf8)
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
// +build windows plan9
|
// +build windows plan9 js
|
||||||
|
|
||||||
package local
|
package local
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
// +build !windows,!plan9
|
// +build !windows,!plan9,!js
|
||||||
|
|
||||||
package local
|
package local
|
||||||
|
|
||||||
|
|||||||
+249
-90
@@ -10,7 +10,6 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"regexp"
|
|
||||||
"runtime"
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
@@ -20,10 +19,12 @@ import (
|
|||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"github.com/rclone/rclone/fs"
|
"github.com/rclone/rclone/fs"
|
||||||
"github.com/rclone/rclone/fs/accounting"
|
"github.com/rclone/rclone/fs/accounting"
|
||||||
|
"github.com/rclone/rclone/fs/config"
|
||||||
"github.com/rclone/rclone/fs/config/configmap"
|
"github.com/rclone/rclone/fs/config/configmap"
|
||||||
"github.com/rclone/rclone/fs/config/configstruct"
|
"github.com/rclone/rclone/fs/config/configstruct"
|
||||||
"github.com/rclone/rclone/fs/fserrors"
|
"github.com/rclone/rclone/fs/fserrors"
|
||||||
"github.com/rclone/rclone/fs/hash"
|
"github.com/rclone/rclone/fs/hash"
|
||||||
|
"github.com/rclone/rclone/lib/encoder"
|
||||||
"github.com/rclone/rclone/lib/file"
|
"github.com/rclone/rclone/lib/file"
|
||||||
"github.com/rclone/rclone/lib/readers"
|
"github.com/rclone/rclone/lib/readers"
|
||||||
)
|
)
|
||||||
@@ -39,6 +40,7 @@ func init() {
|
|||||||
Name: "local",
|
Name: "local",
|
||||||
Description: "Local Disk",
|
Description: "Local Disk",
|
||||||
NewFs: NewFs,
|
NewFs: NewFs,
|
||||||
|
CommandHelp: commandHelp,
|
||||||
Options: []fs.Option{{
|
Options: []fs.Option{{
|
||||||
Name: "nounc",
|
Name: "nounc",
|
||||||
Help: "Disable UNC (long path names) conversion on Windows",
|
Help: "Disable UNC (long path names) conversion on Windows",
|
||||||
@@ -68,6 +70,20 @@ points, as you explicitly acknowledge that they should be skipped.`,
|
|||||||
Default: false,
|
Default: false,
|
||||||
NoPrefix: true,
|
NoPrefix: true,
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: "zero_size_links",
|
||||||
|
Help: `Assume the Stat size of links is zero (and read them instead)
|
||||||
|
|
||||||
|
On some virtual filesystems (such ash LucidLink), reading a link size via a Stat call always returns 0.
|
||||||
|
However, on unix it reads as the length of the text in the link. This may cause errors like this when
|
||||||
|
syncing:
|
||||||
|
|
||||||
|
Failed to copy: corrupted on transfer: sizes differ 0 vs 13
|
||||||
|
|
||||||
|
Setting this flag causes rclone to read the link and use that as the size of the link
|
||||||
|
instead of 0 which in most cases fixes the problem.`,
|
||||||
|
Default: false,
|
||||||
|
Advanced: true,
|
||||||
}, {
|
}, {
|
||||||
Name: "no_unicode_normalization",
|
Name: "no_unicode_normalization",
|
||||||
Help: `Don't apply unicode normalization to paths and filenames (Deprecated)
|
Help: `Don't apply unicode normalization to paths and filenames (Deprecated)
|
||||||
@@ -85,9 +101,26 @@ Normally rclone checks the size and modification time of files as they
|
|||||||
are being uploaded and aborts with a message which starts "can't copy
|
are being uploaded and aborts with a message which starts "can't copy
|
||||||
- source file is being updated" if the file changes during upload.
|
- source file is being updated" if the file changes during upload.
|
||||||
|
|
||||||
However on some file systems this modification time check may fail (eg
|
However on some file systems this modification time check may fail (e.g.
|
||||||
[Glusterfs #2206](https://github.com/rclone/rclone/issues/2206)) so this
|
[Glusterfs #2206](https://github.com/rclone/rclone/issues/2206)) so this
|
||||||
check can be disabled with this flag.`,
|
check can be disabled with this flag.
|
||||||
|
|
||||||
|
If this flag is set, rclone will use its best efforts to transfer a
|
||||||
|
file which is being updated. If the file is only having things
|
||||||
|
appended to it (e.g. a log) then rclone will transfer the log file with
|
||||||
|
the size it had the first time rclone saw it.
|
||||||
|
|
||||||
|
If the file is being modified throughout (not just appended to) then
|
||||||
|
the transfer may fail with a hash check failure.
|
||||||
|
|
||||||
|
In detail, once the file has had stat() called on it for the first
|
||||||
|
time we:
|
||||||
|
|
||||||
|
- Only transfer the size that stat gave
|
||||||
|
- Only checksum the size that stat gave
|
||||||
|
- Don't update the stat info for the file
|
||||||
|
|
||||||
|
`,
|
||||||
Default: false,
|
Default: false,
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
}, {
|
}, {
|
||||||
@@ -115,6 +148,32 @@ Windows/macOS and case sensitive for everything else. Use this flag
|
|||||||
to override the default choice.`,
|
to override the default choice.`,
|
||||||
Default: false,
|
Default: false,
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: "no_sparse",
|
||||||
|
Help: `Disable sparse files for multi-thread downloads
|
||||||
|
|
||||||
|
On Windows platforms rclone will make sparse files when doing
|
||||||
|
multi-thread downloads. This avoids long pauses on large files where
|
||||||
|
the OS zeros the file. However sparse files may be undesirable as they
|
||||||
|
cause disk fragmentation and can be slow to work with.`,
|
||||||
|
Default: false,
|
||||||
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: "no_set_modtime",
|
||||||
|
Help: `Disable setting modtime
|
||||||
|
|
||||||
|
Normally rclone updates modification time of files after they are done
|
||||||
|
uploading. This can cause permissions issues on Linux platforms when
|
||||||
|
the user rclone is running as does not own the file uploaded, such as
|
||||||
|
when copying to a CIFS mount owned by another user. If this option is
|
||||||
|
enabled, rclone will no longer update the modtime after copying a file.`,
|
||||||
|
Default: false,
|
||||||
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: config.ConfigEncoding,
|
||||||
|
Help: config.ConfigEncodingHelp,
|
||||||
|
Advanced: true,
|
||||||
|
Default: defaultEnc,
|
||||||
}},
|
}},
|
||||||
}
|
}
|
||||||
fs.Register(fsi)
|
fs.Register(fsi)
|
||||||
@@ -122,15 +181,19 @@ to override the default choice.`,
|
|||||||
|
|
||||||
// Options defines the configuration for this backend
|
// Options defines the configuration for this backend
|
||||||
type Options struct {
|
type Options struct {
|
||||||
FollowSymlinks bool `config:"copy_links"`
|
FollowSymlinks bool `config:"copy_links"`
|
||||||
TranslateSymlinks bool `config:"links"`
|
TranslateSymlinks bool `config:"links"`
|
||||||
SkipSymlinks bool `config:"skip_links"`
|
SkipSymlinks bool `config:"skip_links"`
|
||||||
NoUTFNorm bool `config:"no_unicode_normalization"`
|
ZeroSizeLinks bool `config:"zero_size_links"`
|
||||||
NoCheckUpdated bool `config:"no_check_updated"`
|
NoUTFNorm bool `config:"no_unicode_normalization"`
|
||||||
NoUNC bool `config:"nounc"`
|
NoCheckUpdated bool `config:"no_check_updated"`
|
||||||
OneFileSystem bool `config:"one_file_system"`
|
NoUNC bool `config:"nounc"`
|
||||||
CaseSensitive bool `config:"case_sensitive"`
|
OneFileSystem bool `config:"one_file_system"`
|
||||||
CaseInsensitive bool `config:"case_insensitive"`
|
CaseSensitive bool `config:"case_sensitive"`
|
||||||
|
CaseInsensitive bool `config:"case_insensitive"`
|
||||||
|
NoSparse bool `config:"no_sparse"`
|
||||||
|
NoSetModTime bool `config:"no_set_modtime"`
|
||||||
|
Enc encoder.MultiEncoder `config:"encoding"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fs represents a local filesystem rooted at root
|
// Fs represents a local filesystem rooted at root
|
||||||
@@ -146,20 +209,22 @@ type Fs struct {
|
|||||||
warned map[string]struct{} // whether we have warned about this string
|
warned map[string]struct{} // whether we have warned about this string
|
||||||
|
|
||||||
// do os.Lstat or os.Stat
|
// do os.Lstat or os.Stat
|
||||||
lstat func(name string) (os.FileInfo, error)
|
lstat func(name string) (os.FileInfo, error)
|
||||||
objectHashesMu sync.Mutex // global lock for Object.hashes
|
objectMetaMu sync.RWMutex // global lock for Object metadata
|
||||||
}
|
}
|
||||||
|
|
||||||
// Object represents a local filesystem object
|
// Object represents a local filesystem object
|
||||||
type Object struct {
|
type Object struct {
|
||||||
fs *Fs // The Fs this object is part of
|
fs *Fs // The Fs this object is part of
|
||||||
remote string // The remote path (encoded path)
|
remote string // The remote path (encoded path)
|
||||||
path string // The local path (OS path)
|
path string // The local path (OS path)
|
||||||
size int64 // file metadata - always present
|
// When using these items the fs.objectMetaMu must be held
|
||||||
mode os.FileMode
|
size int64 // file metadata - always present
|
||||||
modTime time.Time
|
mode os.FileMode
|
||||||
hashes map[hash.Type]string // Hashes
|
modTime time.Time
|
||||||
translatedLink bool // Is this object a translated link
|
hashes map[hash.Type]string // Hashes
|
||||||
|
// these are read only and don't need the mutex held
|
||||||
|
translatedLink bool // Is this object a translated link
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------
|
// ------------------------------------------------------------
|
||||||
@@ -167,7 +232,7 @@ type Object struct {
|
|||||||
var errLinksAndCopyLinks = errors.New("can't use -l/--links with -L/--copy-links")
|
var errLinksAndCopyLinks = errors.New("can't use -l/--links with -L/--copy-links")
|
||||||
|
|
||||||
// NewFs constructs an Fs from the path
|
// NewFs constructs an Fs from the path
|
||||||
func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {
|
||||||
// Parse config into Options struct
|
// Parse config into Options struct
|
||||||
opt := new(Options)
|
opt := new(Options)
|
||||||
err := configstruct.Set(m, opt)
|
err := configstruct.Set(m, opt)
|
||||||
@@ -189,12 +254,13 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
dev: devUnset,
|
dev: devUnset,
|
||||||
lstat: os.Lstat,
|
lstat: os.Lstat,
|
||||||
}
|
}
|
||||||
f.root = cleanRootPath(root, f.opt.NoUNC)
|
f.root = cleanRootPath(root, f.opt.NoUNC, f.opt.Enc)
|
||||||
f.features = (&fs.Features{
|
f.features = (&fs.Features{
|
||||||
CaseInsensitive: f.caseInsensitive(),
|
CaseInsensitive: f.caseInsensitive(),
|
||||||
CanHaveEmptyDirectories: true,
|
CanHaveEmptyDirectories: true,
|
||||||
IsLocal: true,
|
IsLocal: true,
|
||||||
}).Fill(f)
|
SlowHash: true,
|
||||||
|
}).Fill(ctx, f)
|
||||||
if opt.FollowSymlinks {
|
if opt.FollowSymlinks {
|
||||||
f.lstat = os.Stat
|
f.lstat = os.Stat
|
||||||
}
|
}
|
||||||
@@ -234,7 +300,7 @@ func (f *Fs) Name() string {
|
|||||||
|
|
||||||
// Root of the remote (as passed into NewFs)
|
// Root of the remote (as passed into NewFs)
|
||||||
func (f *Fs) Root() string {
|
func (f *Fs) Root() string {
|
||||||
return enc.ToStandardPath(filepath.ToSlash(f.root))
|
return f.opt.Enc.ToStandardPath(filepath.ToSlash(f.root))
|
||||||
}
|
}
|
||||||
|
|
||||||
// String converts this Fs to a string
|
// String converts this Fs to a string
|
||||||
@@ -405,8 +471,8 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
|
|||||||
if f.opt.FollowSymlinks && (mode&os.ModeSymlink) != 0 {
|
if f.opt.FollowSymlinks && (mode&os.ModeSymlink) != 0 {
|
||||||
localPath := filepath.Join(fsDirPath, name)
|
localPath := filepath.Join(fsDirPath, name)
|
||||||
fi, err = os.Stat(localPath)
|
fi, err = os.Stat(localPath)
|
||||||
if os.IsNotExist(err) {
|
if os.IsNotExist(err) || isCircularSymlinkError(err) {
|
||||||
// Skip bad symlinks
|
// Skip bad symlinks and circular symlinks
|
||||||
err = fserrors.NoRetryError(errors.Wrap(err, "symlink"))
|
err = fserrors.NoRetryError(errors.Wrap(err, "symlink"))
|
||||||
fs.Errorf(newRemote, "Listing error: %v", err)
|
fs.Errorf(newRemote, "Listing error: %v", err)
|
||||||
err = accounting.Stats(ctx).Error(err)
|
err = accounting.Stats(ctx).Error(err)
|
||||||
@@ -443,7 +509,7 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fs) cleanRemote(dir, filename string) (remote string) {
|
func (f *Fs) cleanRemote(dir, filename string) (remote string) {
|
||||||
remote = path.Join(dir, enc.ToStandardName(filename))
|
remote = path.Join(dir, f.opt.Enc.ToStandardName(filename))
|
||||||
|
|
||||||
if !utf8.ValidString(filename) {
|
if !utf8.ValidString(filename) {
|
||||||
f.warnedMu.Lock()
|
f.warnedMu.Lock()
|
||||||
@@ -457,7 +523,7 @@ func (f *Fs) cleanRemote(dir, filename string) (remote string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fs) localPath(name string) string {
|
func (f *Fs) localPath(name string) string {
|
||||||
return filepath.Join(f.root, filepath.FromSlash(enc.FromStandardPath(name)))
|
return filepath.Join(f.root, filepath.FromSlash(f.opt.Enc.FromStandardPath(name)))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Put the Object to the local filesystem
|
// Put the Object to the local filesystem
|
||||||
@@ -503,6 +569,10 @@ func (f *Fs) Rmdir(ctx context.Context, dir string) error {
|
|||||||
|
|
||||||
// Precision of the file system
|
// Precision of the file system
|
||||||
func (f *Fs) Precision() (precision time.Duration) {
|
func (f *Fs) Precision() (precision time.Duration) {
|
||||||
|
if f.opt.NoSetModTime {
|
||||||
|
return fs.ModTimeNotSupported
|
||||||
|
}
|
||||||
|
|
||||||
f.precisionOk.Do(func() {
|
f.precisionOk.Do(func() {
|
||||||
f.precision = f.readPrecision()
|
f.precision = f.readPrecision()
|
||||||
})
|
})
|
||||||
@@ -561,23 +631,28 @@ func (f *Fs) readPrecision() (precision time.Duration) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Purge deletes all the files and directories
|
// Purge deletes all the files in the directory
|
||||||
//
|
//
|
||||||
// Optional interface: Only implement this if you have a way of
|
// Optional interface: Only implement this if you have a way of
|
||||||
// deleting all the files quicker than just running Remove() on the
|
// deleting all the files quicker than just running Remove() on the
|
||||||
// result of List()
|
// result of List()
|
||||||
func (f *Fs) Purge(ctx context.Context) error {
|
func (f *Fs) Purge(ctx context.Context, dir string) error {
|
||||||
fi, err := f.lstat(f.root)
|
dir = f.localPath(dir)
|
||||||
|
fi, err := f.lstat(dir)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
// already purged
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
return fs.ErrorDirNotFound
|
||||||
|
}
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if !fi.Mode().IsDir() {
|
if !fi.Mode().IsDir() {
|
||||||
return errors.Errorf("can't purge non directory: %q", f.root)
|
return errors.Errorf("can't purge non directory: %q", dir)
|
||||||
}
|
}
|
||||||
return os.RemoveAll(f.root)
|
return os.RemoveAll(dir)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Move src to this remote using server side move operations.
|
// Move src to this remote using server-side move operations.
|
||||||
//
|
//
|
||||||
// This is stored with the remote path given
|
// This is stored with the remote path given
|
||||||
//
|
//
|
||||||
@@ -595,6 +670,9 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
|
|
||||||
// Temporary Object under construction
|
// Temporary Object under construction
|
||||||
dstObj := f.newObject(remote)
|
dstObj := f.newObject(remote)
|
||||||
|
dstObj.fs.objectMetaMu.RLock()
|
||||||
|
dstObjMode := dstObj.mode
|
||||||
|
dstObj.fs.objectMetaMu.RUnlock()
|
||||||
|
|
||||||
// Check it is a file if it exists
|
// Check it is a file if it exists
|
||||||
err := dstObj.lstat()
|
err := dstObj.lstat()
|
||||||
@@ -602,7 +680,7 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
// OK
|
// OK
|
||||||
} else if err != nil {
|
} else if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
} else if !dstObj.fs.isRegular(dstObj.mode) {
|
} else if !dstObj.fs.isRegular(dstObjMode) {
|
||||||
// It isn't a file
|
// It isn't a file
|
||||||
return nil, errors.New("can't move file onto non-file")
|
return nil, errors.New("can't move file onto non-file")
|
||||||
}
|
}
|
||||||
@@ -638,7 +716,7 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DirMove moves src, srcRemote to this remote at dstRemote
|
// DirMove moves src, srcRemote to this remote at dstRemote
|
||||||
// using server side move operations.
|
// using server-side move operations.
|
||||||
//
|
//
|
||||||
// Will only be called if src.Fs().Name() == f.Name()
|
// Will only be called if src.Fs().Name() == f.Name()
|
||||||
//
|
//
|
||||||
@@ -689,6 +767,50 @@ func (f *Fs) Hashes() hash.Set {
|
|||||||
return hash.Supported()
|
return hash.Supported()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var commandHelp = []fs.CommandHelp{
|
||||||
|
{
|
||||||
|
Name: "noop",
|
||||||
|
Short: "A null operation for testing backend commands",
|
||||||
|
Long: `This is a test command which has some options
|
||||||
|
you can try to change the output.`,
|
||||||
|
Opts: map[string]string{
|
||||||
|
"echo": "echo the input arguments",
|
||||||
|
"error": "return an error based on option value",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// Command the backend to run a named command
|
||||||
|
//
|
||||||
|
// The command run is name
|
||||||
|
// args may be used to read arguments from
|
||||||
|
// opts may be used to read optional arguments from
|
||||||
|
//
|
||||||
|
// The result should be capable of being JSON encoded
|
||||||
|
// If it is a string or a []string it will be shown to the user
|
||||||
|
// otherwise it will be JSON encoded and shown to the user like that
|
||||||
|
func (f *Fs) Command(ctx context.Context, name string, arg []string, opt map[string]string) (interface{}, error) {
|
||||||
|
switch name {
|
||||||
|
case "noop":
|
||||||
|
if txt, ok := opt["error"]; ok {
|
||||||
|
if txt == "" {
|
||||||
|
txt = "unspecified error"
|
||||||
|
}
|
||||||
|
return nil, errors.New(txt)
|
||||||
|
}
|
||||||
|
if _, ok := opt["echo"]; ok {
|
||||||
|
out := map[string]interface{}{}
|
||||||
|
out["name"] = name
|
||||||
|
out["arg"] = arg
|
||||||
|
out["opt"] = opt
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
default:
|
||||||
|
return nil, fs.ErrorCommandNotFound
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------
|
// ------------------------------------------------------------
|
||||||
|
|
||||||
// Fs returns the parent Fs
|
// Fs returns the parent Fs
|
||||||
@@ -712,19 +834,31 @@ func (o *Object) Remote() string {
|
|||||||
// Hash returns the requested hash of a file as a lowercase hex string
|
// Hash returns the requested hash of a file as a lowercase hex string
|
||||||
func (o *Object) Hash(ctx context.Context, r hash.Type) (string, error) {
|
func (o *Object) Hash(ctx context.Context, r hash.Type) (string, error) {
|
||||||
// Check that the underlying file hasn't changed
|
// Check that the underlying file hasn't changed
|
||||||
|
o.fs.objectMetaMu.RLock()
|
||||||
oldtime := o.modTime
|
oldtime := o.modTime
|
||||||
oldsize := o.size
|
oldsize := o.size
|
||||||
|
o.fs.objectMetaMu.RUnlock()
|
||||||
err := o.lstat()
|
err := o.lstat()
|
||||||
|
var changed bool
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", errors.Wrap(err, "hash: failed to stat")
|
if os.IsNotExist(errors.Cause(err)) {
|
||||||
|
// If file not found then we assume any accumulated
|
||||||
|
// hashes are OK - this will error on Open
|
||||||
|
changed = true
|
||||||
|
} else {
|
||||||
|
return "", errors.Wrap(err, "hash: failed to stat")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
o.fs.objectMetaMu.RLock()
|
||||||
|
changed = !o.modTime.Equal(oldtime) || oldsize != o.size
|
||||||
|
o.fs.objectMetaMu.RUnlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
o.fs.objectHashesMu.Lock()
|
o.fs.objectMetaMu.RLock()
|
||||||
hashes := o.hashes
|
|
||||||
hashValue, hashFound := o.hashes[r]
|
hashValue, hashFound := o.hashes[r]
|
||||||
o.fs.objectHashesMu.Unlock()
|
o.fs.objectMetaMu.RUnlock()
|
||||||
|
|
||||||
if !o.modTime.Equal(oldtime) || oldsize != o.size || hashes == nil || !hashFound {
|
if changed || !hashFound {
|
||||||
var in io.ReadCloser
|
var in io.ReadCloser
|
||||||
|
|
||||||
if !o.translatedLink {
|
if !o.translatedLink {
|
||||||
@@ -736,9 +870,14 @@ func (o *Object) Hash(ctx context.Context, r hash.Type) (string, error) {
|
|||||||
} else {
|
} else {
|
||||||
in, err = o.openTranslatedLink(0, -1)
|
in, err = o.openTranslatedLink(0, -1)
|
||||||
}
|
}
|
||||||
|
// If not checking for updates, only read size given
|
||||||
|
if o.fs.opt.NoCheckUpdated {
|
||||||
|
in = readers.NewLimitedReadCloser(in, o.size)
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", errors.Wrap(err, "hash: failed to open")
|
return "", errors.Wrap(err, "hash: failed to open")
|
||||||
}
|
}
|
||||||
|
var hashes map[hash.Type]string
|
||||||
hashes, err = hash.StreamTypes(in, hash.NewHashSet(r))
|
hashes, err = hash.StreamTypes(in, hash.NewHashSet(r))
|
||||||
closeErr := in.Close()
|
closeErr := in.Close()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -748,29 +887,36 @@ func (o *Object) Hash(ctx context.Context, r hash.Type) (string, error) {
|
|||||||
return "", errors.Wrap(closeErr, "hash: failed to close")
|
return "", errors.Wrap(closeErr, "hash: failed to close")
|
||||||
}
|
}
|
||||||
hashValue = hashes[r]
|
hashValue = hashes[r]
|
||||||
o.fs.objectHashesMu.Lock()
|
o.fs.objectMetaMu.Lock()
|
||||||
if o.hashes == nil {
|
if o.hashes == nil {
|
||||||
o.hashes = hashes
|
o.hashes = hashes
|
||||||
} else {
|
} else {
|
||||||
o.hashes[r] = hashValue
|
o.hashes[r] = hashValue
|
||||||
}
|
}
|
||||||
o.fs.objectHashesMu.Unlock()
|
o.fs.objectMetaMu.Unlock()
|
||||||
}
|
}
|
||||||
return hashValue, nil
|
return hashValue, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Size returns the size of an object in bytes
|
// Size returns the size of an object in bytes
|
||||||
func (o *Object) Size() int64 {
|
func (o *Object) Size() int64 {
|
||||||
|
o.fs.objectMetaMu.RLock()
|
||||||
|
defer o.fs.objectMetaMu.RUnlock()
|
||||||
return o.size
|
return o.size
|
||||||
}
|
}
|
||||||
|
|
||||||
// ModTime returns the modification time of the object
|
// ModTime returns the modification time of the object
|
||||||
func (o *Object) ModTime(ctx context.Context) time.Time {
|
func (o *Object) ModTime(ctx context.Context) time.Time {
|
||||||
|
o.fs.objectMetaMu.RLock()
|
||||||
|
defer o.fs.objectMetaMu.RUnlock()
|
||||||
return o.modTime
|
return o.modTime
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetModTime sets the modification time of the local fs object
|
// SetModTime sets the modification time of the local fs object
|
||||||
func (o *Object) SetModTime(ctx context.Context, modTime time.Time) error {
|
func (o *Object) SetModTime(ctx context.Context, modTime time.Time) error {
|
||||||
|
if o.fs.opt.NoSetModTime {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
var err error
|
var err error
|
||||||
if o.translatedLink {
|
if o.translatedLink {
|
||||||
err = lChtimes(o.path, modTime, modTime)
|
err = lChtimes(o.path, modTime, modTime)
|
||||||
@@ -786,7 +932,9 @@ func (o *Object) SetModTime(ctx context.Context, modTime time.Time) error {
|
|||||||
|
|
||||||
// Storable returns a boolean showing if this object is storable
|
// Storable returns a boolean showing if this object is storable
|
||||||
func (o *Object) Storable() bool {
|
func (o *Object) Storable() bool {
|
||||||
|
o.fs.objectMetaMu.RLock()
|
||||||
mode := o.mode
|
mode := o.mode
|
||||||
|
o.fs.objectMetaMu.RUnlock()
|
||||||
if mode&os.ModeSymlink != 0 && !o.fs.opt.TranslateSymlinks {
|
if mode&os.ModeSymlink != 0 && !o.fs.opt.TranslateSymlinks {
|
||||||
if !o.fs.opt.SkipSymlinks {
|
if !o.fs.opt.SkipSymlinks {
|
||||||
fs.Logf(o, "Can't follow symlink without -L/--copy-links")
|
fs.Logf(o, "Can't follow symlink without -L/--copy-links")
|
||||||
@@ -819,11 +967,15 @@ func (file *localOpenFile) Read(p []byte) (n int, err error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, errors.Wrap(err, "can't read status of source file while transferring")
|
return 0, errors.Wrap(err, "can't read status of source file while transferring")
|
||||||
}
|
}
|
||||||
if file.o.size != fi.Size() {
|
file.o.fs.objectMetaMu.RLock()
|
||||||
return 0, fserrors.NoLowLevelRetryError(errors.Errorf("can't copy - source file is being updated (size changed from %d to %d)", file.o.size, fi.Size()))
|
oldtime := file.o.modTime
|
||||||
|
oldsize := file.o.size
|
||||||
|
file.o.fs.objectMetaMu.RUnlock()
|
||||||
|
if oldsize != fi.Size() {
|
||||||
|
return 0, fserrors.NoLowLevelRetryError(errors.Errorf("can't copy - source file is being updated (size changed from %d to %d)", oldsize, fi.Size()))
|
||||||
}
|
}
|
||||||
if !file.o.modTime.Equal(fi.ModTime()) {
|
if !oldtime.Equal(fi.ModTime()) {
|
||||||
return 0, fserrors.NoLowLevelRetryError(errors.Errorf("can't copy - source file is being updated (mod time changed from %v to %v)", file.o.modTime, fi.ModTime()))
|
return 0, fserrors.NoLowLevelRetryError(errors.Errorf("can't copy - source file is being updated (mod time changed from %v to %v)", oldtime, fi.ModTime()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -840,9 +992,9 @@ func (file *localOpenFile) Close() (err error) {
|
|||||||
err = file.in.Close()
|
err = file.in.Close()
|
||||||
if err == nil {
|
if err == nil {
|
||||||
if file.hash.Size() == file.o.Size() {
|
if file.hash.Size() == file.o.Size() {
|
||||||
file.o.fs.objectHashesMu.Lock()
|
file.o.fs.objectMetaMu.Lock()
|
||||||
file.o.hashes = file.hash.Sums()
|
file.o.hashes = file.hash.Sums()
|
||||||
file.o.fs.objectHashesMu.Unlock()
|
file.o.fs.objectMetaMu.Unlock()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return err
|
return err
|
||||||
@@ -867,7 +1019,7 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.Read
|
|||||||
case *fs.SeekOption:
|
case *fs.SeekOption:
|
||||||
offset = x.Offset
|
offset = x.Offset
|
||||||
case *fs.RangeOption:
|
case *fs.RangeOption:
|
||||||
offset, limit = x.Decode(o.size)
|
offset, limit = x.Decode(o.Size())
|
||||||
case *fs.HashesOption:
|
case *fs.HashesOption:
|
||||||
if x.Hashes.Count() > 0 {
|
if x.Hashes.Count() > 0 {
|
||||||
hasher, err = hash.NewMultiHasherTypes(x.Hashes)
|
hasher, err = hash.NewMultiHasherTypes(x.Hashes)
|
||||||
@@ -882,6 +1034,13 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.Read
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// If not checking updated then limit to current size. This means if
|
||||||
|
// file is being extended, readers will read a o.Size() bytes rather
|
||||||
|
// than the new size making for a consistent upload.
|
||||||
|
if limit < 0 && o.fs.opt.NoCheckUpdated {
|
||||||
|
limit = o.size
|
||||||
|
}
|
||||||
|
|
||||||
// Handle a translated link
|
// Handle a translated link
|
||||||
if o.translatedLink {
|
if o.translatedLink {
|
||||||
return o.openTranslatedLink(offset, limit)
|
return o.openTranslatedLink(offset, limit)
|
||||||
@@ -969,7 +1128,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Pre-allocate the file for performance reasons
|
// Pre-allocate the file for performance reasons
|
||||||
err = preAllocate(src.Size(), f)
|
err = file.PreAllocate(src.Size(), f)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fs.Debugf(o, "Failed to pre-allocate: %v", err)
|
fs.Debugf(o, "Failed to pre-allocate: %v", err)
|
||||||
}
|
}
|
||||||
@@ -1018,9 +1177,9 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
|
|
||||||
// All successful so update the hashes
|
// All successful so update the hashes
|
||||||
if hasher != nil {
|
if hasher != nil {
|
||||||
o.fs.objectHashesMu.Lock()
|
o.fs.objectMetaMu.Lock()
|
||||||
o.hashes = hasher.Sums()
|
o.hashes = hasher.Sums()
|
||||||
o.fs.objectHashesMu.Unlock()
|
o.fs.objectMetaMu.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set the mtime
|
// Set the mtime
|
||||||
@@ -1033,6 +1192,8 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
return o.lstat()
|
return o.lstat()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var sparseWarning sync.Once
|
||||||
|
|
||||||
// OpenWriterAt opens with a handle for random access writes
|
// OpenWriterAt opens with a handle for random access writes
|
||||||
//
|
//
|
||||||
// Pass in the remote desired and the size if known.
|
// Pass in the remote desired and the size if known.
|
||||||
@@ -1056,29 +1217,48 @@ func (f *Fs) OpenWriterAt(ctx context.Context, remote string, size int64) (fs.Wr
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
// Pre-allocate the file for performance reasons
|
// Pre-allocate the file for performance reasons
|
||||||
err = preAllocate(size, out)
|
err = file.PreAllocate(size, out)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fs.Debugf(o, "Failed to pre-allocate: %v", err)
|
fs.Debugf(o, "Failed to pre-allocate: %v", err)
|
||||||
}
|
}
|
||||||
|
if !f.opt.NoSparse && file.SetSparseImplemented {
|
||||||
|
sparseWarning.Do(func() {
|
||||||
|
fs.Infof(nil, "Writing sparse files: use --local-no-sparse or --multi-thread-streams 0 to disable")
|
||||||
|
})
|
||||||
|
// Set the file to be a sparse file (important on Windows)
|
||||||
|
err = file.SetSparse(out)
|
||||||
|
if err != nil {
|
||||||
|
fs.Errorf(o, "Failed to set sparse: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// setMetadata sets the file info from the os.FileInfo passed in
|
// setMetadata sets the file info from the os.FileInfo passed in
|
||||||
func (o *Object) setMetadata(info os.FileInfo) {
|
func (o *Object) setMetadata(info os.FileInfo) {
|
||||||
// Don't overwrite the info if we don't need to
|
// if not checking updated then don't update the stat
|
||||||
// this avoids upsetting the race detector
|
if o.fs.opt.NoCheckUpdated && !o.modTime.IsZero() {
|
||||||
if o.size != info.Size() {
|
return
|
||||||
o.size = info.Size()
|
|
||||||
}
|
}
|
||||||
if !o.modTime.Equal(info.ModTime()) {
|
o.fs.objectMetaMu.Lock()
|
||||||
o.modTime = info.ModTime()
|
o.size = info.Size()
|
||||||
}
|
o.modTime = info.ModTime()
|
||||||
if o.mode != info.Mode() {
|
o.mode = info.Mode()
|
||||||
o.mode = info.Mode()
|
o.fs.objectMetaMu.Unlock()
|
||||||
|
// On Windows links read as 0 size so set the correct size here
|
||||||
|
// Optionally, users can turn this feature on with the zero_size_links flag
|
||||||
|
if (runtime.GOOS == "windows" || o.fs.opt.ZeroSizeLinks) && o.translatedLink {
|
||||||
|
linkdst, err := os.Readlink(o.path)
|
||||||
|
if err != nil {
|
||||||
|
fs.Errorf(o, "Failed to read link size: %v", err)
|
||||||
|
} else {
|
||||||
|
o.size = int64(len(linkdst))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stat a Object into info
|
// Stat an Object into info
|
||||||
func (o *Object) lstat() error {
|
func (o *Object) lstat() error {
|
||||||
info, err := o.fs.lstat(o.path)
|
info, err := o.fs.lstat(o.path)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
@@ -1092,7 +1272,7 @@ func (o *Object) Remove(ctx context.Context) error {
|
|||||||
return remove(o.path)
|
return remove(o.path)
|
||||||
}
|
}
|
||||||
|
|
||||||
func cleanRootPath(s string, noUNC bool) string {
|
func cleanRootPath(s string, noUNC bool, enc encoder.MultiEncoder) string {
|
||||||
if runtime.GOOS == "windows" {
|
if runtime.GOOS == "windows" {
|
||||||
if !filepath.IsAbs(s) && !strings.HasPrefix(s, "\\") {
|
if !filepath.IsAbs(s) && !strings.HasPrefix(s, "\\") {
|
||||||
s2, err := filepath.Abs(s)
|
s2, err := filepath.Abs(s)
|
||||||
@@ -1107,7 +1287,7 @@ func cleanRootPath(s string, noUNC bool) string {
|
|||||||
|
|
||||||
if !noUNC {
|
if !noUNC {
|
||||||
// Convert to UNC
|
// Convert to UNC
|
||||||
s = uncPath(s)
|
s = file.UNCPath(s)
|
||||||
}
|
}
|
||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
@@ -1121,28 +1301,6 @@ func cleanRootPath(s string, noUNC bool) string {
|
|||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pattern to match a windows absolute path: "c:\" and similar
|
|
||||||
var isAbsWinDrive = regexp.MustCompile(`^[a-zA-Z]\:\\`)
|
|
||||||
|
|
||||||
// uncPath converts an absolute Windows path
|
|
||||||
// to a UNC long path.
|
|
||||||
func uncPath(l string) string {
|
|
||||||
// If prefix is "\\", we already have a UNC path or server.
|
|
||||||
if strings.HasPrefix(l, `\\`) {
|
|
||||||
// If already long path, just keep it
|
|
||||||
if strings.HasPrefix(l, `\\?\`) {
|
|
||||||
return l
|
|
||||||
}
|
|
||||||
|
|
||||||
// Trim "\\" from path and add UNC prefix.
|
|
||||||
return `\\?\UNC\` + strings.TrimPrefix(l, `\\`)
|
|
||||||
}
|
|
||||||
if isAbsWinDrive.MatchString(l) {
|
|
||||||
return `\\?\` + l
|
|
||||||
}
|
|
||||||
return l
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check the interfaces are satisfied
|
// Check the interfaces are satisfied
|
||||||
var (
|
var (
|
||||||
_ fs.Fs = &Fs{}
|
_ fs.Fs = &Fs{}
|
||||||
@@ -1150,6 +1308,7 @@ var (
|
|||||||
_ fs.PutStreamer = &Fs{}
|
_ fs.PutStreamer = &Fs{}
|
||||||
_ fs.Mover = &Fs{}
|
_ fs.Mover = &Fs{}
|
||||||
_ fs.DirMover = &Fs{}
|
_ fs.DirMover = &Fs{}
|
||||||
|
_ fs.Commander = &Fs{}
|
||||||
_ fs.OpenWriterAter = &Fs{}
|
_ fs.OpenWriterAter = &Fs{}
|
||||||
_ fs.Object = &Object{}
|
_ fs.Object = &Object{}
|
||||||
)
|
)
|
||||||
@@ -6,7 +6,6 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"runtime"
|
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -89,9 +88,6 @@ func TestSymlink(t *testing.T) {
|
|||||||
|
|
||||||
// Object viewed as symlink
|
// Object viewed as symlink
|
||||||
file2 := fstest.NewItem("symlink.txt"+linkSuffix, "file.txt", modTime2)
|
file2 := fstest.NewItem("symlink.txt"+linkSuffix, "file.txt", modTime2)
|
||||||
if runtime.GOOS == "windows" {
|
|
||||||
file2.Size = 0 // symlinks are 0 length under Windows
|
|
||||||
}
|
|
||||||
|
|
||||||
// Object viewed as destination
|
// Object viewed as destination
|
||||||
file2d := fstest.NewItem("symlink.txt", "hello", modTime1)
|
file2d := fstest.NewItem("symlink.txt", "hello", modTime1)
|
||||||
@@ -121,9 +117,6 @@ func TestSymlink(t *testing.T) {
|
|||||||
// Create a symlink
|
// Create a symlink
|
||||||
modTime3 := fstest.Time("2002-03-03T04:05:10.123123123Z")
|
modTime3 := fstest.Time("2002-03-03T04:05:10.123123123Z")
|
||||||
file3 := r.WriteObjectTo(ctx, r.Flocal, "symlink2.txt"+linkSuffix, "file.txt", modTime3, false)
|
file3 := r.WriteObjectTo(ctx, r.Flocal, "symlink2.txt"+linkSuffix, "file.txt", modTime3, false)
|
||||||
if runtime.GOOS == "windows" {
|
|
||||||
file3.Size = 0 // symlinks are 0 length under Windows
|
|
||||||
}
|
|
||||||
fstest.CheckListingWithPrecision(t, r.Flocal, []fstest.Item{file1, file2, file3}, nil, fs.ModTimeNotSupported)
|
fstest.CheckListingWithPrecision(t, r.Flocal, []fstest.Item{file1, file2, file3}, nil, fs.ModTimeNotSupported)
|
||||||
if haveLChtimes {
|
if haveLChtimes {
|
||||||
fstest.CheckItems(t, r.Flocal, file1, file2, file3)
|
fstest.CheckItems(t, r.Flocal, file1, file2, file3)
|
||||||
@@ -142,9 +135,7 @@ func TestSymlink(t *testing.T) {
|
|||||||
o, err := r.Flocal.NewObject(ctx, "symlink2.txt"+linkSuffix)
|
o, err := r.Flocal.NewObject(ctx, "symlink2.txt"+linkSuffix)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
assert.Equal(t, "symlink2.txt"+linkSuffix, o.Remote())
|
assert.Equal(t, "symlink2.txt"+linkSuffix, o.Remote())
|
||||||
if runtime.GOOS != "windows" {
|
assert.Equal(t, int64(8), o.Size())
|
||||||
assert.Equal(t, int64(8), o.Size())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check that NewObject doesn't see the non suffixed version
|
// Check that NewObject doesn't see the non suffixed version
|
||||||
_, err = r.Flocal.NewObject(ctx, "symlink2.txt")
|
_, err = r.Flocal.NewObject(ctx, "symlink2.txt")
|
||||||
@@ -172,6 +163,6 @@ func TestSymlinkError(t *testing.T) {
|
|||||||
"links": "true",
|
"links": "true",
|
||||||
"copy_links": "true",
|
"copy_links": "true",
|
||||||
}
|
}
|
||||||
_, err := NewFs("local", "/", m)
|
_, err := NewFs(context.Background(), "local", "/", m)
|
||||||
assert.Equal(t, errLinksAndCopyLinks, err)
|
assert.Equal(t, errLinksAndCopyLinks, err)
|
||||||
}
|
}
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
//+build !windows,!linux
|
|
||||||
|
|
||||||
package local
|
|
||||||
|
|
||||||
import "os"
|
|
||||||
|
|
||||||
// preAllocate the file for performance reasons
|
|
||||||
func preAllocate(size int64, out *os.File) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
Loaded 100 of 2744 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user