Compare commits
747
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c741c02fb6 | ||
|
|
56e8d75cab | ||
|
|
e74f5b8906 | ||
|
|
e4a7686444 | ||
|
|
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 |
No files matched your search
@@ -0,0 +1,4 @@
|
|||||||
|
github: [ncw]
|
||||||
|
patreon: njcw
|
||||||
|
liberapay: ncw
|
||||||
|
custom: ["https://rclone.org/donate/"]
|
||||||
@@ -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.
|
||||||
+44
-42
@@ -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.11', 'go1.12', 'go1.13']
|
job_name: ['linux', 'mac', 'windows_amd64', 'windows_386', 'other_os', 'go1.11', 'go1.12', 'go1.13', 'go1.14']
|
||||||
|
|
||||||
include:
|
include:
|
||||||
- job_name: linux
|
- job_name: linux
|
||||||
os: ubuntu-latest
|
os: ubuntu-latest
|
||||||
go: '1.14.x'
|
go: '1.15.x'
|
||||||
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.14.x'
|
go: '1.15.x'
|
||||||
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,8 +43,7 @@ jobs:
|
|||||||
|
|
||||||
- job_name: windows_amd64
|
- job_name: windows_amd64
|
||||||
os: windows-latest
|
os: windows-latest
|
||||||
go: '1.14.x'
|
go: '1.15.x'
|
||||||
modules: 'off'
|
|
||||||
gotags: cmount
|
gotags: cmount
|
||||||
build_flags: '-include "^windows/amd64" -cgo'
|
build_flags: '-include "^windows/amd64" -cgo'
|
||||||
quicktest: true
|
quicktest: true
|
||||||
@@ -54,8 +52,7 @@ jobs:
|
|||||||
|
|
||||||
- job_name: windows_386
|
- job_name: windows_386
|
||||||
os: windows-latest
|
os: windows-latest
|
||||||
go: '1.14.x'
|
go: '1.15.x'
|
||||||
modules: 'off'
|
|
||||||
gotags: cmount
|
gotags: cmount
|
||||||
goarch: '386'
|
goarch: '386'
|
||||||
cgo: '1'
|
cgo: '1'
|
||||||
@@ -65,59 +62,51 @@ jobs:
|
|||||||
|
|
||||||
- job_name: other_os
|
- job_name: other_os
|
||||||
os: ubuntu-latest
|
os: ubuntu-latest
|
||||||
go: '1.14.x'
|
go: '1.15.x'
|
||||||
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
|
|
||||||
os: ubuntu-latest
|
|
||||||
go: '1.14.x'
|
|
||||||
modules: 'on'
|
|
||||||
quicktest: true
|
|
||||||
racequicktest: true
|
|
||||||
|
|
||||||
- job_name: go1.11
|
- job_name: go1.11
|
||||||
os: ubuntu-latest
|
os: ubuntu-latest
|
||||||
go: '1.11.x'
|
go: '1.11.x'
|
||||||
modules: 'off'
|
|
||||||
quicktest: true
|
quicktest: true
|
||||||
|
|
||||||
- job_name: go1.12
|
- job_name: go1.12
|
||||||
os: ubuntu-latest
|
os: ubuntu-latest
|
||||||
go: '1.12.x'
|
go: '1.12.x'
|
||||||
modules: 'off'
|
|
||||||
quicktest: true
|
quicktest: true
|
||||||
|
|
||||||
- job_name: go1.13
|
- job_name: go1.13
|
||||||
os: ubuntu-latest
|
os: ubuntu-latest
|
||||||
go: '1.13.x'
|
go: '1.13.x'
|
||||||
modules: 'off'
|
|
||||||
quicktest: true
|
quicktest: true
|
||||||
|
|
||||||
|
- job_name: go1.14
|
||||||
|
os: ubuntu-latest
|
||||||
|
go: '1.14.x'
|
||||||
|
quicktest: true
|
||||||
|
racequicktest: true
|
||||||
|
|
||||||
name: ${{ matrix.job_name }}
|
name: ${{ matrix.job_name }}
|
||||||
|
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
|
|
||||||
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 '::add-path::${{ runner.workspace }}/bin'
|
|
||||||
echo '::set-env name=GO111MODULE::${{ matrix.modules }}'
|
|
||||||
echo '::set-env name=GOTAGS::${{ matrix.gotags }}'
|
echo '::set-env name=GOTAGS::${{ matrix.gotags }}'
|
||||||
echo '::set-env name=BUILD_FLAGS::${{ matrix.build_flags }}'
|
echo '::set-env name=BUILD_FLAGS::${{ matrix.build_flags }}'
|
||||||
if [[ "${{ matrix.goarch }}" != "" ]]; then echo '::set-env name=GOARCH::${{ matrix.goarch }}' ; fi
|
if [[ "${{ matrix.goarch }}" != "" ]]; then echo '::set-env name=GOARCH::${{ matrix.goarch }}' ; fi
|
||||||
@@ -167,10 +156,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 +198,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)'
|
||||||
@@ -227,13 +229,13 @@ jobs:
|
|||||||
- 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 +243,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@439099796bfc03dd9cedeb72a0c7cb92be5cc92c
|
||||||
|
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@439099796bfc03dd9cedeb72a0c7cb92be5cc92c
|
||||||
|
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 }}
|
||||||
@@ -9,3 +9,4 @@ rclone.iml
|
|||||||
*.test
|
*.test
|
||||||
*.log
|
*.log
|
||||||
*.iml
|
*.iml
|
||||||
|
fuzz-build.zip
|
||||||
+17
-27
@@ -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 reccommends wizardzines.com
|
||||||
|
```
|
||||||
|
|
||||||
## CI for your fork ##
|
## CI for your fork ##
|
||||||
|
|
||||||
@@ -158,7 +165,7 @@ 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
|
||||||
@@ -179,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 ##
|
||||||
@@ -259,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 ##
|
||||||
|
|
||||||
@@ -383,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/
|
||||||
|
|
||||||
|
|||||||
+15
-12
@@ -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 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,7 +33,7 @@ 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
|
||||||
|
|||||||
Generated
+12351
-9589
File diff suppressed because it is too large.
Load diff
Generated
+14307
-9821
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
|
||||||
@@ -57,10 +59,13 @@ vars:
|
|||||||
@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,43 @@ 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'
|
go run bin/get-github-release.go -extract nfpm goreleaser/nfpm 'nfpm_.*_Linux_x86_64.tar.gz'
|
||||||
go run bin/get-github-release.go -extract github-release aktau/github-release 'linux-amd64-github-release.tar.bz2'
|
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 +149,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
|
||||||
@@ -175,14 +201,7 @@ log_since_last_release:
|
|||||||
compile_all:
|
compile_all:
|
||||||
go run bin/cross-compile.go -compile-only $(BUILDTAGS) $(TAG)
|
go run bin/cross-compile.go -compile-only $(BUILDTAGS) $(TAG)
|
||||||
|
|
||||||
appveyor_upload:
|
ci_upload:
|
||||||
rclone --config bin/travis.rclone.conf -v copy --exclude '*beta-latest*' build/ $(BETA_UPLOAD)
|
|
||||||
ifndef BRANCH_PATH
|
|
||||||
rclone --config bin/travis.rclone.conf -v copy --include '*beta-latest*' --include version.txt build/ $(BETA_UPLOAD_ROOT)
|
|
||||||
endif
|
|
||||||
@echo Beta release ready at $(BETA_URL)
|
|
||||||
|
|
||||||
circleci_upload:
|
|
||||||
sudo chown -R $$USER build
|
sudo chown -R $$USER build
|
||||||
find build -type l -delete
|
find build -type l -delete
|
||||||
gzip -r9v build
|
gzip -r9v build
|
||||||
@@ -192,10 +211,7 @@ ifndef BRANCH_PATH
|
|||||||
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) $(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)
|
||||||
@@ -204,33 +220,40 @@ ifndef BRANCH_PATH
|
|||||||
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
|
||||||
@@ -59,9 +59,11 @@ 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)
|
* StackPath [:page_facing_up:](https://rclone.org/s3/#stackpath)
|
||||||
* SugarSync [:page_facing_up:](https://rclone.org/sugarsync/)
|
* SugarSync [:page_facing_up:](https://rclone.org/sugarsync/)
|
||||||
|
* Tardigrade [:page_facing_up:](https://rclone.org/tardigrade/)
|
||||||
* 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/)
|
||||||
|
|||||||
+26
-50
@@ -9,7 +9,7 @@ This file describes how to make the various kinds of releases
|
|||||||
|
|
||||||
## Making a release
|
## Making a release
|
||||||
|
|
||||||
* git checkout master
|
* git checkout master # see below for stable branch
|
||||||
* git pull
|
* git pull
|
||||||
* git status - make sure everything is checked in
|
* git status - make sure everything is checked in
|
||||||
* Check GitHub actions build for master is Green
|
* Check GitHub actions build for master is Green
|
||||||
@@ -25,15 +25,16 @@ This file describes how to make the various kinds of releases
|
|||||||
* # Wait for the GitHub 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
|
||||||
@@ -41,71 +42,46 @@ 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 # eg v1.52
|
||||||
|
* NEW_TAG=${BASE_TAG}.Y # eg 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
|
* NB this overwrites the current beta so we need to do this - FIXME is this true any more?
|
||||||
* 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
|
||||||
* # 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
|
||||||
```
|
```
|
||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"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"
|
||||||
@@ -46,9 +47,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(fspath.JoinRootPath(opt.Remote, root))
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return fsInfo.NewFs(configName, fspath.JoinRootPath(fsPath, root), config)
|
|
||||||
}
|
}
|
||||||
@@ -31,10 +31,12 @@ 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/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"
|
||||||
|
|||||||
@@ -71,28 +71,12 @@ func init() {
|
|||||||
Description: "Amazon Drive",
|
Description: "Amazon Drive",
|
||||||
NewFs: NewFs,
|
NewFs: NewFs,
|
||||||
Config: func(name string, m configmap.Mapper) {
|
Config: func(name string, m configmap.Mapper) {
|
||||||
err := oauthutil.Config("amazon cloud drive", name, m, acdConfig)
|
err := oauthutil.Config("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,
|
||||||
@@ -143,7 +127,7 @@ underlying S3 storage.`,
|
|||||||
// Encode invalid UTF-8 bytes as json doesn't handle them properly.
|
// Encode invalid UTF-8 bytes as json doesn't handle them properly.
|
||||||
Default: (encoder.Base |
|
Default: (encoder.Base |
|
||||||
encoder.EncodeInvalidUtf8),
|
encoder.EncodeInvalidUtf8),
|
||||||
}},
|
}}...),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -169,7 +153,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 {
|
||||||
@@ -229,7 +213,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
|
||||||
@@ -514,10 +498,6 @@ 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
|
||||||
@@ -665,7 +645,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
|
||||||
}
|
}
|
||||||
@@ -696,13 +676,7 @@ 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
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -724,10 +698,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
|
||||||
@@ -797,54 +767,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
|
||||||
}
|
}
|
||||||
@@ -890,10 +830,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
|
||||||
@@ -985,8 +921,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)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------
|
// ------------------------------------------------------------
|
||||||
@@ -1037,7 +973,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
|
||||||
|
|||||||
+191
-121
@@ -1,6 +1,6 @@
|
|||||||
// Package azureblob provides an interface to the Microsoft Azure blob object storage system
|
// Package azureblob provides an interface to the Microsoft Azure blob object storage system
|
||||||
|
|
||||||
// +build !plan9,!solaris
|
// +build !plan9,!solaris,!js,go1.13
|
||||||
|
|
||||||
package azureblob
|
package azureblob
|
||||||
|
|
||||||
@@ -9,7 +9,6 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"crypto/md5"
|
"crypto/md5"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"encoding/binary"
|
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
@@ -35,6 +34,9 @@ import (
|
|||||||
"github.com/rclone/rclone/lib/bucket"
|
"github.com/rclone/rclone/lib/bucket"
|
||||||
"github.com/rclone/rclone/lib/encoder"
|
"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/readers"
|
||||||
|
"golang.org/x/sync/errgroup"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -59,6 +61,8 @@ const (
|
|||||||
emulatorAccount = "devstoreaccount1"
|
emulatorAccount = "devstoreaccount1"
|
||||||
emulatorAccountKey = "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw=="
|
emulatorAccountKey = "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw=="
|
||||||
emulatorBlobEndpoint = "http://127.0.0.1:10000/devstoreaccount1"
|
emulatorBlobEndpoint = "http://127.0.0.1:10000/devstoreaccount1"
|
||||||
|
memoryPoolFlushTime = fs.Duration(time.Minute) // flush the cached buffers after this long
|
||||||
|
memoryPoolUseMmap = false
|
||||||
)
|
)
|
||||||
|
|
||||||
// Register with Fs
|
// Register with Fs
|
||||||
@@ -125,6 +129,28 @@ If blobs are in "archive tier" at remote, trying to perform data transfer
|
|||||||
operations from remote will not be allowed. User should first restore by
|
operations from remote will not be allowed. User should first restore by
|
||||||
tiering blob to "Hot" or "Cool".`,
|
tiering blob to "Hot" or "Cool".`,
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: "disable_checksum",
|
||||||
|
Help: `Don't store MD5 checksum with object metadata.
|
||||||
|
|
||||||
|
Normally rclone will calculate the MD5 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,
|
||||||
|
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,
|
Name: config.ConfigEncoding,
|
||||||
Help: config.ConfigEncodingHelp,
|
Help: config.ConfigEncodingHelp,
|
||||||
@@ -141,16 +167,19 @@ tiering blob to "Hot" or "Cool".`,
|
|||||||
|
|
||||||
// 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"`
|
||||||
SASURL string `config:"sas_url"`
|
SASURL string `config:"sas_url"`
|
||||||
UploadCutoff fs.SizeSuffix `config:"upload_cutoff"`
|
UploadCutoff fs.SizeSuffix `config:"upload_cutoff"`
|
||||||
ChunkSize fs.SizeSuffix `config:"chunk_size"`
|
ChunkSize fs.SizeSuffix `config:"chunk_size"`
|
||||||
ListChunkSize uint `config:"list_chunk"`
|
ListChunkSize uint `config:"list_chunk"`
|
||||||
AccessTier string `config:"access_tier"`
|
AccessTier string `config:"access_tier"`
|
||||||
UseEmulator bool `config:"use_emulator"`
|
UseEmulator bool `config:"use_emulator"`
|
||||||
Enc encoder.MultiEncoder `config:"encoding"`
|
DisableCheckSum bool `config:"disable_checksum"`
|
||||||
|
MemoryPoolFlushTime fs.Duration `config:"memory_pool_flush_time"`
|
||||||
|
MemoryPoolUseMmap bool `config:"memory_pool_use_mmap"`
|
||||||
|
Enc encoder.MultiEncoder `config:"encoding"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fs represents a remote azure server
|
// Fs represents a remote azure server
|
||||||
@@ -169,9 +198,10 @@ type Fs struct {
|
|||||||
cache *bucket.Cache // cache for container creation status
|
cache *bucket.Cache // cache for container creation status
|
||||||
pacer *fs.Pacer // To pace and retry the API calls
|
pacer *fs.Pacer // To pace and retry the API calls
|
||||||
uploadToken *pacer.TokenDispenser // control concurrency
|
uploadToken *pacer.TokenDispenser // control concurrency
|
||||||
|
pool *pool.Pool // memory pool
|
||||||
}
|
}
|
||||||
|
|
||||||
// Object describes a azure object
|
// Object describes an azure object
|
||||||
type Object struct {
|
type Object struct {
|
||||||
fs *Fs // what this object is part of
|
fs *Fs // what this object is part of
|
||||||
remote string // The remote path
|
remote string // The remote path
|
||||||
@@ -257,6 +287,12 @@ var retryErrorCodes = []int{
|
|||||||
func (f *Fs) shouldRetry(err error) (bool, error) {
|
func (f *Fs) shouldRetry(err error) (bool, error) {
|
||||||
// FIXME interpret special errors - more to do here
|
// FIXME interpret special errors - more to do here
|
||||||
if storageErr, ok := err.(azblob.StorageError); ok {
|
if storageErr, ok := err.(azblob.StorageError); ok {
|
||||||
|
switch storageErr.ServiceCode() {
|
||||||
|
case "InvalidBlobOrBlock":
|
||||||
|
// These errors happen sometimes in multipart uploads
|
||||||
|
// because of block concurrency issues
|
||||||
|
return true, err
|
||||||
|
}
|
||||||
statusCode := storageErr.Response().StatusCode
|
statusCode := storageErr.Response().StatusCode
|
||||||
for _, e := range retryErrorCodes {
|
for _, e := range retryErrorCodes {
|
||||||
if statusCode == e {
|
if statusCode == e {
|
||||||
@@ -302,7 +338,7 @@ func (f *Fs) setUploadCutoff(cs fs.SizeSuffix) (old fs.SizeSuffix, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// httpClientFactory creates a Factory object that sends HTTP requests
|
// httpClientFactory creates a Factory object that sends HTTP requests
|
||||||
// to a rclone's http.Client.
|
// to an rclone's http.Client.
|
||||||
//
|
//
|
||||||
// copied from azblob.newDefaultHTTPClientFactory
|
// copied from azblob.newDefaultHTTPClientFactory
|
||||||
func httpClientFactory(client *http.Client) pipeline.Factory {
|
func httpClientFactory(client *http.Client) pipeline.Factory {
|
||||||
@@ -382,6 +418,12 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
client: fshttp.NewClient(fs.Config),
|
client: fshttp.NewClient(fs.Config),
|
||||||
cache: bucket.NewCache(),
|
cache: bucket.NewCache(),
|
||||||
cntURLcache: make(map[string]*azblob.ContainerURL, 1),
|
cntURLcache: make(map[string]*azblob.ContainerURL, 1),
|
||||||
|
pool: pool.New(
|
||||||
|
time.Duration(opt.MemoryPoolFlushTime),
|
||||||
|
int(opt.ChunkSize),
|
||||||
|
fs.Config.Transfers,
|
||||||
|
opt.MemoryPoolUseMmap,
|
||||||
|
),
|
||||||
}
|
}
|
||||||
f.setRoot(root)
|
f.setRoot(root)
|
||||||
f.features = (&fs.Features{
|
f.features = (&fs.Features{
|
||||||
@@ -816,6 +858,11 @@ func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options .
|
|||||||
return fs, fs.Update(ctx, in, src, options...)
|
return fs, fs.Update(ctx, in, src, options...)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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 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 {
|
||||||
container, _ := f.split(dir)
|
container, _ := f.split(dir)
|
||||||
@@ -825,6 +872,10 @@ func (f *Fs) Mkdir(ctx context.Context, dir string) error {
|
|||||||
// makeContainer creates the container if it doesn't exist
|
// makeContainer creates the container if it doesn't exist
|
||||||
func (f *Fs) makeContainer(ctx context.Context, container string) error {
|
func (f *Fs) makeContainer(ctx context.Context, container string) error {
|
||||||
return f.cache.Create(container, func() error {
|
return f.cache.Create(container, func() error {
|
||||||
|
// If this is a SAS URL limited to a container then assume it is already created
|
||||||
|
if f.isLimited {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
// now try to create the container
|
// now try to create the container
|
||||||
return f.pacer.Call(func() (bool, error) {
|
return f.pacer.Call(func() (bool, error) {
|
||||||
_, err := f.cntURL(container).Create(ctx, azblob.Metadata{}, azblob.PublicAccessNone)
|
_, err := f.cntURL(container).Create(ctx, azblob.Metadata{}, azblob.PublicAccessNone)
|
||||||
@@ -916,8 +967,7 @@ func (f *Fs) Hashes() hash.Set {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 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 {
|
||||||
dir := "" // forward compat!
|
|
||||||
container, directory := f.split(dir)
|
container, directory := f.split(dir)
|
||||||
if container == "" || directory != "" {
|
if container == "" || directory != "" {
|
||||||
// Delegate to caller if not root of a container
|
// Delegate to caller if not root of a container
|
||||||
@@ -978,6 +1028,19 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
return f.NewObject(ctx, remote)
|
return f.NewObject(ctx, remote)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (f *Fs) getMemoryPool(size int64) *pool.Pool {
|
||||||
|
if size == int64(f.opt.ChunkSize) {
|
||||||
|
return f.pool
|
||||||
|
}
|
||||||
|
|
||||||
|
return pool.New(
|
||||||
|
time.Duration(f.opt.MemoryPoolFlushTime),
|
||||||
|
int(size),
|
||||||
|
fs.Config.Transfers,
|
||||||
|
f.opt.MemoryPoolUseMmap,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------
|
// ------------------------------------------------------------
|
||||||
|
|
||||||
// Fs returns the parent Fs
|
// Fs returns the parent Fs
|
||||||
@@ -1221,103 +1284,116 @@ type readSeeker struct {
|
|||||||
io.Seeker
|
io.Seeker
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// increment the slice passed in as LSB binary
|
||||||
|
func increment(xs []byte) {
|
||||||
|
for i, digit := range xs {
|
||||||
|
newDigit := digit + 1
|
||||||
|
xs[i] = newDigit
|
||||||
|
if newDigit >= digit {
|
||||||
|
// exit if no carry
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var warnStreamUpload sync.Once
|
||||||
|
|
||||||
// uploadMultipart uploads a file using multipart upload
|
// uploadMultipart uploads a file using multipart upload
|
||||||
//
|
//
|
||||||
// Write a larger blob, using CreateBlockBlob, PutBlock, and PutBlockList.
|
// Write a larger blob, using CreateBlockBlob, PutBlock, and PutBlockList.
|
||||||
func (o *Object) uploadMultipart(in io.Reader, size int64, blob *azblob.BlobURL, httpHeaders *azblob.BlobHTTPHeaders) (err error) {
|
func (o *Object) uploadMultipart(ctx context.Context, in io.Reader, size int64, blob *azblob.BlobURL, httpHeaders *azblob.BlobHTTPHeaders) (err error) {
|
||||||
// Calculate correct chunkSize
|
// Calculate correct chunkSize
|
||||||
chunkSize := int64(o.fs.opt.ChunkSize)
|
chunkSize := int64(o.fs.opt.ChunkSize)
|
||||||
var totalParts int64
|
totalParts := -1
|
||||||
for {
|
|
||||||
// Calculate number of parts
|
// Note that the max size of file is 4.75 TB (100 MB X 50,000
|
||||||
var remainder int64
|
// blocks) and this is bigger than the max uncommitted block
|
||||||
totalParts, remainder = size/chunkSize, size%chunkSize
|
// size (9.52 TB) so we do not need to part commit block lists
|
||||||
if remainder != 0 {
|
// or garbage collect uncommitted blocks.
|
||||||
totalParts++
|
//
|
||||||
|
// See: https://docs.microsoft.com/en-gb/rest/api/storageservices/put-block
|
||||||
|
|
||||||
|
// size can be -1 here meaning we don't know the size of the incoming file. We use ChunkSize
|
||||||
|
// buffers here (default 4MB). With a maximum number of parts (50,000) this will be a file of
|
||||||
|
// 195GB which seems like a not too unreasonable limit.
|
||||||
|
if size == -1 {
|
||||||
|
warnStreamUpload.Do(func() {
|
||||||
|
fs.Logf(o, "Streaming uploads using chunk size %v will have maximum file size of %v",
|
||||||
|
o.fs.opt.ChunkSize, fs.SizeSuffix(chunkSize*maxTotalParts))
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
// Adjust partSize until the number of parts is small enough.
|
||||||
|
if size/chunkSize >= maxTotalParts {
|
||||||
|
// Calculate partition size rounded up to the nearest MB
|
||||||
|
chunkSize = (((size / maxTotalParts) >> 20) + 1) << 20
|
||||||
}
|
}
|
||||||
if totalParts < maxTotalParts {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
// Double chunk size if the number of parts is too big
|
|
||||||
chunkSize *= 2
|
|
||||||
if chunkSize > int64(maxChunkSize) {
|
if chunkSize > int64(maxChunkSize) {
|
||||||
return errors.Errorf("can't upload as it is too big %v - takes more than %d chunks of %v", fs.SizeSuffix(size), totalParts, fs.SizeSuffix(chunkSize/2))
|
return errors.Errorf("can't upload as it is too big %v - takes more than %d chunks of %v", fs.SizeSuffix(size), totalParts, fs.SizeSuffix(chunkSize/2))
|
||||||
}
|
}
|
||||||
|
totalParts = int(size / chunkSize)
|
||||||
|
if size%chunkSize != 0 {
|
||||||
|
totalParts++
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fs.Debugf(o, "Multipart upload session started for %d parts of size %v", totalParts, fs.SizeSuffix(chunkSize))
|
fs.Debugf(o, "Multipart upload session started for %d parts of size %v", totalParts, fs.SizeSuffix(chunkSize))
|
||||||
|
|
||||||
// https://godoc.org/github.com/Azure/azure-storage-blob-go/2017-07-29/azblob#example-BlockBlobURL
|
|
||||||
// Utilities are cloned from above example
|
|
||||||
// These helper functions convert a binary block ID to a base-64 string and vice versa
|
|
||||||
// NOTE: The blockID must be <= 64 bytes and ALL blockIDs for the block must be the same length
|
|
||||||
blockIDBinaryToBase64 := func(blockID []byte) string { return base64.StdEncoding.EncodeToString(blockID) }
|
|
||||||
// These helper functions convert an int block ID to a base-64 string and vice versa
|
|
||||||
blockIDIntToBase64 := func(blockID uint64) string {
|
|
||||||
binaryBlockID := (&[8]byte{})[:] // All block IDs are 8 bytes long
|
|
||||||
binary.LittleEndian.PutUint64(binaryBlockID, blockID)
|
|
||||||
return blockIDBinaryToBase64(binaryBlockID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// block ID variables
|
|
||||||
var (
|
|
||||||
rawID uint64
|
|
||||||
blockID = "" // id in base64 encoded form
|
|
||||||
blocks []string
|
|
||||||
)
|
|
||||||
|
|
||||||
// increment the blockID
|
|
||||||
nextID := func() {
|
|
||||||
rawID++
|
|
||||||
blockID = blockIDIntToBase64(rawID)
|
|
||||||
blocks = append(blocks, blockID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get BlockBlobURL, we will use default pipeline here
|
|
||||||
blockBlobURL := blob.ToBlockBlobURL()
|
|
||||||
ctx := context.Background()
|
|
||||||
ac := azblob.LeaseAccessConditions{} // Use default lease access conditions
|
|
||||||
|
|
||||||
// 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)
|
in, wrap := accounting.UnWrap(in)
|
||||||
|
|
||||||
// Upload the chunks
|
// Upload the chunks
|
||||||
remaining := size
|
var (
|
||||||
position := int64(0)
|
g, gCtx = errgroup.WithContext(ctx)
|
||||||
errs := make(chan error, 1)
|
remaining = size // remaining size in file for logging only, -1 if size < 0
|
||||||
var wg sync.WaitGroup
|
position = int64(0) // position in file
|
||||||
outer:
|
memPool = o.fs.getMemoryPool(chunkSize) // pool to get memory from
|
||||||
for part := 0; part < int(totalParts); part++ {
|
finished = false // set when we have read EOF
|
||||||
// Check any errors
|
blocks []string // list of blocks for finalize
|
||||||
select {
|
blockBlobURL = blob.ToBlockBlobURL() // Get BlockBlobURL, we will use default pipeline here
|
||||||
case err = <-errs:
|
ac = azblob.LeaseAccessConditions{} // Use default lease access conditions
|
||||||
break outer
|
binaryBlockID = make([]byte, 8) // block counter as LSB first 8 bytes
|
||||||
default:
|
)
|
||||||
|
for part := 0; !finished; part++ {
|
||||||
|
// Get a block of memory from the pool and a token which limits concurrency
|
||||||
|
o.fs.uploadToken.Get()
|
||||||
|
buf := memPool.Get()
|
||||||
|
|
||||||
|
free := func() {
|
||||||
|
memPool.Put(buf) // return the buf
|
||||||
|
o.fs.uploadToken.Put() // return the token
|
||||||
}
|
}
|
||||||
|
|
||||||
reqSize := remaining
|
// Fail fast, in case an errgroup managed function returns an error
|
||||||
if reqSize >= chunkSize {
|
// gCtx is cancelled. There is no point in uploading all the other parts.
|
||||||
reqSize = chunkSize
|
if gCtx.Err() != nil {
|
||||||
|
free()
|
||||||
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
// Make a block of memory
|
|
||||||
buf := make([]byte, reqSize)
|
|
||||||
|
|
||||||
// Read the chunk
|
// Read the chunk
|
||||||
_, err = io.ReadFull(in, buf)
|
n, err := readers.ReadFill(in, buf) // this can never return 0, nil
|
||||||
if err != nil {
|
if err == io.EOF {
|
||||||
err = errors.Wrap(err, "multipart upload failed to read source")
|
if n == 0 { // end if no data
|
||||||
break outer
|
free()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
finished = true
|
||||||
|
} else if err != nil {
|
||||||
|
free()
|
||||||
|
return errors.Wrap(err, "multipart upload failed to read source")
|
||||||
}
|
}
|
||||||
|
buf = buf[:n]
|
||||||
|
|
||||||
|
// increment the blockID and save the blocks for finalize
|
||||||
|
increment(binaryBlockID)
|
||||||
|
blockID := base64.StdEncoding.EncodeToString(binaryBlockID)
|
||||||
|
blocks = append(blocks, blockID)
|
||||||
|
|
||||||
// Transfer the chunk
|
// Transfer the chunk
|
||||||
nextID()
|
fs.Debugf(o, "Uploading part %d/%d offset %v/%v part size %v", part+1, totalParts, fs.SizeSuffix(position), fs.SizeSuffix(size), fs.SizeSuffix(chunkSize))
|
||||||
wg.Add(1)
|
g.Go(func() (err error) {
|
||||||
o.fs.uploadToken.Get()
|
defer free()
|
||||||
go func(part int, position int64, blockID string) {
|
|
||||||
defer wg.Done()
|
|
||||||
defer o.fs.uploadToken.Put()
|
|
||||||
fs.Debugf(o, "Uploading part %d/%d offset %v/%v part size %v", part+1, totalParts, fs.SizeSuffix(position), fs.SizeSuffix(size), fs.SizeSuffix(chunkSize))
|
|
||||||
|
|
||||||
// Upload the block, with MD5 for check
|
// Upload the block, with MD5 for check
|
||||||
md5sum := md5.Sum(buf)
|
md5sum := md5.Sum(buf)
|
||||||
@@ -1329,28 +1405,19 @@ outer:
|
|||||||
_, err = blockBlobURL.StageBlock(ctx, blockID, &rs, ac, transactionalMD5)
|
_, err = blockBlobURL.StageBlock(ctx, blockID, &rs, ac, transactionalMD5)
|
||||||
return o.fs.shouldRetry(err)
|
return o.fs.shouldRetry(err)
|
||||||
})
|
})
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
err = errors.Wrap(err, "multipart upload failed to upload part")
|
return errors.Wrap(err, "multipart upload failed to upload part")
|
||||||
select {
|
|
||||||
case errs <- err:
|
|
||||||
default:
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
}(part, position, blockID)
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
// ready for next block
|
// ready for next block
|
||||||
remaining -= chunkSize
|
if size >= 0 {
|
||||||
|
remaining -= chunkSize
|
||||||
|
}
|
||||||
position += chunkSize
|
position += chunkSize
|
||||||
}
|
}
|
||||||
wg.Wait()
|
err = g.Wait()
|
||||||
if err == nil {
|
|
||||||
select {
|
|
||||||
case err = <-errs:
|
|
||||||
default:
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -1387,14 +1454,16 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
httpHeaders.ContentType = fs.MimeType(ctx, o)
|
httpHeaders.ContentType = fs.MimeType(ctx, o)
|
||||||
// Compute the Content-MD5 of the file, for multiparts uploads it
|
// Compute the Content-MD5 of the file, for multiparts uploads it
|
||||||
// will be set in PutBlockList API call using the 'x-ms-blob-content-md5' header
|
// will be set in PutBlockList API call using the 'x-ms-blob-content-md5' header
|
||||||
// Note: If multipart, a MD5 checksum will also be computed for each uploaded block
|
// Note: If multipart, an MD5 checksum will also be computed for each uploaded block
|
||||||
// in order to validate its integrity during transport
|
// in order to validate its integrity during transport
|
||||||
if sourceMD5, _ := src.Hash(ctx, hash.MD5); sourceMD5 != "" {
|
if !o.fs.opt.DisableCheckSum {
|
||||||
sourceMD5bytes, err := hex.DecodeString(sourceMD5)
|
if sourceMD5, _ := src.Hash(ctx, hash.MD5); sourceMD5 != "" {
|
||||||
if err == nil {
|
sourceMD5bytes, err := hex.DecodeString(sourceMD5)
|
||||||
httpHeaders.ContentMD5 = sourceMD5bytes
|
if err == nil {
|
||||||
} else {
|
httpHeaders.ContentMD5 = sourceMD5bytes
|
||||||
fs.Debugf(o, "Failed to decode %q as MD5: %v", sourceMD5, err)
|
} else {
|
||||||
|
fs.Debugf(o, "Failed to decode %q as MD5: %v", sourceMD5, err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1408,7 +1477,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
// is merged the SDK can't upload a single blob of exactly the chunk
|
// is merged the SDK can't upload a single blob of exactly the chunk
|
||||||
// size, so upload with a multpart upload to work around.
|
// size, so upload with a multpart upload to work around.
|
||||||
// See: https://github.com/rclone/rclone/issues/2653
|
// See: https://github.com/rclone/rclone/issues/2653
|
||||||
multipartUpload := size >= int64(o.fs.opt.UploadCutoff)
|
multipartUpload := size < 0 || size >= int64(o.fs.opt.UploadCutoff)
|
||||||
if size == int64(o.fs.opt.ChunkSize) {
|
if size == int64(o.fs.opt.ChunkSize) {
|
||||||
multipartUpload = true
|
multipartUpload = true
|
||||||
fs.Debugf(o, "Setting multipart upload for file of chunk size (%d) to work around SDK bug", size)
|
fs.Debugf(o, "Setting multipart upload for file of chunk size (%d) to work around SDK bug", size)
|
||||||
@@ -1418,7 +1487,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
err = o.fs.pacer.CallNoRetry(func() (bool, error) {
|
err = o.fs.pacer.CallNoRetry(func() (bool, error) {
|
||||||
if multipartUpload {
|
if multipartUpload {
|
||||||
// If a large file upload in chunks
|
// If a large file upload in chunks
|
||||||
err = o.uploadMultipart(in, size, &blob, &httpHeaders)
|
err = o.uploadMultipart(ctx, in, size, &blob, &httpHeaders)
|
||||||
} else {
|
} else {
|
||||||
// Write a small blob in one transaction
|
// Write a small blob in one transaction
|
||||||
blockBlobURL := blob.ToBlockBlobURL()
|
blockBlobURL := blob.ToBlockBlobURL()
|
||||||
@@ -1503,12 +1572,13 @@ func (o *Object) GetTier() string {
|
|||||||
|
|
||||||
// Check the interfaces are satisfied
|
// Check the interfaces are satisfied
|
||||||
var (
|
var (
|
||||||
_ fs.Fs = &Fs{}
|
_ fs.Fs = &Fs{}
|
||||||
_ fs.Copier = &Fs{}
|
_ fs.Copier = &Fs{}
|
||||||
_ fs.Purger = &Fs{}
|
_ fs.PutStreamer = &Fs{}
|
||||||
_ fs.ListRer = &Fs{}
|
_ fs.Purger = &Fs{}
|
||||||
_ fs.Object = &Object{}
|
_ fs.ListRer = &Fs{}
|
||||||
_ fs.MimeTyper = &Object{}
|
_ fs.Object = &Object{}
|
||||||
_ fs.GetTierer = &Object{}
|
_ fs.MimeTyper = &Object{}
|
||||||
_ fs.SetTierer = &Object{}
|
_ fs.GetTierer = &Object{}
|
||||||
|
_ fs.SetTierer = &Object{}
|
||||||
)
|
)
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
// +build !plan9,!solaris
|
// +build !plan9,!solaris,!js,go1.13
|
||||||
|
|
||||||
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,6 +1,6 @@
|
|||||||
// Test AzureBlob filesystem interface
|
// Test AzureBlob filesystem interface
|
||||||
|
|
||||||
// +build !plan9,!solaris
|
// +build !plan9,!solaris,!js,go1.13
|
||||||
|
|
||||||
package azureblob
|
package azureblob
|
||||||
|
|
||||||
|
|||||||
@@ -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.13
|
||||||
|
|
||||||
package azureblob
|
package azureblob
|
||||||
@@ -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.
|
||||||
|
}
|
||||||
+159
-97
@@ -33,6 +33,7 @@ import (
|
|||||||
"github.com/rclone/rclone/lib/bucket"
|
"github.com/rclone/rclone/lib/bucket"
|
||||||
"github.com/rclone/rclone/lib/encoder"
|
"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"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -54,6 +55,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
|
||||||
@@ -113,6 +117,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.
|
||||||
@@ -124,8 +138,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,
|
||||||
}, {
|
}, {
|
||||||
@@ -145,6 +164,18 @@ 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,
|
Name: config.ConfigEncoding,
|
||||||
Help: config.ConfigEncodingHelp,
|
Help: config.ConfigEncodingHelp,
|
||||||
@@ -168,10 +199,13 @@ type Options struct {
|
|||||||
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"`
|
||||||
|
CopyCutoff fs.SizeSuffix `config:"copy_cutoff"`
|
||||||
ChunkSize fs.SizeSuffix `config:"chunk_size"`
|
ChunkSize fs.SizeSuffix `config:"chunk_size"`
|
||||||
DisableCheckSum bool `config:"disable_checksum"`
|
DisableCheckSum bool `config:"disable_checksum"`
|
||||||
DownloadURL string `config:"download_url"`
|
DownloadURL string `config:"download_url"`
|
||||||
DownloadAuthorizationDuration fs.Duration `config:"download_auth_duration"`
|
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"`
|
Enc encoder.MultiEncoder `config:"encoding"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -194,7 +228,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
|
||||||
@@ -330,7 +365,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
|
||||||
}
|
}
|
||||||
@@ -391,6 +425,13 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
_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(pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
|
||||||
|
uploadToken: pacer.NewTokenDispenser(fs.Config.Transfers),
|
||||||
|
pool: pool.New(
|
||||||
|
time.Duration(opt.MemoryPoolFlushTime),
|
||||||
|
int(opt.ChunkSize),
|
||||||
|
fs.Config.Transfers,
|
||||||
|
opt.MemoryPoolUseMmap,
|
||||||
|
),
|
||||||
}
|
}
|
||||||
f.setRoot(root)
|
f.setRoot(root)
|
||||||
f.features = (&fs.Features{
|
f.features = (&fs.Features{
|
||||||
@@ -405,7 +446,6 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
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")
|
||||||
@@ -528,32 +568,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
|
||||||
@@ -668,7 +701,7 @@ 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 {
|
||||||
remote = remote[:len(remote)-1]
|
remote = remote[:len(remote)-1]
|
||||||
}
|
}
|
||||||
@@ -1110,7 +1143,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")
|
||||||
}
|
}
|
||||||
@@ -1185,19 +1219,76 @@ 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 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.
|
// Copy src to this remote using server side copy operations.
|
||||||
@@ -1210,47 +1301,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: f.opt.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.
|
||||||
@@ -1293,7 +1358,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 == "" {
|
||||||
@@ -1370,6 +1435,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 (eg 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
|
||||||
@@ -1385,12 +1465,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)
|
||||||
@@ -1511,28 +1586,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: o.fs.opt.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
|
||||||
@@ -1616,8 +1673,8 @@ 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()
|
||||||
@@ -1648,6 +1705,7 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.Read
|
|||||||
o.sha1 = resp.Header.Get(sha1InfoHeader)
|
o.sha1 = resp.Header.Get(sha1InfoHeader)
|
||||||
fs.Debugf(o, "Reading sha1 from info - %q", o.sha1)
|
fs.Debugf(o, "Reading sha1 from info - %q", o.sha1)
|
||||||
}
|
}
|
||||||
|
o.sha1 = cleanSHA1(o.sha1)
|
||||||
}
|
}
|
||||||
// Don't check length or hash on partial content
|
// Don't check length or hash on partial content
|
||||||
if resp.StatusCode == http.StatusPartialContent {
|
if resp.StatusCode == http.StatusPartialContent {
|
||||||
@@ -1707,7 +1765,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)
|
||||||
@@ -1717,22 +1776,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
|
||||||
}
|
}
|
||||||
@@ -1816,6 +1877,7 @@ 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(o.fs.opt.Enc.FromStandardPath(bucketPath)),
|
"X-Bz-File-Name": urlEncode(o.fs.opt.Enc.FromStandardPath(bucketPath)),
|
||||||
|
|||||||
+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: f.opt.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"`
|
||||||
|
}
|
||||||
+182
-118
@@ -26,6 +26,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/rclone/rclone/lib/encoder"
|
"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"
|
||||||
@@ -53,8 +54,7 @@ const (
|
|||||||
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
|
||||||
@@ -87,43 +87,33 @@ func init() {
|
|||||||
Config: func(name string, m configmap.Mapper) {
|
Config: func(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(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("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",
|
||||||
@@ -159,10 +149,31 @@ func init() {
|
|||||||
encoder.EncodeBackSlash |
|
encoder.EncodeBackSlash |
|
||||||
encoder.EncodeRightSpace |
|
encoder.EncodeRightSpace |
|
||||||
encoder.EncodeInvalidUtf8),
|
encoder.EncodeInvalidUtf8),
|
||||||
}},
|
}}...),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func refreshJWTToken(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(fs.Config)
|
||||||
|
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 {
|
||||||
@@ -185,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,
|
||||||
@@ -236,6 +246,8 @@ 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"`
|
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
|
||||||
@@ -287,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
|
||||||
@@ -318,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
|
||||||
@@ -374,16 +386,22 @@ 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(fs.Config)
|
||||||
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(name, m, oauthConfig)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "failed to configure Box")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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(pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
|
||||||
uploadToken: pacer.NewTokenDispenser(fs.Config.Transfers),
|
uploadToken: pacer.NewTokenDispenser(fs.Config.Transfers),
|
||||||
}
|
}
|
||||||
@@ -393,13 +411,34 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
}).Fill(f)
|
}).Fill(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(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
|
||||||
@@ -592,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
|
||||||
@@ -636,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
|
||||||
}
|
}
|
||||||
@@ -692,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
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -723,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
|
||||||
@@ -831,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
|
||||||
@@ -860,6 +885,30 @@ func (f *Fs) move(ctx context.Context, endpoint, id, leaf, directoryID string) (
|
|||||||
return info, nil
|
return info, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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.
|
// 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
|
||||||
@@ -909,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
|
||||||
}
|
}
|
||||||
@@ -975,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 {
|
||||||
@@ -1014,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 permenently 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() {
|
||||||
@@ -1167,7 +1226,7 @@ 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: o.fs.opt.Enc.FromStandardName(leaf),
|
Name: o.fs.opt.Enc.FromStandardName(leaf),
|
||||||
ContentModifiedAt: api.Time(modTime),
|
ContentModifiedAt: api.Time(modTime),
|
||||||
@@ -1186,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 != "" {
|
||||||
@@ -1212,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
|
||||||
}
|
}
|
||||||
@@ -1250,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)
|
||||||
)
|
)
|
||||||
+11
-11
@@ -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"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -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
+60
-20
@@ -1,4 +1,4 @@
|
|||||||
// +build !plan9
|
// +build !plan9,!js
|
||||||
|
|
||||||
package cache
|
package cache
|
||||||
|
|
||||||
@@ -65,6 +65,7 @@ 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, eg \"myremote:path/to/dir\",\n\"myremote:bucket\" or maybe \"myremote:\" (not recommended).",
|
||||||
@@ -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",
|
||||||
@@ -338,7 +339,7 @@ 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(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)
|
||||||
@@ -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(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{}
|
||||||
@@ -519,9 +516,6 @@ func NewFs(name, rootPath string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
// 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
|
||||||
}
|
}
|
||||||
@@ -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 {
|
||||||
@@ -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,31 @@ func (f *Fs) Disconnect(ctx context.Context) error {
|
|||||||
return do(ctx)
|
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 +1937,6 @@ 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)
|
||||||
)
|
)
|
||||||
Vendored
+58
-326
@@ -1,4 +1,4 @@
|
|||||||
// +build !plan9
|
// +build !plan9,!js
|
||||||
// +build !race
|
// +build !race
|
||||||
|
|
||||||
package cache_test
|
package cache_test
|
||||||
@@ -16,7 +16,6 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"runtime"
|
|
||||||
"runtime/debug"
|
"runtime/debug"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -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 == "" {
|
||||||
@@ -1055,14 +927,6 @@ func (r *run) newCacheFs(t *testing.T, remote, id string, needRemote, purge bool
|
|||||||
|
|
||||||
fs.Config.LowLevelRetries = 1
|
fs.Config.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()
|
||||||
@@ -1082,33 +946,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)
|
||||||
|
|
||||||
@@ -1148,37 +1000,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 {
|
||||||
@@ -1195,10 +1021,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
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1206,26 +1028,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
|
||||||
@@ -1235,30 +1047,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)
|
||||||
}
|
}
|
||||||
@@ -1281,28 +1075,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
|
||||||
@@ -1311,18 +1096,10 @@ 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
|
||||||
}
|
}
|
||||||
@@ -1351,13 +1128,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
|
||||||
@@ -1373,13 +1144,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
|
||||||
@@ -1399,13 +1164,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
|
||||||
@@ -1425,13 +1184,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
|
||||||
@@ -1442,13 +1194,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
|
||||||
@@ -1459,28 +1204,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
|
||||||
}
|
}
|
||||||
|
|||||||
-21
@@ -1,21 +0,0 @@
|
|||||||
// +build !linux !go1.13
|
|
||||||
// +build !darwin !go1.13
|
|
||||||
// +build !freebsd !go1.13
|
|
||||||
// +build !windows
|
|
||||||
// +build !race
|
|
||||||
|
|
||||||
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")
|
|
||||||
}
|
|
||||||
-79
@@ -1,79 +0,0 @@
|
|||||||
// +build linux,go1.13 darwin,go1.13 freebsd,go1.13
|
|
||||||
// +build !race
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
-125
@@ -1,125 +0,0 @@
|
|||||||
// +build windows
|
|
||||||
// +build !race
|
|
||||||
|
|
||||||
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
+2
-2
@@ -1,6 +1,6 @@
|
|||||||
// Test Cache filesystem interface
|
// Test Cache filesystem interface
|
||||||
|
|
||||||
// +build !plan9
|
// +build !plan9,!js
|
||||||
// +build !race
|
// +build !race
|
||||||
|
|
||||||
package cache_test
|
package cache_test
|
||||||
@@ -18,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
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
// +build !plan9
|
// +build !plan9,!js
|
||||||
// +build !race
|
// +build !race
|
||||||
|
|
||||||
package cache_test
|
package cache_test
|
||||||
|
|||||||
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
+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
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
// +build !plan9
|
// +build !plan9,!js
|
||||||
|
|
||||||
package cache
|
package cache
|
||||||
|
|
||||||
|
|||||||
Vendored
+2
-24
@@ -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
|
||||||
@@ -980,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 {
|
||||||
@@ -1036,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
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -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"
|
||||||
@@ -238,15 +239,18 @@ 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(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")
|
||||||
@@ -258,6 +262,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 +276,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(baseName + firstChunkPath)
|
||||||
if testErr == fs.ErrorIsFile {
|
if testErr == fs.ErrorIsFile {
|
||||||
err = testErr
|
err = testErr
|
||||||
}
|
}
|
||||||
@@ -1333,7 +1338,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 +1349,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)
|
||||||
|
|||||||
+39
-56
@@ -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,
|
||||||
@@ -172,7 +149,7 @@ func newCipher(mode NameEncryptionMode, password, salt string, dirNameEncrypt bo
|
|||||||
//
|
//
|
||||||
// Note that empty passsword makes all 0x00 keys which is used in the
|
// Note that empty passsword 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,
|
||||||
@@ -683,13 +661,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 +682,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 +693,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 +721,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
|
||||||
@@ -1012,7 +996,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 +1009,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 +1018,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 +1028,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 +1047,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)
|
||||||
|
|||||||
+161
-52
@@ -12,6 +12,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/config/obscure"
|
"github.com/rclone/rclone/fs/config/obscure"
|
||||||
@@ -26,6 +27,7 @@ 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, eg \"myremote:path/to/dir\",\n\"myremote:bucket\" or maybe \"myremote:\" (not recommended).",
|
||||||
@@ -71,6 +73,20 @@ NB If filename_encryption is "off" then this option will do nothing.`,
|
|||||||
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 (eg 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.
|
||||||
@@ -90,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
|
||||||
@@ -117,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)
|
||||||
@@ -143,24 +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)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.Wrapf(err, "failed to parse remote %q to wrap", remote)
|
|
||||||
}
|
|
||||||
// Make sure to remove trailing . reffering to the current dir
|
// Make sure to remove trailing . reffering to the current dir
|
||||||
if path.Base(rpath) == "." {
|
if path.Base(rpath) == "." {
|
||||||
rpath = strings.TrimSuffix(rpath, ".")
|
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(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(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(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,
|
||||||
@@ -169,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{
|
||||||
@@ -180,6 +198,7 @@ func NewFs(name, rpath string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
CanHaveEmptyDirectories: true,
|
CanHaveEmptyDirectories: true,
|
||||||
SetTier: true,
|
SetTier: true,
|
||||||
GetTier: true,
|
GetTier: true,
|
||||||
|
ServerSideAcrossConfigs: opt.ServerSideAcrossConfigs,
|
||||||
}).Fill(f).Mask(wrappedFs).WrapsFs(f, wrappedFs)
|
}).Fill(f).Mask(wrappedFs).WrapsFs(f, wrappedFs)
|
||||||
|
|
||||||
return f, err
|
return f, err
|
||||||
@@ -192,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"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -203,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)
|
||||||
@@ -240,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)
|
||||||
@@ -327,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
|
||||||
}
|
}
|
||||||
@@ -351,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
|
||||||
}
|
}
|
||||||
@@ -410,18 +430,18 @@ 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.
|
||||||
@@ -504,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
|
||||||
}
|
}
|
||||||
@@ -561,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
|
||||||
//
|
//
|
||||||
@@ -572,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")
|
||||||
@@ -597,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
|
||||||
@@ -647,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")
|
||||||
@@ -655,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
|
||||||
@@ -692,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
|
||||||
@@ -833,13 +922,15 @@ func (f *Fs) Disconnect(ctx context.Context) error {
|
|||||||
// 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,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -865,6 +956,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
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -903,6 +1011,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)
|
||||||
|
|||||||
@@ -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()
|
||||||
|
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 encryptor
|
||||||
|
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
+931
-331
File diff suppressed because it is too large.
Load diff
@@ -10,12 +10,16 @@ import (
|
|||||||
"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"
|
||||||
@@ -268,6 +272,142 @@ func (f *Fs) InternalTestDocumentLink(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestIntegration/FsMkdir/FsPutFiles/Internal/Shortcuts
|
||||||
|
func (f *Fs) InternalTestShortcuts(t *testing.T) {
|
||||||
|
const (
|
||||||
|
// from fstest/fstests/fstests.go
|
||||||
|
existingDir = "hello? sausage"
|
||||||
|
existingFile = `hello? sausage/êé/Hello, 世界/ " ' @ < > & ? + ≠/z.txt`
|
||||||
|
existingSubDir = "êé"
|
||||||
|
)
|
||||||
|
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"))
|
||||||
|
}
|
||||||
|
|
||||||
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 +422,8 @@ func (f *Fs) InternalTest(t *testing.T) {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
t.Run("Shortcuts", f.InternalTestShortcuts)
|
||||||
|
t.Run("UnTrash", f.InternalTestUnTrash)
|
||||||
}
|
}
|
||||||
|
|
||||||
var _ fstests.InternalTester = (*Fs)(nil)
|
var _ fstests.InternalTester = (*Fs)(nil)
|
||||||
Regular → Executable
+313
-65
@@ -22,6 +22,7 @@ of path_display and all will be well.
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
@@ -29,9 +30,11 @@ import (
|
|||||||
"path"
|
"path"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox"
|
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox"
|
||||||
|
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/async"
|
||||||
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/auth"
|
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/auth"
|
||||||
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/common"
|
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/common"
|
||||||
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/files"
|
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/files"
|
||||||
@@ -47,6 +50,7 @@ import (
|
|||||||
"github.com/rclone/rclone/fs/config/obscure"
|
"github.com/rclone/rclone/fs/config/obscure"
|
||||||
"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/atexit"
|
||||||
"github.com/rclone/rclone/lib/encoder"
|
"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"
|
||||||
@@ -61,6 +65,7 @@ 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
|
||||||
|
maxBatchSize = 1000
|
||||||
// Upload chunk size - setting too small makes uploads slow.
|
// Upload chunk size - setting too small makes uploads slow.
|
||||||
// Chunks are buffered into memory for retries.
|
// Chunks are buffered into memory for retries.
|
||||||
//
|
//
|
||||||
@@ -117,18 +122,15 @@ func init() {
|
|||||||
Description: "Dropbox",
|
Description: "Dropbox",
|
||||||
NewFs: NewFs,
|
NewFs: NewFs,
|
||||||
Config: func(name string, m configmap.Mapper) {
|
Config: func(name string, m configmap.Mapper) {
|
||||||
err := oauthutil.ConfigNoOffline("dropbox", name, m, dropboxConfig)
|
opt := oauthutil.Options{
|
||||||
|
NoOffline: true,
|
||||||
|
}
|
||||||
|
err := oauthutil.Config("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).
|
||||||
|
|
||||||
@@ -145,6 +147,23 @@ 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: "batch",
|
||||||
|
Help: `Enable batching of files if non-zero.
|
||||||
|
|
||||||
|
This sets the batch size of files to upload. It has to be less than 1000. A
|
||||||
|
sensible setting is probably 1000 if you are using this feature.
|
||||||
|
|
||||||
|
Rclone will close any outstanding batches when it exits.
|
||||||
|
|
||||||
|
Setting this is a great idea if you are uploading lots of small files as it will
|
||||||
|
make them a lot quicker. You can use --transfers 32 to maximise throughput.
|
||||||
|
|
||||||
|
It has the downside that rclone can't check the hash of the file after upload,
|
||||||
|
so using "rclone check" after the transfer completes is recommended.
|
||||||
|
`,
|
||||||
|
Default: 0,
|
||||||
|
Advanced: true,
|
||||||
}, {
|
}, {
|
||||||
Name: config.ConfigEncoding,
|
Name: config.ConfigEncoding,
|
||||||
Help: config.ConfigEncodingHelp,
|
Help: config.ConfigEncodingHelp,
|
||||||
@@ -158,7 +177,7 @@ memory. It can be set smaller if you are tight on memory.`, maxChunkSize),
|
|||||||
encoder.EncodeDel |
|
encoder.EncodeDel |
|
||||||
encoder.EncodeRightSpace |
|
encoder.EncodeRightSpace |
|
||||||
encoder.EncodeInvalidUtf8),
|
encoder.EncodeInvalidUtf8),
|
||||||
}},
|
}}...),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -166,6 +185,7 @@ memory. It can be set smaller if you are tight on memory.`, maxChunkSize),
|
|||||||
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"`
|
||||||
|
Batch int `config:"batch"`
|
||||||
Enc encoder.MultiEncoder `config:"encoding"`
|
Enc encoder.MultiEncoder `config:"encoding"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -183,6 +203,7 @@ type Fs struct {
|
|||||||
slashRootSlash string // root with "/" prefix and postfix, lowercase
|
slashRootSlash string // root with "/" prefix and postfix, lowercase
|
||||||
pacer *fs.Pacer // To pace the API calls
|
pacer *fs.Pacer // To pace the API calls
|
||||||
ns string // The namespace we are using or "" for none
|
ns string // The namespace we are using or "" for none
|
||||||
|
batcher *batcher // batch builder
|
||||||
}
|
}
|
||||||
|
|
||||||
// Object describes a dropbox object
|
// Object describes a dropbox object
|
||||||
@@ -198,6 +219,165 @@ type Object struct {
|
|||||||
|
|
||||||
// ------------------------------------------------------------
|
// ------------------------------------------------------------
|
||||||
|
|
||||||
|
// batcher holds info about the current items waiting for upload
|
||||||
|
type batcher struct {
|
||||||
|
f *Fs // Fs this batch is part of
|
||||||
|
mu sync.Mutex // lock for vars below
|
||||||
|
commitMu sync.Mutex // lock for waiting for batch
|
||||||
|
maxBatch int // maximum size for batch
|
||||||
|
active int // number of batches being sent
|
||||||
|
items []*files.UploadSessionFinishArg // current uncommitted files
|
||||||
|
atexit atexit.FnHandle // atexit handle
|
||||||
|
}
|
||||||
|
|
||||||
|
// newBatcher creates a new batcher structure
|
||||||
|
func newBatcher(f *Fs, maxBatch int) *batcher {
|
||||||
|
return &batcher{
|
||||||
|
f: f,
|
||||||
|
maxBatch: maxBatch,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start starts adding an item to a batch returning true if it was
|
||||||
|
// successfully started
|
||||||
|
//
|
||||||
|
// This should be paired with End
|
||||||
|
func (b *batcher) Start() bool {
|
||||||
|
if b.maxBatch <= 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
b.mu.Lock()
|
||||||
|
defer b.mu.Unlock()
|
||||||
|
b.active++
|
||||||
|
// FIXME set a timer or something
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// End ends adding an item
|
||||||
|
func (b *batcher) End(started bool) error {
|
||||||
|
if !started {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
b.mu.Lock()
|
||||||
|
defer b.mu.Unlock()
|
||||||
|
b.active--
|
||||||
|
if len(b.items) < b.maxBatch {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return b._commit(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Waits for the batch to complete - call with batchMu held
|
||||||
|
func (b *batcher) _waitForBatchResult(res *files.UploadSessionFinishBatchLaunch) (batchResult *files.UploadSessionFinishBatchResult, err error) {
|
||||||
|
if res.AsyncJobId == "" {
|
||||||
|
return res.Complete, nil
|
||||||
|
}
|
||||||
|
var batchStatus *files.UploadSessionFinishBatchJobStatus
|
||||||
|
sleepTime := time.Second
|
||||||
|
const maxTries = 120
|
||||||
|
for try := 1; try <= maxTries; try++ {
|
||||||
|
err = b.f.pacer.Call(func() (bool, error) {
|
||||||
|
batchStatus, err = b.f.srv.UploadSessionFinishBatchCheck(&async.PollArg{
|
||||||
|
AsyncJobId: res.AsyncJobId,
|
||||||
|
})
|
||||||
|
return shouldRetry(err)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
fs.Errorf(b.f, "failed to wait for batch: %v", err)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if batchStatus.Tag == "complete" {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
fs.Debugf(b.f, "sleeping for %v to wait for batch to complete, try %d/%d", sleepTime, try, maxTries)
|
||||||
|
time.Sleep(sleepTime)
|
||||||
|
}
|
||||||
|
return batchStatus.Complete, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// commit a batch - call with batchMu held
|
||||||
|
//
|
||||||
|
// if finalizing is true then it doesn't unregister Finalize as this
|
||||||
|
// causes a deadlock during finalization.
|
||||||
|
func (b *batcher) _commit(finalizing bool) (err error) {
|
||||||
|
b.commitMu.Lock()
|
||||||
|
batch := "batch"
|
||||||
|
if finalizing {
|
||||||
|
batch = "last batch"
|
||||||
|
}
|
||||||
|
fs.Debugf(b.f, "comitting %s length %d", batch, len(b.items))
|
||||||
|
var arg = &files.UploadSessionFinishBatchArg{
|
||||||
|
Entries: b.items,
|
||||||
|
}
|
||||||
|
var res *files.UploadSessionFinishBatchLaunch
|
||||||
|
err = b.f.pacer.Call(func() (bool, error) {
|
||||||
|
res, err = b.f.srv.UploadSessionFinishBatch(arg)
|
||||||
|
// 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
|
||||||
|
return err != nil, err
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
b.commitMu.Unlock()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clear batch
|
||||||
|
b.items = nil
|
||||||
|
|
||||||
|
// If finalizing, don't unregister or get result
|
||||||
|
if finalizing {
|
||||||
|
b.commitMu.Unlock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unregister the atexit since queue is empty
|
||||||
|
atexit.Unregister(b.atexit)
|
||||||
|
b.atexit = nil
|
||||||
|
|
||||||
|
// Wait for the batch to finish before we proceed in the background
|
||||||
|
go func() {
|
||||||
|
defer b.commitMu.Unlock()
|
||||||
|
_, err = b._waitForBatchResult(res)
|
||||||
|
if err != nil {
|
||||||
|
fs.Errorf(b.f, "Error waiting for batch to finish: %v", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add adds a finished item to the batch
|
||||||
|
func (b *batcher) Add(commitInfo *files.UploadSessionFinishArg) {
|
||||||
|
fs.Debugf(b.f, "adding %q to batch", commitInfo.Commit.Path)
|
||||||
|
b.mu.Lock()
|
||||||
|
defer b.mu.Unlock()
|
||||||
|
b.items = append(b.items, commitInfo)
|
||||||
|
if b.atexit == nil {
|
||||||
|
b.atexit = atexit.Register(b.Finalize)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Finalize finishes any pending batches
|
||||||
|
func (b *batcher) Finalize() {
|
||||||
|
b.mu.Lock()
|
||||||
|
defer b.mu.Unlock()
|
||||||
|
if len(b.items) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
err := b._commit(true)
|
||||||
|
if err != nil {
|
||||||
|
fs.Errorf(b.f, "Failed to finalize last batch: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------
|
||||||
|
|
||||||
// Name of the remote (as passed into NewFs)
|
// Name of the remote (as passed into NewFs)
|
||||||
func (f *Fs) Name() string {
|
func (f *Fs) Name() string {
|
||||||
return f.name
|
return f.name
|
||||||
@@ -225,11 +405,15 @@ 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 Insufficient Space
|
||||||
|
if strings.Contains(baseErrString, "insufficient_space") {
|
||||||
|
return false, fserrors.FatalError(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 {
|
||||||
fs.Debugf(baseErrString, "Too many requests or write operations. Trying again in %d seconds.", e.RateLimitError.RetryAfter)
|
fs.Logf(baseErrString, "Too many requests or write operations. Trying again in %d seconds.", e.RateLimitError.RetryAfter)
|
||||||
err = pacer.RetryAfterError(err, time.Duration(e.RateLimitError.RetryAfter)*time.Second)
|
err = pacer.RetryAfterError(err, time.Duration(e.RateLimitError.RetryAfter)*time.Second)
|
||||||
}
|
}
|
||||||
return true, err
|
return true, err
|
||||||
@@ -272,6 +456,9 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "dropbox: chunk size")
|
return nil, errors.Wrap(err, "dropbox: chunk size")
|
||||||
}
|
}
|
||||||
|
if opt.Batch > maxBatchSize || opt.Batch < 0 {
|
||||||
|
return nil, errors.Errorf("dropbox: batch must be < %d and >= 0 - it is currently %d", maxBatchSize, opt.Batch)
|
||||||
|
}
|
||||||
|
|
||||||
// Convert the old token if it exists. The old token was just
|
// Convert the old token if it exists. The old token was just
|
||||||
// just a string, the new one is a JSON blob
|
// just a string, the new one is a JSON blob
|
||||||
@@ -296,6 +483,7 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
opt: *opt,
|
opt: *opt,
|
||||||
pacer: fs.NewPacer(pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
|
pacer: fs.NewPacer(pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
|
||||||
}
|
}
|
||||||
|
f.batcher = newBatcher(f, f.opt.Batch)
|
||||||
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
|
||||||
Client: oAuthClient, // maybe???
|
Client: oAuthClient, // maybe???
|
||||||
@@ -604,10 +792,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
|
||||||
@@ -615,31 +802,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 = f.opt.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
|
||||||
@@ -650,6 +839,13 @@ 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 {
|
||||||
|
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
|
||||||
@@ -712,15 +908,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) (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: f.opt.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.
|
||||||
@@ -775,11 +964,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 := f.opt.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) {
|
||||||
@@ -1036,6 +1231,13 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.Read
|
|||||||
// unknown (i.e. -1) or smaller than uploadChunkSize, the method incurs an
|
// unknown (i.e. -1) or smaller than uploadChunkSize, the method incurs an
|
||||||
// avoidable request to the Dropbox API that does not carry payload.
|
// avoidable request to the Dropbox API that does not carry payload.
|
||||||
func (o *Object) uploadChunked(in0 io.Reader, commitInfo *files.CommitInfo, size int64) (entry *files.FileMetadata, err error) {
|
func (o *Object) uploadChunked(in0 io.Reader, commitInfo *files.CommitInfo, size int64) (entry *files.FileMetadata, err error) {
|
||||||
|
batching := o.fs.batcher.Start()
|
||||||
|
defer func() {
|
||||||
|
batchErr := o.fs.batcher.End(batching)
|
||||||
|
if err != nil {
|
||||||
|
err = batchErr
|
||||||
|
}
|
||||||
|
}()
|
||||||
chunkSize := int64(o.fs.opt.ChunkSize)
|
chunkSize := int64(o.fs.opt.ChunkSize)
|
||||||
chunks := 0
|
chunks := 0
|
||||||
if size != -1 {
|
if size != -1 {
|
||||||
@@ -1049,11 +1251,15 @@ func (o *Object) uploadChunked(in0 io.Reader, commitInfo *files.CommitInfo, size
|
|||||||
fs.Debugf(o, "Streaming chunk %d/%d", cur, cur)
|
fs.Debugf(o, "Streaming chunk %d/%d", cur, cur)
|
||||||
} else if chunks == 0 {
|
} else if chunks == 0 {
|
||||||
fs.Debugf(o, "Streaming chunk %d/unknown", cur)
|
fs.Debugf(o, "Streaming chunk %d/unknown", cur)
|
||||||
} else {
|
} else if chunks != 1 {
|
||||||
fs.Debugf(o, "Uploading chunk %d/%d", cur, chunks)
|
fs.Debugf(o, "Uploading chunk %d/%d", cur, chunks)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
appendArg := files.UploadSessionAppendArg{
|
||||||
|
Close: chunks == 1,
|
||||||
|
}
|
||||||
|
|
||||||
// write the first chunk
|
// write the first chunk
|
||||||
fmtChunk(1, false)
|
fmtChunk(1, false)
|
||||||
var res *files.UploadSessionStartResult
|
var res *files.UploadSessionStartResult
|
||||||
@@ -1063,7 +1269,10 @@ func (o *Object) uploadChunked(in0 io.Reader, commitInfo *files.CommitInfo, size
|
|||||||
if _, err = chunk.Seek(0, io.SeekStart); err != nil {
|
if _, err = chunk.Seek(0, io.SeekStart); err != nil {
|
||||||
return false, nil
|
return false, nil
|
||||||
}
|
}
|
||||||
res, err = o.fs.srv.UploadSessionStart(&files.UploadSessionStartArg{}, chunk)
|
arg := files.UploadSessionStartArg{
|
||||||
|
Close: appendArg.Close,
|
||||||
|
}
|
||||||
|
res, err = o.fs.srv.UploadSessionStart(&arg, chunk)
|
||||||
return shouldRetry(err)
|
return shouldRetry(err)
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -1074,22 +1283,34 @@ func (o *Object) uploadChunked(in0 io.Reader, commitInfo *files.CommitInfo, size
|
|||||||
SessionId: res.SessionId,
|
SessionId: res.SessionId,
|
||||||
Offset: 0,
|
Offset: 0,
|
||||||
}
|
}
|
||||||
appendArg := files.UploadSessionAppendArg{
|
appendArg.Cursor = &cursor
|
||||||
Cursor: &cursor,
|
|
||||||
Close: false,
|
|
||||||
}
|
|
||||||
|
|
||||||
// write more whole chunks (if any)
|
// write more whole chunks (if any, and if !batching), if
|
||||||
|
// batching write the last chunk also.
|
||||||
currentChunk := 2
|
currentChunk := 2
|
||||||
for {
|
for {
|
||||||
if chunks > 0 && currentChunk >= chunks {
|
if chunks > 0 {
|
||||||
// if the size is known, only upload full chunks. Remaining bytes are uploaded with
|
// Size known
|
||||||
// the UploadSessionFinish request.
|
if currentChunk == chunks {
|
||||||
break
|
// Last chunk
|
||||||
} else if chunks == 0 && in.BytesRead()-cursor.Offset < uint64(chunkSize) {
|
if !batching {
|
||||||
// if the size is unknown, upload as long as we can read full chunks from the reader.
|
// if the size is known, only upload full chunks. Remaining bytes are uploaded with
|
||||||
// The UploadSessionFinish request will not contain any payload.
|
// the UploadSessionFinish request.
|
||||||
break
|
break
|
||||||
|
}
|
||||||
|
appendArg.Close = true
|
||||||
|
} else if currentChunk > chunks {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Size unknown
|
||||||
|
lastReadWasShort := in.BytesRead()-cursor.Offset < uint64(chunkSize)
|
||||||
|
if lastReadWasShort {
|
||||||
|
// if the size is unknown, upload as long as we can read full chunks from the reader.
|
||||||
|
// The UploadSessionFinish request will not contain any payload.
|
||||||
|
// This is also what we want if batching
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
cursor.Offset = in.BytesRead()
|
cursor.Offset = in.BytesRead()
|
||||||
fmtChunk(currentChunk, false)
|
fmtChunk(currentChunk, false)
|
||||||
@@ -1115,6 +1336,26 @@ func (o *Object) uploadChunked(in0 io.Reader, commitInfo *files.CommitInfo, size
|
|||||||
Cursor: &cursor,
|
Cursor: &cursor,
|
||||||
Commit: commitInfo,
|
Commit: commitInfo,
|
||||||
}
|
}
|
||||||
|
// If we are batching then we should have written all the data now
|
||||||
|
// store the commit info now for a batch commit
|
||||||
|
if batching {
|
||||||
|
// If we haven't closed the session then we need to
|
||||||
|
if !appendArg.Close {
|
||||||
|
fs.Debugf(o, "Closing session")
|
||||||
|
var empty bytes.Buffer
|
||||||
|
err = o.fs.pacer.Call(func() (bool, error) {
|
||||||
|
err = o.fs.srv.UploadSessionAppendV2(&appendArg, &empty)
|
||||||
|
// after the first chunk is uploaded, we retry everything
|
||||||
|
return err != nil, err
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
o.fs.batcher.Add(args)
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
fmtChunk(currentChunk, true)
|
fmtChunk(currentChunk, true)
|
||||||
chunk = readers.NewRepeatableReaderBuffer(in, buf)
|
chunk = readers.NewRepeatableReaderBuffer(in, buf)
|
||||||
err = o.fs.pacer.Call(func() (bool, error) {
|
err = o.fs.pacer.Call(func() (bool, error) {
|
||||||
@@ -1157,7 +1398,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
size := src.Size()
|
size := src.Size()
|
||||||
var err error
|
var err error
|
||||||
var entry *files.FileMetadata
|
var entry *files.FileMetadata
|
||||||
if size > int64(o.fs.opt.ChunkSize) || size == -1 {
|
if size > int64(o.fs.opt.ChunkSize) || size == -1 || o.fs.opt.Batch > 0 {
|
||||||
entry, err = o.uploadChunked(in, commitInfo, size)
|
entry, err = o.uploadChunked(in, commitInfo, size)
|
||||||
} else {
|
} else {
|
||||||
err = o.fs.pacer.CallNoRetry(func() (bool, error) {
|
err = o.fs.pacer.CallNoRetry(func() (bool, error) {
|
||||||
@@ -1168,6 +1409,13 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.Wrap(err, "upload failed")
|
return errors.Wrap(err, "upload failed")
|
||||||
}
|
}
|
||||||
|
// If we haven't received data back from batch upload then fake it
|
||||||
|
if entry == nil {
|
||||||
|
o.bytes = size
|
||||||
|
o.modTime = commitInfo.ClientModified
|
||||||
|
o.hash = "" // we don't have this
|
||||||
|
return nil
|
||||||
|
}
|
||||||
return o.setMetadataFromEntry(entry)
|
return o.setMetadataFromEntry(entry)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+18
-6
@@ -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
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -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
|
||||||
@@ -320,7 +331,7 @@ 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 = f.opt.Enc.FromStandardName(fileName)
|
fileName = f.opt.Enc.FromStandardName(fileName)
|
||||||
@@ -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{
|
||||||
|
|||||||
+12
-22
@@ -23,11 +23,12 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
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
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
@@ -185,7 +186,7 @@ func NewFs(name string, root string, config configmap.Mapper) (fs.Fs, error) {
|
|||||||
name: name,
|
name: name,
|
||||||
root: root,
|
root: root,
|
||||||
opt: *opt,
|
opt: *opt,
|
||||||
pacer: fs.NewPacer(pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
|
pacer: fs.NewPacer(pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant), pacer.AttackConstant(attackConstant))),
|
||||||
baseClient: &http.Client{},
|
baseClient: &http.Client{},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -263,7 +264,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
|
||||||
@@ -297,7 +298,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).
|
||||||
//
|
//
|
||||||
@@ -333,12 +334,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
|
||||||
}
|
}
|
||||||
@@ -388,13 +389,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
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -402,11 +397,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
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|||||||
+70
-5
@@ -8,6 +8,8 @@ import (
|
|||||||
"net/textproto"
|
"net/textproto"
|
||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -50,8 +52,19 @@ func init() {
|
|||||||
IsPassword: true,
|
IsPassword: true,
|
||||||
Required: true,
|
Required: true,
|
||||||
}, {
|
}, {
|
||||||
Name: "tls",
|
Name: "tls",
|
||||||
Help: "Use FTP over TLS (Implicit)",
|
Help: `Use FTPS over TLS (Implicit)
|
||||||
|
When using implicit FTP over TLS the client will connect using TLS
|
||||||
|
right from the start, which in turn breaks the compatibility with
|
||||||
|
non-TLS-aware servers. This is usually served over port 990 rather
|
||||||
|
than port 21. Cannot be used in combination with explicit FTP.`,
|
||||||
|
Default: false,
|
||||||
|
}, {
|
||||||
|
Name: "explicit_tls",
|
||||||
|
Help: `Use FTP over TLS (Explicit)
|
||||||
|
When using explicit FTP over TLS the client explicitly request
|
||||||
|
security from the server in order to upgrade a plain text connection
|
||||||
|
to an encrypted one. Cannot be used in combination with implicit FTP.`,
|
||||||
Default: false,
|
Default: false,
|
||||||
}, {
|
}, {
|
||||||
Name: "concurrency",
|
Name: "concurrency",
|
||||||
@@ -72,7 +85,7 @@ func init() {
|
|||||||
Name: config.ConfigEncoding,
|
Name: config.ConfigEncoding,
|
||||||
Help: config.ConfigEncodingHelp,
|
Help: config.ConfigEncodingHelp,
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
// The FTP protocal can't handle trailing spaces (for instance
|
// The FTP protocol can't handle trailing spaces (for instance
|
||||||
// pureftpd turns them into _)
|
// pureftpd turns them into _)
|
||||||
//
|
//
|
||||||
// proftpd can't handle '*' in file names
|
// proftpd can't handle '*' in file names
|
||||||
@@ -90,6 +103,7 @@ type Options struct {
|
|||||||
Pass string `config:"pass"`
|
Pass string `config:"pass"`
|
||||||
Port string `config:"port"`
|
Port string `config:"port"`
|
||||||
TLS bool `config:"tls"`
|
TLS bool `config:"tls"`
|
||||||
|
ExplicitTLS bool `config:"explicit_tls"`
|
||||||
Concurrency int `config:"concurrency"`
|
Concurrency int `config:"concurrency"`
|
||||||
SkipVerifyTLSCert bool `config:"no_check_certificate"`
|
SkipVerifyTLSCert bool `config:"no_check_certificate"`
|
||||||
DisableEPSV bool `config:"disable_epsv"`
|
DisableEPSV bool `config:"disable_epsv"`
|
||||||
@@ -148,20 +162,69 @@ 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() (*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(fs.Config.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 fs.Config.Dump&(fs.DumpHeaders|fs.DumpBodies|fs.DumpRequests|fs.DumpResponses) != 0 {
|
||||||
|
ftpConfig = append(ftpConfig, ftp.DialWithDebugOutput(&debugLog{auth: fs.Config.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)
|
||||||
@@ -799,10 +862,12 @@ func (f *ftpReadCloser) Close() error {
|
|||||||
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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ import (
|
|||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
|
||||||
"path"
|
"path"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -38,6 +37,7 @@ import (
|
|||||||
"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/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"
|
||||||
@@ -79,30 +79,29 @@ func init() {
|
|||||||
Config: func(name string, m configmap.Mapper) {
|
Config: func(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("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.",
|
||||||
@@ -242,6 +241,9 @@ 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",
|
||||||
@@ -253,7 +255,7 @@ Docs: https://cloud.google.com/storage/docs/bucket-policy-only
|
|||||||
Default: (encoder.Base |
|
Default: (encoder.Base |
|
||||||
encoder.EncodeCrLf |
|
encoder.EncodeCrLf |
|
||||||
encoder.EncodeInvalidUtf8),
|
encoder.EncodeInvalidUtf8),
|
||||||
}},
|
}}...),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -262,6 +264,7 @@ 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"`
|
||||||
|
Anonymous bool `config:"anonymous"`
|
||||||
ObjectACL string `config:"object_acl"`
|
ObjectACL string `config:"object_acl"`
|
||||||
BucketACL string `config:"bucket_acl"`
|
BucketACL string `config:"bucket_acl"`
|
||||||
BucketPolicyOnly bool `config:"bucket_policy_only"`
|
BucketPolicyOnly bool `config:"bucket_policy_only"`
|
||||||
@@ -402,13 +405,15 @@ 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 = &http.Client{}
|
||||||
|
} else if opt.ServiceAccountCredentials != "" {
|
||||||
oAuthClient, err = getServiceAccountClient([]byte(opt.ServiceAccountCredentials))
|
oAuthClient, err = getServiceAccountClient([]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")
|
||||||
@@ -555,7 +560,7 @@ func (f *Fs) list(ctx context.Context, bucket, directory, prefix string, addBuck
|
|||||||
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)
|
||||||
}
|
}
|
||||||
@@ -1063,6 +1068,33 @@ 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
|
||||||
|
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"
|
||||||
@@ -96,7 +95,7 @@ func init() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Do the oauth
|
// Do the oauth
|
||||||
err = oauthutil.Config("google photos", name, m, oauthConfig)
|
err = oauthutil.Config("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,20 @@ 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,
|
||||||
|
}}...),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fs represents a remote storage server
|
// Fs represents a remote storage server
|
||||||
@@ -202,6 +201,11 @@ 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
|
||||||
|
}
|
||||||
|
|
||||||
// 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 +228,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,
|
||||||
@@ -943,8 +951,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 +1012,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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ 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
|
||||||
}
|
}
|
||||||
|
|
||||||
// dirPattern describes a single directory pattern
|
// dirPattern describes a single directory pattern
|
||||||
@@ -52,6 +53,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 +191,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 +224,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 +246,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 +313,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,11 @@ func (f *testLister) dirTime() time.Time {
|
|||||||
return startTime
|
return startTime
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// mock startYear for testing
|
||||||
|
func (f *testLister) startYear() int {
|
||||||
|
return 2000
|
||||||
|
}
|
||||||
|
|
||||||
func TestPatternMatch(t *testing.T) {
|
func TestPatternMatch(t *testing.T) {
|
||||||
for testNumber, test := range []struct {
|
for testNumber, test := range []struct {
|
||||||
// input
|
// input
|
||||||
@@ -150,6 +155,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)
|
||||||
|
|||||||
@@ -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")
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ 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(*swift.Connection) (r *http.Request, err error) {
|
||||||
|
|||||||
+5
-12
@@ -20,7 +20,6 @@ import (
|
|||||||
"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/",
|
||||||
@@ -58,26 +57,20 @@ func init() {
|
|||||||
Description: "Hubic",
|
Description: "Hubic",
|
||||||
NewFs: NewFs,
|
NewFs: NewFs,
|
||||||
Config: func(name string, m configmap.Mapper) {
|
Config: func(name string, m configmap.Mapper) {
|
||||||
err := oauthutil.Config("hubic", name, m, oauthConfig)
|
err := oauthutil.Config("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 - eg "2015-11-09T14:24:56+01:00"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -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,6 +27,7 @@ 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/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"
|
||||||
@@ -39,26 +41,33 @@ import (
|
|||||||
|
|
||||||
// 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
|
||||||
)
|
)
|
||||||
|
|
||||||
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,
|
||||||
@@ -72,7 +81,7 @@ 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(name string, m configmap.Mapper) {
|
||||||
ctx := context.TODO()
|
ctx := context.TODO()
|
||||||
@@ -83,7 +92,7 @@ func init() {
|
|||||||
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 {
|
||||||
@@ -98,42 +107,12 @@ func init() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
clientConfig := *fs.Config
|
fmt.Printf("Use legacy authentification?.\nThis is only required for certain whitelabel versions of Jottacloud and not recommended for normal users.\n")
|
||||||
clientConfig.UserAgent = "JottaCli 0.6.18626 windows-amd64"
|
|
||||||
srv := rest.NewClient(fshttp.NewClient(&clientConfig))
|
|
||||||
|
|
||||||
fmt.Printf("Generate a personal login token here: https://www.jottacloud.com/web/secure\n")
|
|
||||||
fmt.Printf("Login Token> ")
|
|
||||||
loginToken := config.ReadLine()
|
|
||||||
|
|
||||||
token, err := doAuth(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) {
|
if config.Confirm(false) {
|
||||||
oAuthClient, _, err := oauthutil.NewClient(name, m, oauthConfig)
|
v1config(ctx, name, m)
|
||||||
if err != nil {
|
} else {
|
||||||
log.Fatalf("Failed to load oAuthClient: %s", err)
|
v2config(ctx, name, m)
|
||||||
}
|
|
||||||
|
|
||||||
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",
|
||||||
@@ -141,13 +120,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,
|
||||||
}, {
|
}, {
|
||||||
@@ -174,8 +153,8 @@ 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"`
|
||||||
|
TrashedOnly bool `config:"trashed_only"`
|
||||||
HardDelete bool `config:"hard_delete"`
|
HardDelete bool `config:"hard_delete"`
|
||||||
Unlink bool `config:"unlink"`
|
|
||||||
UploadThreshold fs.SizeSuffix `config:"upload_resume_limit"`
|
UploadThreshold fs.SizeSuffix `config:"upload_resume_limit"`
|
||||||
Enc encoder.MultiEncoder `config:"encoding"`
|
Enc encoder.MultiEncoder `config:"encoding"`
|
||||||
}
|
}
|
||||||
@@ -229,7 +208,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
|
||||||
@@ -251,8 +230,181 @@ 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
|
// v1config configure a jottacloud backend using legacy authentification
|
||||||
func doAuth(ctx context.Context, srv *rest.Client, loginTokenBase64 string, m configmap.Mapper) (token oauth2.Token, err error) {
|
func v1config(ctx context.Context, name string, m configmap.Mapper) {
|
||||||
|
srv := rest.NewClient(fshttp.NewClient(fs.Config))
|
||||||
|
|
||||||
|
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(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 authentification
|
||||||
|
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 authentification
|
||||||
|
func v2config(ctx context.Context, name string, m configmap.Mapper) {
|
||||||
|
srv := rest.NewClient(fshttp.NewClient(fs.Config))
|
||||||
|
|
||||||
|
fmt.Printf("Generate a personal login token here: https://www.jottacloud.com/web/secure\n")
|
||||||
|
fmt.Printf("Login Token> ")
|
||||||
|
loginToken := config.ReadLine()
|
||||||
|
|
||||||
|
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) {
|
||||||
|
oauthConfig.ClientID = "jottacli"
|
||||||
|
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))
|
||||||
|
}
|
||||||
|
|
||||||
|
// doAuthV2 runs the actual token request for V2 authentification
|
||||||
|
func doAuthV2(ctx context.Context, srv *rest.Client, loginTokenBase64 string, m configmap.Mapper) (token oauth2.Token, err error) {
|
||||||
loginTokenBytes, err := base64.RawURLEncoding.DecodeString(loginTokenBase64)
|
loginTokenBytes, err := base64.RawURLEncoding.DecodeString(loginTokenBase64)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return token, err
|
return token, err
|
||||||
@@ -448,7 +600,7 @@ 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)
|
||||||
}
|
}
|
||||||
@@ -458,11 +610,34 @@ func (f *Fs) filePathRaw(file string) string {
|
|||||||
return path.Join(f.endpointURL, f.opt.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(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
||||||
ctx := context.TODO()
|
ctx := context.TODO()
|
||||||
@@ -474,28 +649,55 @@ 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(fs.Config)
|
||||||
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(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")
|
||||||
@@ -519,6 +721,9 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
WriteMimeType: true,
|
WriteMimeType: true,
|
||||||
}).Fill(f)
|
}).Fill(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 {
|
||||||
@@ -638,13 +843,13 @@ 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, f.opt.Enc.ToStandardName(item.Name))
|
remote := path.Join(dir, f.opt.Enc.ToStandardName(item.Name))
|
||||||
@@ -654,8 +859,14 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
|
|||||||
|
|
||||||
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, f.opt.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)
|
||||||
@@ -859,8 +1070,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
|
||||||
@@ -876,7 +1087,8 @@ func (f *Fs) copyOrMove(ctx context.Context, method, src, dest string) (info *ap
|
|||||||
var resp *http.Response
|
var resp *http.Response
|
||||||
err = f.pacer.Call(func() (bool, error) {
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
resp, err = f.srv.CallXML(ctx, &opts, nil, &info)
|
resp, err = f.srv.CallXML(ctx, &opts, nil, &info)
|
||||||
return shouldRetry(resp, err)
|
retry, _ := shouldRetry(resp, err)
|
||||||
|
return (retry && resp.StatusCode != 500), err
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -980,6 +1192,18 @@ func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string
|
|||||||
|
|
||||||
_, err = f.copyOrMove(ctx, "mvDir", path.Join(f.endpointURL, f.opt.Enc.FromStandardPath(srcPath))+"/", dstRemote)
|
_, err = f.copyOrMove(ctx, "mvDir", path.Join(f.endpointURL, f.opt.Enc.FromStandardPath(srcPath))+"/", dstRemote)
|
||||||
|
|
||||||
|
// surprise! jottacloud fucked up dirmove - the api spits out an error but
|
||||||
|
// dir gets moved regardless
|
||||||
|
if apiErr, ok := err.(*api.Error); ok {
|
||||||
|
if apiErr.StatusCode == 500 {
|
||||||
|
_, err := f.NewObject(ctx, dstRemote)
|
||||||
|
if err == fs.ErrorNotAFile {
|
||||||
|
log.Printf("FIXME: ignoring DirMove error - move succeeded anyway\n")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.Wrap(err, "couldn't move directory")
|
return errors.Wrap(err, "couldn't move directory")
|
||||||
}
|
}
|
||||||
@@ -987,14 +1211,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")
|
||||||
@@ -1014,12 +1238,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)
|
||||||
}
|
}
|
||||||
@@ -1049,6 +1273,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)
|
||||||
@@ -1074,7 +1314,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)
|
||||||
}
|
}
|
||||||
@@ -1122,7 +1362,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)
|
||||||
@@ -1179,7 +1419,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)
|
||||||
@@ -1259,6 +1499,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()
|
||||||
@@ -1355,6 +1596,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)
|
||||||
)
|
)
|
||||||
@@ -79,7 +79,7 @@ type Options struct {
|
|||||||
Enc encoder.MultiEncoder `config:"encoding"`
|
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
|
||||||
@@ -250,7 +250,7 @@ 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 f.opt.Enc.FromStandardPath(path.Join("/", f.root, part))
|
return f.opt.Enc.FromStandardPath(path.Join("/", f.root, part))
|
||||||
}
|
}
|
||||||
@@ -421,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
|
||||||
@@ -603,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
|
||||||
|
|||||||
@@ -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
|
||||||
|
|
||||||
|
|||||||
+196
-70
@@ -10,7 +10,6 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"regexp"
|
|
||||||
"runtime"
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
@@ -41,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",
|
||||||
@@ -89,7 +89,24 @@ are being uploaded and aborts with a message which starts "can't copy
|
|||||||
|
|
||||||
However on some file systems this modification time check may fail (eg
|
However on some file systems this modification time check may fail (eg
|
||||||
[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 (eg 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,
|
||||||
}, {
|
}, {
|
||||||
@@ -117,6 +134,27 @@ 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,
|
Name: config.ConfigEncoding,
|
||||||
Help: config.ConfigEncodingHelp,
|
Help: config.ConfigEncodingHelp,
|
||||||
@@ -138,6 +176,8 @@ type Options struct {
|
|||||||
OneFileSystem bool `config:"one_file_system"`
|
OneFileSystem bool `config:"one_file_system"`
|
||||||
CaseSensitive bool `config:"case_sensitive"`
|
CaseSensitive bool `config:"case_sensitive"`
|
||||||
CaseInsensitive bool `config:"case_insensitive"`
|
CaseInsensitive bool `config:"case_insensitive"`
|
||||||
|
NoSparse bool `config:"no_sparse"`
|
||||||
|
NoSetModTime bool `config:"no_set_modtime"`
|
||||||
Enc encoder.MultiEncoder `config:"encoding"`
|
Enc encoder.MultiEncoder `config:"encoding"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -154,20 +194,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
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------
|
// ------------------------------------------------------------
|
||||||
@@ -202,6 +244,7 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
CaseInsensitive: f.caseInsensitive(),
|
CaseInsensitive: f.caseInsensitive(),
|
||||||
CanHaveEmptyDirectories: true,
|
CanHaveEmptyDirectories: true,
|
||||||
IsLocal: true,
|
IsLocal: true,
|
||||||
|
SlowHash: true,
|
||||||
}).Fill(f)
|
}).Fill(f)
|
||||||
if opt.FollowSymlinks {
|
if opt.FollowSymlinks {
|
||||||
f.lstat = os.Stat
|
f.lstat = os.Stat
|
||||||
@@ -511,6 +554,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()
|
||||||
})
|
})
|
||||||
@@ -569,20 +616,25 @@ 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.
|
||||||
@@ -603,6 +655,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()
|
||||||
@@ -610,7 +665,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")
|
||||||
}
|
}
|
||||||
@@ -697,6 +752,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
|
||||||
@@ -720,19 +819,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 {
|
||||||
@@ -744,9 +855,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 {
|
||||||
@@ -756,29 +872,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)
|
||||||
@@ -794,7 +917,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")
|
||||||
@@ -827,11 +952,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()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -848,9 +977,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
|
||||||
@@ -875,7 +1004,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)
|
||||||
@@ -890,6 +1019,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)
|
||||||
@@ -977,7 +1113,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)
|
||||||
}
|
}
|
||||||
@@ -1026,9 +1162,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
|
||||||
@@ -1041,6 +1177,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.
|
||||||
@@ -1064,29 +1202,38 @@ 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.Debugf(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.modTime = info.ModTime()
|
|
||||||
}
|
|
||||||
if o.mode != info.Mode() {
|
|
||||||
o.mode = info.Mode()
|
|
||||||
}
|
}
|
||||||
|
o.fs.objectMetaMu.Lock()
|
||||||
|
o.size = info.Size()
|
||||||
|
o.modTime = info.ModTime()
|
||||||
|
o.mode = info.Mode()
|
||||||
|
o.fs.objectMetaMu.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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 {
|
||||||
@@ -1115,7 +1262,7 @@ func cleanRootPath(s string, noUNC bool, enc encoder.MultiEncoder) string {
|
|||||||
|
|
||||||
if !noUNC {
|
if !noUNC {
|
||||||
// Convert to UNC
|
// Convert to UNC
|
||||||
s = uncPath(s)
|
s = file.UNCPath(s)
|
||||||
}
|
}
|
||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
@@ -1129,28 +1276,6 @@ func cleanRootPath(s string, noUNC bool, enc encoder.MultiEncoder) 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{}
|
||||||
@@ -1158,6 +1283,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{}
|
||||||
)
|
)
|
||||||
@@ -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
|
|
||||||
}
|
|
||||||
@@ -5,49 +5,6 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
var uncTestPaths = []string{
|
|
||||||
`C:\Ba*d\P|a?t<h>\Windows\Folder`,
|
|
||||||
`C:\Windows\Folder`,
|
|
||||||
`\\?\C:\Windows\Folder`,
|
|
||||||
`\\?\UNC\server\share\Desktop`,
|
|
||||||
`\\?\unC\server\share\Desktop\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path`,
|
|
||||||
`\\server\share\Desktop\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path`,
|
|
||||||
`C:\Desktop\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path`,
|
|
||||||
`C:\AbsoluteToRoot\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path`,
|
|
||||||
`\\server\share\Desktop`,
|
|
||||||
`\\?\UNC\\share\folder\Desktop`,
|
|
||||||
`\\server\share`,
|
|
||||||
}
|
|
||||||
|
|
||||||
var uncTestPathsResults = []string{
|
|
||||||
`\\?\C:\Ba*d\P|a?t<h>\Windows\Folder`,
|
|
||||||
`\\?\C:\Windows\Folder`,
|
|
||||||
`\\?\C:\Windows\Folder`,
|
|
||||||
`\\?\UNC\server\share\Desktop`,
|
|
||||||
`\\?\unC\server\share\Desktop\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path`,
|
|
||||||
`\\?\UNC\server\share\Desktop\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path`,
|
|
||||||
`\\?\C:\Desktop\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path`,
|
|
||||||
`\\?\C:\AbsoluteToRoot\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path\Very Long path`,
|
|
||||||
`\\?\UNC\server\share\Desktop`,
|
|
||||||
`\\?\UNC\\share\folder\Desktop`,
|
|
||||||
`\\?\UNC\server\share`,
|
|
||||||
}
|
|
||||||
|
|
||||||
// Test that UNC paths are converted.
|
|
||||||
func TestUncPaths(t *testing.T) {
|
|
||||||
for i, p := range uncTestPaths {
|
|
||||||
unc := uncPath(p)
|
|
||||||
if unc != uncTestPathsResults[i] {
|
|
||||||
t.Fatalf("UNC test path\nInput:%s\nOutput:%s\nExpected:%s", p, unc, uncTestPathsResults[i])
|
|
||||||
}
|
|
||||||
// Test we don't add more.
|
|
||||||
unc = uncPath(unc)
|
|
||||||
if unc != uncTestPathsResults[i] {
|
|
||||||
t.Fatalf("UNC test path\nInput:%s\nOutput:%s\nExpected:%s", p, unc, uncTestPathsResults[i])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Test Windows character replacements
|
// Test Windows character replacements
|
||||||
var testsWindows = [][2]string{
|
var testsWindows = [][2]string{
|
||||||
{`c:\temp`, `c:\temp`},
|
{`c:\temp`, `c:\temp`},
|
||||||
|
|||||||
@@ -402,7 +402,7 @@ func (q *quirks) parseQuirks(option string) {
|
|||||||
// "Accept-Encoding: gzip" header. However, enabling compression
|
// "Accept-Encoding: gzip" header. However, enabling compression
|
||||||
// might be good for performance.
|
// might be good for performance.
|
||||||
// Use this quirk to investigate the performance impact.
|
// Use this quirk to investigate the performance impact.
|
||||||
// Remove this quirk if perfomance does not improve.
|
// Remove this quirk if performance does not improve.
|
||||||
q.gzip = true
|
q.gzip = true
|
||||||
case "insecure":
|
case "insecure":
|
||||||
// The mailru disk-o protocol is not documented. To compare HTTP
|
// The mailru disk-o protocol is not documented. To compare HTTP
|
||||||
@@ -1162,12 +1162,12 @@ func (f *Fs) Rmdir(ctx context.Context, dir string) error {
|
|||||||
return f.purgeWithCheck(ctx, dir, true, "rmdir")
|
return f.purgeWithCheck(ctx, dir, true, "rmdir")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Purge deletes all the files and the root directory
|
// Purge deletes all the files in the directory
|
||||||
// Optional interface: Only implement this if you have a way of deleting
|
// Optional interface: Only implement this if you have a way of deleting
|
||||||
// all the files quicker than just running Remove() on the result of List()
|
// all the files quicker than just running Remove() on the result of List()
|
||||||
func (f *Fs) Purge(ctx context.Context) error {
|
func (f *Fs) Purge(ctx context.Context, dir string) error {
|
||||||
// fs.Debugf(f, ">>> Purge")
|
// fs.Debugf(f, ">>> Purge")
|
||||||
return f.purgeWithCheck(ctx, "", false, "purge")
|
return f.purgeWithCheck(ctx, dir, false, "purge")
|
||||||
}
|
}
|
||||||
|
|
||||||
// purgeWithCheck() removes the root directory.
|
// purgeWithCheck() removes the root directory.
|
||||||
@@ -1450,7 +1450,7 @@ 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) {
|
||||||
// fs.Debugf(f, ">>> PublicLink %q", remote)
|
// fs.Debugf(f, ">>> PublicLink %q", remote)
|
||||||
|
|
||||||
token, err := f.accessToken()
|
token, err := f.accessToken()
|
||||||
|
|||||||
@@ -150,7 +150,7 @@ func (f *Fs) Features() *fs.Features {
|
|||||||
return f.features
|
return f.features
|
||||||
}
|
}
|
||||||
|
|
||||||
// parsePath parses an mega 'url'
|
// parsePath parses a mega 'url'
|
||||||
func parsePath(path string) (root string) {
|
func parsePath(path string) (root string) {
|
||||||
root = strings.Trim(path, "/")
|
root = strings.Trim(path, "/")
|
||||||
return
|
return
|
||||||
@@ -669,13 +669,13 @@ func (f *Fs) Precision() time.Duration {
|
|||||||
return fs.ModTimeNotSupported
|
return fs.ModTimeNotSupported
|
||||||
}
|
}
|
||||||
|
|
||||||
// Purge deletes all the files and the container
|
// 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 {
|
||||||
return f.purgeCheck("", false)
|
return f.purgeCheck(dir, false)
|
||||||
}
|
}
|
||||||
|
|
||||||
// move a file or folder (srcFs, srcRemote, info) to (f, dstRemote)
|
// move a file or folder (srcFs, srcRemote, info) to (f, dstRemote)
|
||||||
@@ -836,7 +836,7 @@ func (f *Fs) Hashes() hash.Set {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 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) {
|
||||||
root, err := f.findRoot(false)
|
root, err := f.findRoot(false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", errors.Wrap(err, "PublicLink failed to find root node")
|
return "", errors.Wrap(err, "PublicLink failed to find root node")
|
||||||
@@ -871,7 +871,7 @@ func (f *Fs) MergeDirs(ctx context.Context, dirs []fs.Directory) error {
|
|||||||
return errors.Errorf("MergeDirs failed to find node for: %v", srcDir)
|
return errors.Errorf("MergeDirs failed to find node for: %v", srcDir)
|
||||||
}
|
}
|
||||||
|
|
||||||
// list the the objects
|
// list the objects
|
||||||
infos := []*mega.Node{}
|
infos := []*mega.Node{}
|
||||||
_, err := f.list(ctx, srcDirNode, func(info *mega.Node) bool {
|
_, err := f.list(ctx, srcDirNode, func(info *mega.Node) bool {
|
||||||
infos = append(infos, info)
|
infos = append(infos, info)
|
||||||
|
|||||||
@@ -272,19 +272,19 @@ type CreateShareLinkResponse struct {
|
|||||||
} `json:"link"`
|
} `json:"link"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// AsyncOperationStatus provides information on the status of a asynchronous job progress.
|
// AsyncOperationStatus provides information on the status of an asynchronous job progress.
|
||||||
//
|
//
|
||||||
// The following API calls return AsyncOperationStatus resources:
|
// The following API calls return AsyncOperationStatus resources:
|
||||||
//
|
//
|
||||||
// Copy Item
|
// Copy Item
|
||||||
// Upload From URL
|
// Upload From URL
|
||||||
type AsyncOperationStatus struct {
|
type AsyncOperationStatus struct {
|
||||||
PercentageComplete float64 `json:"percentageComplete"` // An float value between 0 and 100 that indicates the percentage complete.
|
PercentageComplete float64 `json:"percentageComplete"` // A float value between 0 and 100 that indicates the percentage complete.
|
||||||
Status string `json:"status"` // A string value that maps to an enumeration of possible values about the status of the job. "notStarted | inProgress | completed | updating | failed | deletePending | deleteFailed | waiting"
|
Status string `json:"status"` // A string value that maps to an enumeration of possible values about the status of the job. "notStarted | inProgress | completed | updating | failed | deletePending | deleteFailed | waiting"
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetID returns a normalized ID of the item
|
// GetID returns a normalized ID of the item
|
||||||
// If DriveID is known it will be prefixed to the ID with # seperator
|
// If DriveID is known it will be prefixed to the ID with # separator
|
||||||
// Can be parsed using onedrive.parseNormalizedID(normalizedID)
|
// Can be parsed using onedrive.parseNormalizedID(normalizedID)
|
||||||
func (i *Item) GetID() string {
|
func (i *Item) GetID() string {
|
||||||
if i.IsRemote() && i.RemoteItem.ID != "" {
|
if i.IsRemote() && i.RemoteItem.ID != "" {
|
||||||
@@ -410,3 +410,28 @@ func (i *Item) GetParentReference() *ItemReference {
|
|||||||
func (i *Item) IsRemote() bool {
|
func (i *Item) IsRemote() bool {
|
||||||
return i.RemoteItem != nil
|
return i.RemoteItem != nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// User details for each version
|
||||||
|
type User struct {
|
||||||
|
Email string `json:"email"`
|
||||||
|
ID string `json:"id"`
|
||||||
|
DisplayName string `json:"displayName"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// LastModifiedBy for each version
|
||||||
|
type LastModifiedBy struct {
|
||||||
|
User User `json:"user"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Version info
|
||||||
|
type Version struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
LastModifiedDateTime time.Time `json:"lastModifiedDateTime"`
|
||||||
|
Size int `json:"size"`
|
||||||
|
LastModifiedBy LastModifiedBy `json:"lastModifiedBy"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// VersionsResponse is returned from /versions
|
||||||
|
type VersionsResponse struct {
|
||||||
|
Versions []Version `json:"value"`
|
||||||
|
}
|
||||||
Regular → Executable
+202
-130
@@ -14,6 +14,7 @@ import (
|
|||||||
"path"
|
"path"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
@@ -26,6 +27,8 @@ import (
|
|||||||
"github.com/rclone/rclone/fs/config/obscure"
|
"github.com/rclone/rclone/fs/config/obscure"
|
||||||
"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/fs/operations"
|
||||||
|
"github.com/rclone/rclone/fs/walk"
|
||||||
"github.com/rclone/rclone/lib/atexit"
|
"github.com/rclone/rclone/lib/atexit"
|
||||||
"github.com/rclone/rclone/lib/dircache"
|
"github.com/rclone/rclone/lib/dircache"
|
||||||
"github.com/rclone/rclone/lib/encoder"
|
"github.com/rclone/rclone/lib/encoder"
|
||||||
@@ -79,7 +82,7 @@ func init() {
|
|||||||
NewFs: NewFs,
|
NewFs: NewFs,
|
||||||
Config: func(name string, m configmap.Mapper) {
|
Config: func(name string, m configmap.Mapper) {
|
||||||
ctx := context.TODO()
|
ctx := context.TODO()
|
||||||
err := oauthutil.Config("onedrive", name, m, oauthConfig)
|
err := oauthutil.Config("onedrive", 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)
|
||||||
return
|
return
|
||||||
@@ -184,6 +187,28 @@ func init() {
|
|||||||
log.Fatalf("Failed to query available drives: %v", err)
|
log.Fatalf("Failed to query available drives: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Also call /me/drive as sometimes /me/drives doesn't return it #4068
|
||||||
|
if opts.Path == "/me/drives" {
|
||||||
|
opts.Path = "/me/drive"
|
||||||
|
meDrive := driveResource{}
|
||||||
|
_, err := srv.CallJSON(ctx, &opts, nil, &meDrive)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to query available drives: %v", err)
|
||||||
|
}
|
||||||
|
found := false
|
||||||
|
for _, drive := range drives.Drives {
|
||||||
|
if drive.DriveID == meDrive.DriveID {
|
||||||
|
found = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// add the me drive if not found already
|
||||||
|
if !found {
|
||||||
|
fs.Debugf(nil, "Adding %v to drives list from /me/drive", meDrive)
|
||||||
|
drives.Drives = append(drives.Drives, meDrive)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if len(drives.Drives) == 0 {
|
if len(drives.Drives) == 0 {
|
||||||
log.Fatalf("No drives found")
|
log.Fatalf("No drives found")
|
||||||
} else {
|
} else {
|
||||||
@@ -216,18 +241,13 @@ func init() {
|
|||||||
m.Set(configDriveType, rootItem.ParentReference.DriveType)
|
m.Set(configDriveType, rootItem.ParentReference.DriveType)
|
||||||
config.SaveConfig()
|
config.SaveConfig()
|
||||||
},
|
},
|
||||||
Options: []fs.Option{{
|
Options: append(oauthutil.SharedOptions, []fs.Option{{
|
||||||
Name: config.ConfigClientID,
|
|
||||||
Help: "Microsoft App Client Id\nLeave blank normally.",
|
|
||||||
}, {
|
|
||||||
Name: config.ConfigClientSecret,
|
|
||||||
Help: "Microsoft App Client Secret\nLeave blank normally.",
|
|
||||||
}, {
|
|
||||||
Name: "chunk_size",
|
Name: "chunk_size",
|
||||||
Help: `Chunk size to upload files with - must be multiple of 320k (327,680 bytes).
|
Help: `Chunk size to upload files with - must be multiple of 320k (327,680 bytes).
|
||||||
|
|
||||||
Above this size files will be chunked - must be multiple of 320k (327,680 bytes). Note
|
Above this size files will be chunked - must be multiple of 320k (327,680 bytes) and
|
||||||
that the chunks will be buffered into memory.`,
|
should not exceed 250M (262,144,000 bytes) else you may encounter \"Microsoft.SharePoint.Client.InvalidClientQueryException: The request message is too big.\"
|
||||||
|
Note that the chunks will be buffered into memory.`,
|
||||||
Default: defaultChunkSize,
|
Default: defaultChunkSize,
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
}, {
|
}, {
|
||||||
@@ -251,6 +271,33 @@ delete OneNote files or otherwise want them to show up in directory
|
|||||||
listing, set this option.`,
|
listing, set this option.`,
|
||||||
Default: false,
|
Default: false,
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: "server_side_across_configs",
|
||||||
|
Default: false,
|
||||||
|
Help: `Allow server side operations (eg copy) to work across different onedrive configs.
|
||||||
|
|
||||||
|
This can be useful if you wish to do a server side copy between two
|
||||||
|
different Onedrives. Note that this isn't enabled by default
|
||||||
|
because it isn't easy to tell if it will work between any two
|
||||||
|
configurations.`,
|
||||||
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: "no_versions",
|
||||||
|
Default: false,
|
||||||
|
Help: `Remove all versions on modifying operations
|
||||||
|
|
||||||
|
Onedrive for business creates versions when rclone uploads new files
|
||||||
|
overwriting an existing one and when it sets the modification time.
|
||||||
|
|
||||||
|
These versions take up space out of the quota.
|
||||||
|
|
||||||
|
This flag checks for versions after file upload and setting
|
||||||
|
modification time and removes all but the last version.
|
||||||
|
|
||||||
|
**NB** Onedrive personal can't currently delete versions so don't use
|
||||||
|
this flag there.
|
||||||
|
`,
|
||||||
|
Advanced: true,
|
||||||
}, {
|
}, {
|
||||||
Name: config.ConfigEncoding,
|
Name: config.ConfigEncoding,
|
||||||
Help: config.ConfigEncodingHelp,
|
Help: config.ConfigEncodingHelp,
|
||||||
@@ -297,17 +344,19 @@ listing, set this option.`,
|
|||||||
encoder.EncodeRightSpace |
|
encoder.EncodeRightSpace |
|
||||||
encoder.EncodeWin |
|
encoder.EncodeWin |
|
||||||
encoder.EncodeInvalidUtf8),
|
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"`
|
||||||
DriveID string `config:"drive_id"`
|
DriveID string `config:"drive_id"`
|
||||||
DriveType string `config:"drive_type"`
|
DriveType string `config:"drive_type"`
|
||||||
ExposeOneNoteFiles bool `config:"expose_onenote_files"`
|
ExposeOneNoteFiles bool `config:"expose_onenote_files"`
|
||||||
Enc encoder.MultiEncoder `config:"encoding"`
|
ServerSideAcrossConfigs bool `config:"server_side_across_configs"`
|
||||||
|
NoVersions bool `config:"no_versions"`
|
||||||
|
Enc encoder.MultiEncoder `config:"encoding"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fs represents a remote one drive
|
// Fs represents a remote one drive
|
||||||
@@ -362,7 +411,7 @@ func (f *Fs) Features() *fs.Features {
|
|||||||
return f.features
|
return f.features
|
||||||
}
|
}
|
||||||
|
|
||||||
// parsePath parses an one drive 'url'
|
// parsePath parses a one drive 'url'
|
||||||
func parsePath(path string) (root string) {
|
func parsePath(path string) (root string) {
|
||||||
root = strings.Trim(path, "/")
|
root = strings.Trim(path, "/")
|
||||||
return
|
return
|
||||||
@@ -402,6 +451,8 @@ func shouldRetry(resp *http.Response, err error) (bool, error) {
|
|||||||
fs.Debugf(nil, "Too many requests. Trying again in %d seconds.", retryAfter)
|
fs.Debugf(nil, "Too many requests. Trying again in %d seconds.", retryAfter)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
case 507: // Insufficient Storage
|
||||||
|
return false, fserrors.FatalError(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return retry || fserrors.ShouldRetry(err) || fserrors.ShouldRetryHTTP(resp, retryErrorCodes), err
|
return retry || fserrors.ShouldRetry(err) || fserrors.ShouldRetryHTTP(resp, retryErrorCodes), err
|
||||||
@@ -462,13 +513,13 @@ func (f *Fs) readMetaDataForPath(ctx context.Context, path string) (info *api.It
|
|||||||
var dirCacheFoundRoot bool
|
var dirCacheFoundRoot bool
|
||||||
var rootNormalizedID string
|
var rootNormalizedID string
|
||||||
if f.dirCache != nil {
|
if f.dirCache != nil {
|
||||||
var dirCacheRootIDExists bool
|
rootNormalizedID, err = f.dirCache.RootID(ctx, false)
|
||||||
rootNormalizedID, dirCacheRootIDExists = f.dirCache.Get("")
|
dirCacheRootIDExists := err == nil
|
||||||
if f.root == "" {
|
if f.root == "" {
|
||||||
// if f.root == "", it means f.root is the absolute root of the drive
|
// if f.root == "", it means f.root is the absolute root of the drive
|
||||||
// and its ID should have been found in NewFs
|
// and its ID should have been found in NewFs
|
||||||
dirCacheFoundRoot = dirCacheRootIDExists
|
dirCacheFoundRoot = dirCacheRootIDExists
|
||||||
} else if _, err := f.dirCache.RootParentID(); err == nil {
|
} else if _, err := f.dirCache.RootParentID(ctx, false); err == nil {
|
||||||
// if root is in a folder, it must have a parent folder, and
|
// if root is in a folder, it must have a parent folder, and
|
||||||
// if dirCache has found root in NewFs, the parent folder's ID
|
// if dirCache has found root in NewFs, the parent folder's ID
|
||||||
// should be present.
|
// should be present.
|
||||||
@@ -576,6 +627,7 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
CaseInsensitive: true,
|
CaseInsensitive: true,
|
||||||
ReadMimeType: true,
|
ReadMimeType: true,
|
||||||
CanHaveEmptyDirectories: true,
|
CanHaveEmptyDirectories: true,
|
||||||
|
ServerSideAcrossConfigs: opt.ServerSideAcrossConfigs,
|
||||||
}).Fill(f)
|
}).Fill(f)
|
||||||
f.srv.SetErrorHandler(errorHandler)
|
f.srv.SetErrorHandler(errorHandler)
|
||||||
|
|
||||||
@@ -776,10 +828,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
|
||||||
@@ -827,7 +875,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 nil, leaf, directoryID, err
|
return nil, leaf, directoryID, err
|
||||||
}
|
}
|
||||||
@@ -858,13 +906,7 @@ 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
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -887,10 +929,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
|
||||||
@@ -988,10 +1026,13 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
srcPath := srcObj.rootPath()
|
// Check we aren't overwriting a file on the same remote
|
||||||
dstPath := f.rootPath(remote)
|
if srcObj.fs == f {
|
||||||
if strings.ToLower(srcPath) == strings.ToLower(dstPath) {
|
srcPath := srcObj.rootPath()
|
||||||
return nil, errors.Errorf("can't copy %q -> %q as are same name when lowercase", srcPath, dstPath)
|
dstPath := f.rootPath(remote)
|
||||||
|
if strings.ToLower(srcPath) == strings.ToLower(dstPath) {
|
||||||
|
return nil, errors.Errorf("can't copy %q -> %q as are same name when lowercase", srcPath, dstPath)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create temporary object
|
// Create temporary object
|
||||||
@@ -1047,13 +1088,13 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
return dstObj, nil
|
return dstObj, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Purge deletes all the files and the container
|
// 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 {
|
||||||
return f.purgeCheck(ctx, "", false)
|
return f.purgeCheck(ctx, dir, false)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Move src to this remote using server side move operations.
|
// Move src to this remote using server side move operations.
|
||||||
@@ -1081,9 +1122,10 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
id, dstDriveID, _ := parseNormalizedID(directoryID)
|
id, dstDriveID, _ := parseNormalizedID(directoryID)
|
||||||
_, srcObjDriveID, _ := parseNormalizedID(srcObj.id)
|
_, srcObjDriveID, _ := parseNormalizedID(srcObj.id)
|
||||||
|
|
||||||
if dstDriveID != srcObjDriveID {
|
if f.canonicalDriveID(dstDriveID) != srcObj.fs.canonicalDriveID(srcObjDriveID) {
|
||||||
// https://docs.microsoft.com/en-us/graph/api/driveitem-move?view=graph-rest-1.0
|
// https://docs.microsoft.com/en-us/graph/api/driveitem-move?view=graph-rest-1.0
|
||||||
// "Items cannot be moved between Drives using this request."
|
// "Items cannot be moved between Drives using this request."
|
||||||
|
fs.Debugf(f, "Can't move files between drives (%q != %q)", dstDriveID, srcObjDriveID)
|
||||||
return nil, fs.ErrorCantMove
|
return nil, fs.ErrorCantMove
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1133,70 +1175,22 @@ 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 {
|
if err != nil {
|
||||||
return err
|
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, dstDirectoryID string
|
|
||||||
findPath := dstRemote
|
|
||||||
if dstRemote == "" {
|
|
||||||
findPath = f.root
|
|
||||||
}
|
|
||||||
leaf, dstDirectoryID, err = f.dirCache.FindPath(ctx, findPath, true)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
parsedDstDirID, dstDriveID, _ := parseNormalizedID(dstDirectoryID)
|
parsedDstDirID, dstDriveID, _ := parseNormalizedID(dstDirectoryID)
|
||||||
|
|
||||||
// Find ID of src
|
|
||||||
srcID, err := srcFs.dirCache.FindDir(ctx, srcRemote, false)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
_, srcDriveID, _ := parseNormalizedID(srcID)
|
_, srcDriveID, _ := parseNormalizedID(srcID)
|
||||||
|
|
||||||
if dstDriveID != srcDriveID {
|
if f.canonicalDriveID(dstDriveID) != srcFs.canonicalDriveID(srcDriveID) {
|
||||||
// https://docs.microsoft.com/en-us/graph/api/driveitem-move?view=graph-rest-1.0
|
// https://docs.microsoft.com/en-us/graph/api/driveitem-move?view=graph-rest-1.0
|
||||||
// "Items cannot be moved between Drives using this request."
|
// "Items cannot be moved between Drives using this request."
|
||||||
|
fs.Debugf(f, "Can't move directories between drives (%q != %q)", dstDriveID, srcDriveID)
|
||||||
return fs.ErrorCantDirMove
|
return fs.ErrorCantDirMove
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get timestamps of src so they can be preserved
|
// Get timestamps of src so they can be preserved
|
||||||
srcInfo, _, err := srcFs.readMetaDataForPathRelativeToID(ctx, srcID, "")
|
srcInfo, _, err := srcFs.readMetaDataForPathRelativeToID(ctx, srcID, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -1206,7 +1200,7 @@ func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string
|
|||||||
// Do the move
|
// Do the move
|
||||||
opts := newOptsCall(srcID, "PATCH", "")
|
opts := newOptsCall(srcID, "PATCH", "")
|
||||||
move := api.MoveItemRequest{
|
move := api.MoveItemRequest{
|
||||||
Name: f.opt.Enc.FromStandardName(leaf),
|
Name: f.opt.Enc.FromStandardName(dstLeaf),
|
||||||
ParentReference: &api.ItemReference{
|
ParentReference: &api.ItemReference{
|
||||||
DriveID: dstDriveID,
|
DriveID: dstDriveID,
|
||||||
ID: parsedDstDirID,
|
ID: parsedDstDirID,
|
||||||
@@ -1270,8 +1264,8 @@ func (f *Fs) Hashes() hash.Set {
|
|||||||
return hash.Set(QuickXorHashType)
|
return hash.Set(QuickXorHashType)
|
||||||
}
|
}
|
||||||
|
|
||||||
// PublicLink returns a link for downloading without accout.
|
// 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) {
|
||||||
info, _, err := f.readMetaDataForPath(ctx, f.rootPath(remote))
|
info, _, err := f.readMetaDataForPath(ctx, f.rootPath(remote))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
@@ -1296,6 +1290,73 @@ func (f *Fs) PublicLink(ctx context.Context, remote string) (link string, err er
|
|||||||
return result.Link.WebURL, nil
|
return result.Link.WebURL, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CleanUp deletes all the hidden files.
|
||||||
|
func (f *Fs) CleanUp(ctx context.Context) error {
|
||||||
|
token := make(chan struct{}, fs.Config.Checkers)
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
err := walk.Walk(ctx, f, "", true, -1, func(path string, entries fs.DirEntries, err error) error {
|
||||||
|
err = entries.ForObjectError(func(obj fs.Object) error {
|
||||||
|
o, ok := obj.(*Object)
|
||||||
|
if !ok {
|
||||||
|
return errors.New("internal error: not a onedrive object")
|
||||||
|
}
|
||||||
|
wg.Add(1)
|
||||||
|
token <- struct{}{}
|
||||||
|
go func() {
|
||||||
|
defer func() {
|
||||||
|
<-token
|
||||||
|
wg.Done()
|
||||||
|
}()
|
||||||
|
err := o.deleteVersions(ctx)
|
||||||
|
if err != nil {
|
||||||
|
fs.Errorf(o, "Failed to remove versions: %v", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
wg.Wait()
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Finds and removes any old versions for o
|
||||||
|
func (o *Object) deleteVersions(ctx context.Context) error {
|
||||||
|
opts := newOptsCall(o.id, "GET", "/versions")
|
||||||
|
var versions api.VersionsResponse
|
||||||
|
err := o.fs.pacer.Call(func() (bool, error) {
|
||||||
|
resp, err := o.fs.srv.CallJSON(ctx, &opts, nil, &versions)
|
||||||
|
return shouldRetry(resp, err)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(versions.Versions) < 2 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
for _, version := range versions.Versions[1:] {
|
||||||
|
err = o.deleteVersion(ctx, version.ID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Finds and removes any old versions for o
|
||||||
|
func (o *Object) deleteVersion(ctx context.Context, ID string) error {
|
||||||
|
if operations.SkipDestructive(ctx, fmt.Sprintf("%s of %s", ID, o.remote), "delete version") {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
fs.Infof(o, "removing version %q", ID)
|
||||||
|
opts := newOptsCall(o.id, "DELETE", "/versions/"+ID)
|
||||||
|
opts.NoResponse = true
|
||||||
|
return o.fs.pacer.Call(func() (bool, error) {
|
||||||
|
resp, err := o.fs.srv.Call(ctx, &opts)
|
||||||
|
return shouldRetry(resp, err)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------
|
// ------------------------------------------------------------
|
||||||
|
|
||||||
// Fs returns the parent Fs
|
// Fs returns the parent Fs
|
||||||
@@ -1459,6 +1520,13 @@ func (o *Object) setModTime(ctx context.Context, modTime time.Time) (*api.Item,
|
|||||||
resp, err := o.fs.srv.CallJSON(ctx, &opts, &update, &info)
|
resp, err := o.fs.srv.CallJSON(ctx, &opts, &update, &info)
|
||||||
return shouldRetry(resp, err)
|
return shouldRetry(resp, err)
|
||||||
})
|
})
|
||||||
|
// Remove versions if required
|
||||||
|
if o.fs.opt.NoVersions {
|
||||||
|
err := o.deleteVersions(ctx)
|
||||||
|
if err != nil {
|
||||||
|
fs.Errorf(o, "Failed to remove versions: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
return info, err
|
return info, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1572,7 +1640,7 @@ func (o *Object) getPosition(ctx context.Context, url string) (pos int64, err er
|
|||||||
}
|
}
|
||||||
|
|
||||||
// uploadFragment uploads a part
|
// uploadFragment uploads a part
|
||||||
func (o *Object) uploadFragment(ctx context.Context, url string, start int64, totalSize int64, chunk io.ReadSeeker, chunkSize int64) (info *api.Item, err error) {
|
func (o *Object) uploadFragment(ctx context.Context, url string, start int64, totalSize int64, chunk io.ReadSeeker, chunkSize int64, options ...fs.OpenOption) (info *api.Item, err error) {
|
||||||
// var response api.UploadFragmentResponse
|
// var response api.UploadFragmentResponse
|
||||||
var resp *http.Response
|
var resp *http.Response
|
||||||
var body []byte
|
var body []byte
|
||||||
@@ -1585,6 +1653,7 @@ func (o *Object) uploadFragment(ctx context.Context, url string, start int64, to
|
|||||||
ContentLength: &toSend,
|
ContentLength: &toSend,
|
||||||
ContentRange: fmt.Sprintf("bytes %d-%d/%d", start+skip, start+chunkSize-1, totalSize),
|
ContentRange: fmt.Sprintf("bytes %d-%d/%d", start+skip, start+chunkSize-1, totalSize),
|
||||||
Body: chunk,
|
Body: chunk,
|
||||||
|
Options: options,
|
||||||
}
|
}
|
||||||
_, _ = chunk.Seek(skip, io.SeekStart)
|
_, _ = chunk.Seek(skip, io.SeekStart)
|
||||||
resp, err = o.fs.srv.Call(ctx, &opts)
|
resp, err = o.fs.srv.Call(ctx, &opts)
|
||||||
@@ -1642,46 +1711,27 @@ func (o *Object) cancelUploadSession(ctx context.Context, url 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, size int64, modTime time.Time) (info *api.Item, err error) {
|
func (o *Object) uploadMultipart(ctx context.Context, in io.Reader, size int64, modTime time.Time, options ...fs.OpenOption) (info *api.Item, err error) {
|
||||||
if size <= 0 {
|
if size <= 0 {
|
||||||
return nil, errors.New("unknown-sized upload not supported")
|
return nil, errors.New("unknown-sized upload not supported")
|
||||||
}
|
}
|
||||||
|
|
||||||
uploadURLChan := make(chan string, 1)
|
|
||||||
gracefulCancel := func() {
|
|
||||||
uploadURL, ok := <-uploadURLChan
|
|
||||||
// Reading from uploadURLChan blocks the atexit process until
|
|
||||||
// we are able to use uploadURL to cancel the upload
|
|
||||||
if !ok { // createUploadSession failed - no need to cancel upload
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
fs.Debugf(o, "Cancelling multipart upload")
|
|
||||||
cancelErr := o.cancelUploadSession(ctx, uploadURL)
|
|
||||||
if cancelErr != nil {
|
|
||||||
fs.Logf(o, "Failed to cancel multipart upload: %v", cancelErr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
cancelFuncHandle := atexit.Register(gracefulCancel)
|
|
||||||
|
|
||||||
// Create upload session
|
// Create upload session
|
||||||
fs.Debugf(o, "Starting multipart upload")
|
fs.Debugf(o, "Starting multipart upload")
|
||||||
session, err := o.createUploadSession(ctx, modTime)
|
session, err := o.createUploadSession(ctx, modTime)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
close(uploadURLChan)
|
|
||||||
atexit.Unregister(cancelFuncHandle)
|
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
uploadURL := session.UploadURL
|
uploadURL := session.UploadURL
|
||||||
uploadURLChan <- uploadURL
|
|
||||||
|
|
||||||
defer func() {
|
// Cancel the session if something went wrong
|
||||||
if err != nil {
|
defer atexit.OnError(&err, func() {
|
||||||
fs.Debugf(o, "Error encountered during upload: %v", err)
|
fs.Debugf(o, "Cancelling multipart upload: %v", err)
|
||||||
gracefulCancel()
|
cancelErr := o.cancelUploadSession(ctx, uploadURL)
|
||||||
|
if cancelErr != nil {
|
||||||
|
fs.Logf(o, "Failed to cancel multipart upload: %v", cancelErr)
|
||||||
}
|
}
|
||||||
atexit.Unregister(cancelFuncHandle)
|
})()
|
||||||
}()
|
|
||||||
|
|
||||||
// Upload the chunks
|
// Upload the chunks
|
||||||
remaining := size
|
remaining := size
|
||||||
@@ -1693,7 +1743,7 @@ func (o *Object) uploadMultipart(ctx context.Context, in io.Reader, size int64,
|
|||||||
}
|
}
|
||||||
seg := readers.NewRepeatableReader(io.LimitReader(in, n))
|
seg := readers.NewRepeatableReader(io.LimitReader(in, n))
|
||||||
fs.Debugf(o, "Uploading segment %d/%d size %d", position, size, n)
|
fs.Debugf(o, "Uploading segment %d/%d size %d", position, size, n)
|
||||||
info, err = o.uploadFragment(ctx, uploadURL, position, size, seg, n)
|
info, err = o.uploadFragment(ctx, uploadURL, position, size, seg, n, options...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -1706,7 +1756,7 @@ func (o *Object) uploadMultipart(ctx context.Context, in io.Reader, size int64,
|
|||||||
|
|
||||||
// Update the content of a remote file within 4MB size in one single request
|
// Update the content of a remote file within 4MB size in one single request
|
||||||
// This function will set modtime after uploading, which will create a new version for the remote file
|
// This function will set modtime after uploading, which will create a new version for the remote file
|
||||||
func (o *Object) uploadSinglepart(ctx context.Context, in io.Reader, size int64, modTime time.Time) (info *api.Item, err error) {
|
func (o *Object) uploadSinglepart(ctx context.Context, in io.Reader, size int64, modTime time.Time, options ...fs.OpenOption) (info *api.Item, err error) {
|
||||||
if size < 0 || size > int64(fs.SizeSuffix(4*1024*1024)) {
|
if size < 0 || size > int64(fs.SizeSuffix(4*1024*1024)) {
|
||||||
return nil, errors.New("size passed into uploadSinglepart must be >= 0 and <= 4MiB")
|
return nil, errors.New("size passed into uploadSinglepart must be >= 0 and <= 4MiB")
|
||||||
}
|
}
|
||||||
@@ -1723,6 +1773,7 @@ func (o *Object) uploadSinglepart(ctx context.Context, in io.Reader, size int64,
|
|||||||
Path: "/" + drive + "/items/" + trueDirID + ":/" + rest.URLPathEscape(o.fs.opt.Enc.FromStandardName(leaf)) + ":/content",
|
Path: "/" + drive + "/items/" + trueDirID + ":/" + rest.URLPathEscape(o.fs.opt.Enc.FromStandardName(leaf)) + ":/content",
|
||||||
ContentLength: &size,
|
ContentLength: &size,
|
||||||
Body: in,
|
Body: in,
|
||||||
|
Options: options,
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
opts = rest.Opts{
|
opts = rest.Opts{
|
||||||
@@ -1730,6 +1781,7 @@ func (o *Object) uploadSinglepart(ctx context.Context, in io.Reader, size int64,
|
|||||||
Path: "/root:/" + rest.URLPathEscape(o.srvPath()) + ":/content",
|
Path: "/root:/" + rest.URLPathEscape(o.srvPath()) + ":/content",
|
||||||
ContentLength: &size,
|
ContentLength: &size,
|
||||||
Body: in,
|
Body: in,
|
||||||
|
Options: options,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1771,9 +1823,9 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
|
|
||||||
var info *api.Item
|
var info *api.Item
|
||||||
if size > 0 {
|
if size > 0 {
|
||||||
info, err = o.uploadMultipart(ctx, in, size, modTime)
|
info, err = o.uploadMultipart(ctx, in, size, modTime, options...)
|
||||||
} else if size == 0 {
|
} else if size == 0 {
|
||||||
info, err = o.uploadSinglepart(ctx, in, size, modTime)
|
info, err = o.uploadSinglepart(ctx, in, size, modTime, options...)
|
||||||
} else {
|
} else {
|
||||||
return errors.New("unknown-sized upload not supported")
|
return errors.New("unknown-sized upload not supported")
|
||||||
}
|
}
|
||||||
@@ -1781,6 +1833,14 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// If updating the file then remove versions
|
||||||
|
if o.fs.opt.NoVersions && o.hasMetaData {
|
||||||
|
err = o.deleteVersions(ctx)
|
||||||
|
if err != nil {
|
||||||
|
fs.Errorf(o, "Failed to remove versions: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return o.setMetaData(info)
|
return o.setMetaData(info)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1826,6 +1886,17 @@ func parseNormalizedID(ID string) (string, string, string) {
|
|||||||
return ID, "", ""
|
return ID, "", ""
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Returns the canonical form of the driveID
|
||||||
|
func (f *Fs) canonicalDriveID(driveID string) (canonicalDriveID string) {
|
||||||
|
if driveID == "" {
|
||||||
|
canonicalDriveID = f.opt.DriveID
|
||||||
|
} else {
|
||||||
|
canonicalDriveID = driveID
|
||||||
|
}
|
||||||
|
canonicalDriveID = strings.ToLower(canonicalDriveID)
|
||||||
|
return canonicalDriveID
|
||||||
|
}
|
||||||
|
|
||||||
// getRelativePathInsideBase checks if `target` is inside `base`. If so, it
|
// getRelativePathInsideBase checks if `target` is inside `base`. If so, it
|
||||||
// returns a relative path for `target` based on `base` and a boolean `true`.
|
// returns a relative path for `target` based on `base` and a boolean `true`.
|
||||||
// Otherwise returns "", false.
|
// Otherwise returns "", false.
|
||||||
@@ -1866,6 +1937,7 @@ var (
|
|||||||
_ fs.DirCacheFlusher = (*Fs)(nil)
|
_ fs.DirCacheFlusher = (*Fs)(nil)
|
||||||
_ fs.Abouter = (*Fs)(nil)
|
_ fs.Abouter = (*Fs)(nil)
|
||||||
_ fs.PublicLinker = (*Fs)(nil)
|
_ fs.PublicLinker = (*Fs)(nil)
|
||||||
|
_ fs.CleanUpper = (*Fs)(nil)
|
||||||
_ fs.Object = (*Object)(nil)
|
_ fs.Object = (*Object)(nil)
|
||||||
_ fs.MimeTyper = &Object{}
|
_ fs.MimeTyper = &Object{}
|
||||||
_ fs.IDer = &Object{}
|
_ fs.IDer = &Object{}
|
||||||
|
|||||||
@@ -63,7 +63,7 @@ func init() {
|
|||||||
// ? (question mark) -> '?' // FULLWIDTH QUESTION MARK
|
// ? (question mark) -> '?' // FULLWIDTH QUESTION MARK
|
||||||
// * (asterisk) -> '*' // FULLWIDTH ASTERISK
|
// * (asterisk) -> '*' // FULLWIDTH ASTERISK
|
||||||
//
|
//
|
||||||
// Additionally names can't begin or end with a ASCII whitespace.
|
// Additionally names can't begin or end with an ASCII whitespace.
|
||||||
// List of replaced characters:
|
// List of replaced characters:
|
||||||
// (space) -> '␠' // SYMBOL FOR SPACE
|
// (space) -> '␠' // SYMBOL FOR SPACE
|
||||||
// (horizontal tab) -> '␉' // SYMBOL FOR HORIZONTAL TABULATION
|
// (horizontal tab) -> '␉' // SYMBOL FOR HORIZONTAL TABULATION
|
||||||
@@ -280,13 +280,7 @@ func errorHandler(resp *http.Response) error {
|
|||||||
// Mkdir creates the folder if it doesn't exist
|
// Mkdir creates the folder 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 {
|
||||||
// fs.Debugf(nil, "Mkdir(\"%s\")", dir)
|
// fs.Debugf(nil, "Mkdir(\"%s\")", dir)
|
||||||
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
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -312,10 +306,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
|
||||||
@@ -483,58 +473,8 @@ 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
|
||||||
}
|
}
|
||||||
@@ -546,9 +486,9 @@ func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string
|
|||||||
moveFolderData := moveCopyFolder{
|
moveFolderData := moveCopyFolder{
|
||||||
SessionID: f.session.SessionID,
|
SessionID: f.session.SessionID,
|
||||||
FolderID: srcID,
|
FolderID: srcID,
|
||||||
DstFolderID: directoryID,
|
DstFolderID: dstDirectoryID,
|
||||||
Move: "true",
|
Move: "true",
|
||||||
NewFolderName: leaf,
|
NewFolderName: dstLeaf,
|
||||||
}
|
}
|
||||||
opts := rest.Opts{
|
opts := rest.Opts{
|
||||||
Method: "POST",
|
Method: "POST",
|
||||||
@@ -566,13 +506,13 @@ func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Purge deletes all the files and the container
|
// 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 {
|
||||||
return f.purgeCheck(ctx, "", false)
|
return f.purgeCheck(ctx, dir, false)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Return an Object from a path
|
// Return an Object from a path
|
||||||
@@ -620,7 +560,7 @@ func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) {
|
|||||||
// 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 nil, leaf, directoryID, err
|
return nil, leaf, directoryID, err
|
||||||
}
|
}
|
||||||
@@ -677,7 +617,7 @@ func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options .
|
|||||||
}
|
}
|
||||||
|
|
||||||
if "" == o.id {
|
if "" == o.id {
|
||||||
// We need to create a ID for this file
|
// We need to create an ID for this file
|
||||||
var resp *http.Response
|
var resp *http.Response
|
||||||
response := createFileResponse{}
|
response := createFileResponse{}
|
||||||
err := o.fs.pacer.Call(func() (bool, error) {
|
err := o.fs.pacer.Call(func() (bool, error) {
|
||||||
@@ -687,8 +627,9 @@ func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options .
|
|||||||
Name: leaf,
|
Name: leaf,
|
||||||
}
|
}
|
||||||
opts := rest.Opts{
|
opts := rest.Opts{
|
||||||
Method: "POST",
|
Method: "POST",
|
||||||
Path: "/upload/create_file.json",
|
Options: options,
|
||||||
|
Path: "/upload/create_file.json",
|
||||||
}
|
}
|
||||||
resp, err = o.fs.srv.CallJSON(ctx, &opts, &createFileData, &response)
|
resp, err = o.fs.srv.CallJSON(ctx, &opts, &createFileData, &response)
|
||||||
return o.fs.shouldRetry(resp, err)
|
return o.fs.shouldRetry(resp, err)
|
||||||
@@ -802,10 +743,6 @@ func (f *Fs) FindLeaf(ctx context.Context, pathID, leaf string) (pathIDOut strin
|
|||||||
// 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) {
|
||||||
// fs.Debugf(nil, "List(%v)", dir)
|
// fs.Debugf(nil, "List(%v)", dir)
|
||||||
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
|
||||||
@@ -970,8 +907,9 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
openUploadData := openUpload{SessionID: o.fs.session.SessionID, FileID: o.id, Size: size}
|
openUploadData := openUpload{SessionID: o.fs.session.SessionID, FileID: o.id, Size: size}
|
||||||
// fs.Debugf(nil, "PreOpen: %#v", openUploadData)
|
// fs.Debugf(nil, "PreOpen: %#v", openUploadData)
|
||||||
opts := rest.Opts{
|
opts := rest.Opts{
|
||||||
Method: "POST",
|
Method: "POST",
|
||||||
Path: "/upload/open_file_upload.json",
|
Options: options,
|
||||||
|
Path: "/upload/open_file_upload.json",
|
||||||
}
|
}
|
||||||
resp, err := o.fs.srv.CallJSON(ctx, &opts, &openUploadData, &openResponse)
|
resp, err := o.fs.srv.CallJSON(ctx, &opts, &openUploadData, &openResponse)
|
||||||
return o.fs.shouldRetry(resp, err)
|
return o.fs.shouldRetry(resp, err)
|
||||||
@@ -1077,7 +1015,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (o *Object) readMetaData(ctx context.Context) (err error) {
|
func (o *Object) readMetaData(ctx context.Context) (err error) {
|
||||||
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
|
||||||
|
|||||||
@@ -18,13 +18,13 @@ func (e *Error) Error() string {
|
|||||||
return fmt.Sprintf("%s (Error %d)", e.Info.Message, e.Info.Code)
|
return fmt.Sprintf("%s (Error %d)", e.Info.Message, e.Info.Code)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Account describes a OpenDRIVE account
|
// Account describes an OpenDRIVE account
|
||||||
type Account struct {
|
type Account struct {
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
Password string `json:"passwd"`
|
Password string `json:"passwd"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// UserSessionInfo describes a OpenDRIVE session
|
// UserSessionInfo describes an OpenDRIVE session
|
||||||
type UserSessionInfo struct {
|
type UserSessionInfo struct {
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
Password string `json:"passwd"`
|
Password string `json:"passwd"`
|
||||||
@@ -45,7 +45,7 @@ type UserSessionInfo struct {
|
|||||||
PartnerUsersDomain string `json:"PartnerUsersDomain"`
|
PartnerUsersDomain string `json:"PartnerUsersDomain"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// FolderList describes a OpenDRIVE listing
|
// FolderList describes an OpenDRIVE listing
|
||||||
type FolderList struct {
|
type FolderList struct {
|
||||||
// DirUpdateTime string `json:"DirUpdateTime,string"`
|
// DirUpdateTime string `json:"DirUpdateTime,string"`
|
||||||
Name string `json:"Name"`
|
Name string `json:"Name"`
|
||||||
@@ -56,7 +56,7 @@ type FolderList struct {
|
|||||||
Files []File `json:"Files"`
|
Files []File `json:"Files"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Folder describes a OpenDRIVE folder
|
// Folder describes an OpenDRIVE folder
|
||||||
type Folder struct {
|
type Folder struct {
|
||||||
FolderID string `json:"FolderID"`
|
FolderID string `json:"FolderID"`
|
||||||
Name string `json:"Name"`
|
Name string `json:"Name"`
|
||||||
@@ -109,7 +109,7 @@ type removeFolder struct {
|
|||||||
FolderID string `json:"folder_id"`
|
FolderID string `json:"folder_id"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// File describes a OpenDRIVE file
|
// File describes an OpenDRIVE file
|
||||||
type File struct {
|
type File struct {
|
||||||
FileID string `json:"FileId"`
|
FileID string `json:"FileId"`
|
||||||
FileHash string `json:"FileHash"`
|
FileHash string `json:"FileHash"`
|
||||||
|
|||||||
@@ -152,6 +152,14 @@ type ChecksumFileResult struct {
|
|||||||
Metadata Item `json:"metadata"`
|
Metadata Item `json:"metadata"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// PubLinkResult is returned from /getfilepublink and /getfolderpublink
|
||||||
|
type PubLinkResult struct {
|
||||||
|
Error
|
||||||
|
LinkID int `json:"linkid"`
|
||||||
|
Link string `json:"link"`
|
||||||
|
LinkCode string `json:"code"`
|
||||||
|
}
|
||||||
|
|
||||||
// UserInfo is returned from /userinfo
|
// UserInfo is returned from /userinfo
|
||||||
type UserInfo struct {
|
type UserInfo struct {
|
||||||
Error
|
Error
|
||||||
|
|||||||
+137
-94
@@ -41,9 +41,8 @@ const (
|
|||||||
rcloneEncryptedClientSecret = "ej1OIF39VOQQ0PXaSdK9ztkLw3tdLNscW2157TKNQdQKkICR4uU7aFg4eFM"
|
rcloneEncryptedClientSecret = "ej1OIF39VOQQ0PXaSdK9ztkLw3tdLNscW2157TKNQdQKkICR4uU7aFg4eFM"
|
||||||
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 = "d0" // ID of root folder is always this
|
defaultHostname = "api.pcloud.com"
|
||||||
rootURL = "https://api.pcloud.com"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Globals
|
// Globals
|
||||||
@@ -52,8 +51,8 @@ var (
|
|||||||
oauthConfig = &oauth2.Config{
|
oauthConfig = &oauth2.Config{
|
||||||
Scopes: nil,
|
Scopes: nil,
|
||||||
Endpoint: oauth2.Endpoint{
|
Endpoint: oauth2.Endpoint{
|
||||||
AuthURL: "https://my.pcloud.com/oauth2/authorize",
|
AuthURL: "https://my.pcloud.com/oauth2/authorize",
|
||||||
TokenURL: "https://api.pcloud.com/oauth2_token",
|
// TokenURL: "https://api.pcloud.com/oauth2_token", set by updateTokenURL
|
||||||
},
|
},
|
||||||
ClientID: rcloneClientID,
|
ClientID: rcloneClientID,
|
||||||
ClientSecret: obscure.MustReveal(rcloneEncryptedClientSecret),
|
ClientSecret: obscure.MustReveal(rcloneEncryptedClientSecret),
|
||||||
@@ -61,25 +60,50 @@ var (
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Update the TokenURL with the actual hostname
|
||||||
|
func updateTokenURL(oauthConfig *oauth2.Config, hostname string) {
|
||||||
|
oauthConfig.Endpoint.TokenURL = "https://" + hostname + "/oauth2_token"
|
||||||
|
}
|
||||||
|
|
||||||
// Register with Fs
|
// Register with Fs
|
||||||
func init() {
|
func init() {
|
||||||
|
updateTokenURL(oauthConfig, defaultHostname)
|
||||||
fs.Register(&fs.RegInfo{
|
fs.Register(&fs.RegInfo{
|
||||||
Name: "pcloud",
|
Name: "pcloud",
|
||||||
Description: "Pcloud",
|
Description: "Pcloud",
|
||||||
NewFs: NewFs,
|
NewFs: NewFs,
|
||||||
Config: func(name string, m configmap.Mapper) {
|
Config: func(name string, m configmap.Mapper) {
|
||||||
err := oauthutil.Config("pcloud", name, m, oauthConfig)
|
optc := new(Options)
|
||||||
|
err := configstruct.Set(m, optc)
|
||||||
|
if err != nil {
|
||||||
|
fs.Errorf(nil, "Failed to read config: %v", err)
|
||||||
|
}
|
||||||
|
updateTokenURL(oauthConfig, optc.Hostname)
|
||||||
|
checkAuth := func(oauthConfig *oauth2.Config, auth *oauthutil.AuthResult) error {
|
||||||
|
if auth == nil || auth.Form == nil {
|
||||||
|
return errors.New("form not found in response")
|
||||||
|
}
|
||||||
|
hostname := auth.Form.Get("hostname")
|
||||||
|
if hostname == "" {
|
||||||
|
hostname = defaultHostname
|
||||||
|
}
|
||||||
|
// Save the hostname in the config
|
||||||
|
m.Set("hostname", hostname)
|
||||||
|
// Update the token URL
|
||||||
|
updateTokenURL(oauthConfig, hostname)
|
||||||
|
fs.Debugf(nil, "pcloud: got hostname %q", hostname)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
opt := oauthutil.Options{
|
||||||
|
CheckAuth: checkAuth,
|
||||||
|
StateBlankOK: true, // pCloud seems to drop the state parameter now - see #4210
|
||||||
|
}
|
||||||
|
err = oauthutil.Config("pcloud", name, m, oauthConfig, &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: "Pcloud App Client Id\nLeave blank normally.",
|
|
||||||
}, {
|
|
||||||
Name: config.ConfigClientSecret,
|
|
||||||
Help: "Pcloud App Client Secret\nLeave blank normally.",
|
|
||||||
}, {
|
|
||||||
Name: config.ConfigEncoding,
|
Name: config.ConfigEncoding,
|
||||||
Help: config.ConfigEncodingHelp,
|
Help: config.ConfigEncodingHelp,
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
@@ -89,13 +113,37 @@ func init() {
|
|||||||
Default: (encoder.Display |
|
Default: (encoder.Display |
|
||||||
encoder.EncodeBackSlash |
|
encoder.EncodeBackSlash |
|
||||||
encoder.EncodeInvalidUtf8),
|
encoder.EncodeInvalidUtf8),
|
||||||
}},
|
}, {
|
||||||
|
Name: "root_folder_id",
|
||||||
|
Help: "Fill in for rclone to use a non root folder as its starting point.",
|
||||||
|
Default: "d0",
|
||||||
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: "hostname",
|
||||||
|
Help: `Hostname to connect to.
|
||||||
|
|
||||||
|
This is normally set when rclone initially does the oauth connection,
|
||||||
|
however you will need to set it by hand if you are using remote config
|
||||||
|
with rclone authorize.
|
||||||
|
`,
|
||||||
|
Default: defaultHostname,
|
||||||
|
Advanced: true,
|
||||||
|
Examples: []fs.OptionExample{{
|
||||||
|
Value: defaultHostname,
|
||||||
|
Help: "Original/US region",
|
||||||
|
}, {
|
||||||
|
Value: "eapi.pcloud.com",
|
||||||
|
Help: "EU region",
|
||||||
|
}},
|
||||||
|
}}...),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Options defines the configuration for this backend
|
// Options defines the configuration for this backend
|
||||||
type Options struct {
|
type Options struct {
|
||||||
Enc encoder.MultiEncoder `config:"encoding"`
|
Enc encoder.MultiEncoder `config:"encoding"`
|
||||||
|
RootFolderID string `config:"root_folder_id"`
|
||||||
|
Hostname string `config:"hostname"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fs represents a remote pcloud
|
// Fs represents a remote pcloud
|
||||||
@@ -147,7 +195,7 @@ func (f *Fs) Features() *fs.Features {
|
|||||||
return f.features
|
return f.features
|
||||||
}
|
}
|
||||||
|
|
||||||
// parsePath parses an pcloud 'url'
|
// parsePath parses a pcloud 'url'
|
||||||
func parsePath(path string) (root string) {
|
func parsePath(path string) (root string) {
|
||||||
root = strings.Trim(path, "/")
|
root = strings.Trim(path, "/")
|
||||||
return
|
return
|
||||||
@@ -190,7 +238,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
|
||||||
@@ -245,12 +293,13 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "failed to configure Pcloud")
|
return nil, errors.Wrap(err, "failed to configure Pcloud")
|
||||||
}
|
}
|
||||||
|
updateTokenURL(oauthConfig, opt.Hostname)
|
||||||
|
|
||||||
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(oAuthClient).SetRoot("https://" + opt.Hostname),
|
||||||
pacer: fs.NewPacer(pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
|
pacer: fs.NewPacer(pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
|
||||||
}
|
}
|
||||||
f.features = (&fs.Features{
|
f.features = (&fs.Features{
|
||||||
@@ -265,7 +314,8 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
return err
|
return err
|
||||||
})
|
})
|
||||||
|
|
||||||
// Get rootID
|
// 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
|
||||||
@@ -446,10 +496,6 @@ func (f *Fs) listAll(ctx context.Context, dirID string, directoriesOnly bool, fi
|
|||||||
// 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
|
||||||
@@ -490,7 +536,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
|
||||||
}
|
}
|
||||||
@@ -521,13 +567,7 @@ 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
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -539,10 +579,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
|
||||||
@@ -639,18 +675,18 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
return dstObj, nil
|
return dstObj, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Purge deletes all the files and the container
|
// 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 {
|
||||||
return f.purgeCheck(ctx, "", false)
|
return f.purgeCheck(ctx, dir, false)
|
||||||
}
|
}
|
||||||
|
|
||||||
// CleanUp empties the trash
|
// CleanUp empties the trash
|
||||||
func (f *Fs) CleanUp(ctx context.Context) error {
|
func (f *Fs) CleanUp(ctx context.Context) error {
|
||||||
err := f.dirCache.FindRoot(ctx, false)
|
rootID, err := f.dirCache.RootID(ctx, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -659,7 +695,7 @@ func (f *Fs) CleanUp(ctx context.Context) error {
|
|||||||
Path: "/trash_clear",
|
Path: "/trash_clear",
|
||||||
Parameters: url.Values{},
|
Parameters: url.Values{},
|
||||||
}
|
}
|
||||||
opts.Parameters.Set("folderid", dirIDtoNumber(f.dirCache.RootID()))
|
opts.Parameters.Set("folderid", dirIDtoNumber(rootID))
|
||||||
var resp *http.Response
|
var resp *http.Response
|
||||||
var result api.Error
|
var result api.Error
|
||||||
return f.pacer.Call(func() (bool, error) {
|
return f.pacer.Call(func() (bool, error) {
|
||||||
@@ -732,58 +768,8 @@ 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
|
||||||
}
|
}
|
||||||
@@ -795,8 +781,8 @@ func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string
|
|||||||
Parameters: url.Values{},
|
Parameters: url.Values{},
|
||||||
}
|
}
|
||||||
opts.Parameters.Set("folderid", dirIDtoNumber(srcID))
|
opts.Parameters.Set("folderid", dirIDtoNumber(srcID))
|
||||||
opts.Parameters.Set("toname", f.opt.Enc.FromStandardName(leaf))
|
opts.Parameters.Set("toname", f.opt.Enc.FromStandardName(dstLeaf))
|
||||||
opts.Parameters.Set("tofolderid", dirIDtoNumber(directoryID))
|
opts.Parameters.Set("tofolderid", dirIDtoNumber(dstDirectoryID))
|
||||||
var resp *http.Response
|
var resp *http.Response
|
||||||
var result api.ItemResult
|
var result api.ItemResult
|
||||||
err = f.pacer.Call(func() (bool, error) {
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
@@ -818,6 +804,61 @@ func (f *Fs) DirCacheFlush() {
|
|||||||
f.dirCache.ResetRoot()
|
f.dirCache.ResetRoot()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (f *Fs) linkDir(ctx context.Context, dirID string, expire fs.Duration) (string, error) {
|
||||||
|
opts := rest.Opts{
|
||||||
|
Method: "POST",
|
||||||
|
Path: "/getfolderpublink",
|
||||||
|
Parameters: url.Values{},
|
||||||
|
}
|
||||||
|
var result api.PubLinkResult
|
||||||
|
opts.Parameters.Set("folderid", dirIDtoNumber(dirID))
|
||||||
|
err := f.pacer.Call(func() (bool, error) {
|
||||||
|
resp, err := f.srv.CallJSON(ctx, &opts, nil, &result)
|
||||||
|
err = result.Error.Update(err)
|
||||||
|
return shouldRetry(resp, err)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return result.Link, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fs) linkFile(ctx context.Context, path string, expire fs.Duration) (string, error) {
|
||||||
|
obj, err := f.NewObject(ctx, path)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
o := obj.(*Object)
|
||||||
|
opts := rest.Opts{
|
||||||
|
Method: "POST",
|
||||||
|
Path: "/getfilepublink",
|
||||||
|
Parameters: url.Values{},
|
||||||
|
}
|
||||||
|
var result api.PubLinkResult
|
||||||
|
opts.Parameters.Set("fileid", fileIDtoNumber(o.id))
|
||||||
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
|
resp, err := f.srv.CallJSON(ctx, &opts, nil, &result)
|
||||||
|
err = result.Error.Update(err)
|
||||||
|
return shouldRetry(resp, err)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return result.Link, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// PublicLink adds a "readable by anyone with link" permission on the given file or folder.
|
||||||
|
func (f *Fs) PublicLink(ctx context.Context, remote string, expire fs.Duration, unlink bool) (string, error) {
|
||||||
|
dirID, err := f.dirCache.FindDir(ctx, remote, false)
|
||||||
|
if err == fs.ErrorDirNotFound {
|
||||||
|
return f.linkFile(ctx, remote, expire)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return f.linkDir(ctx, dirID, expire)
|
||||||
|
}
|
||||||
|
|
||||||
// About gets quota information
|
// About gets quota information
|
||||||
func (f *Fs) About(ctx context.Context) (usage *fs.Usage, err error) {
|
func (f *Fs) About(ctx context.Context) (usage *fs.Usage, err error) {
|
||||||
opts := rest.Opts{
|
opts := rest.Opts{
|
||||||
@@ -1047,7 +1088,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
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
|
||||||
}
|
}
|
||||||
@@ -1074,6 +1115,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
ContentLength: &size,
|
ContentLength: &size,
|
||||||
Parameters: url.Values{},
|
Parameters: url.Values{},
|
||||||
TransferEncoding: []string{"identity"}, // pcloud doesn't like chunked encoding
|
TransferEncoding: []string{"identity"}, // pcloud doesn't like chunked encoding
|
||||||
|
Options: options,
|
||||||
}
|
}
|
||||||
leaf = o.fs.opt.Enc.FromStandardName(leaf)
|
leaf = o.fs.opt.Enc.FromStandardName(leaf)
|
||||||
opts.Parameters.Set("filename", leaf)
|
opts.Parameters.Set("filename", leaf)
|
||||||
@@ -1151,6 +1193,7 @@ var (
|
|||||||
_ 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.Abouter = (*Fs)(nil)
|
_ fs.Abouter = (*Fs)(nil)
|
||||||
_ fs.Object = (*Object)(nil)
|
_ fs.Object = (*Object)(nil)
|
||||||
_ fs.IDer = (*Object)(nil)
|
_ fs.IDer = (*Object)(nil)
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ type Response struct {
|
|||||||
Status string `json:"status"`
|
Status string `json:"status"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Error statisfies the error interface
|
// Error satisfies the error interface
|
||||||
func (e *Response) Error() string {
|
func (e *Response) Error() string {
|
||||||
return fmt.Sprintf("%s: %s", e.Status, e.Message)
|
return fmt.Sprintf("%s: %s", e.Status, e.Message)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -79,7 +79,7 @@ func init() {
|
|||||||
Description: "premiumize.me",
|
Description: "premiumize.me",
|
||||||
NewFs: NewFs,
|
NewFs: NewFs,
|
||||||
Config: func(name string, m configmap.Mapper) {
|
Config: func(name string, m configmap.Mapper) {
|
||||||
err := oauthutil.Config("premiumizeme", name, m, oauthConfig)
|
err := oauthutil.Config("premiumizeme", 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)
|
||||||
}
|
}
|
||||||
@@ -183,7 +183,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, directoriesOnly bool, filesOnly bool) (info *api.Item, err error) {
|
func (f *Fs) readMetaDataForPath(ctx context.Context, path string, directoriesOnly bool, filesOnly bool) (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
|
||||||
@@ -450,10 +450,6 @@ func (f *Fs) listAll(ctx context.Context, dirID string, directoriesOnly bool, fi
|
|||||||
// 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
|
||||||
@@ -493,7 +489,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
|
||||||
}
|
}
|
||||||
@@ -517,7 +513,7 @@ func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options .
|
|||||||
return existingObj, existingObj.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)
|
return f.PutUnchecked(ctx, in, src, options...)
|
||||||
default:
|
default:
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -544,13 +540,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
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -562,10 +552,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
|
||||||
@@ -623,13 +609,13 @@ func (f *Fs) Precision() time.Duration {
|
|||||||
return fs.ModTimeNotSupported
|
return fs.ModTimeNotSupported
|
||||||
}
|
}
|
||||||
|
|
||||||
// Purge deletes all the files and the container
|
// 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 {
|
||||||
return f.purgeCheck(ctx, "", false)
|
return f.purgeCheck(ctx, dir, false)
|
||||||
}
|
}
|
||||||
|
|
||||||
// move a file or folder
|
// move a file or folder
|
||||||
@@ -745,75 +731,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, srcDirectoryID, srcLeaf, 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 {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Find ID of src parent, not creating subdirs
|
|
||||||
var srcLeaf, srcDirectoryID string
|
|
||||||
findPath = srcRemote
|
|
||||||
if srcRemote == "" {
|
|
||||||
findPath = srcFs.root
|
|
||||||
}
|
|
||||||
srcLeaf, srcDirectoryID, err = srcFs.dirCache.FindPath(ctx, findPath, false)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Do the move
|
// Do the move
|
||||||
err = f.move(ctx, false, srcID, srcLeaf, leaf, srcDirectoryID, directoryID)
|
err = f.move(ctx, false, srcID, srcLeaf, dstLeaf, srcDirectoryID, dstDirectoryID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -822,7 +747,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) {
|
||||||
_, err := f.dirCache.FindDir(ctx, remote, false)
|
_, err := f.dirCache.FindDir(ctx, remote, false)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return "", fs.ErrorCantShareDirectories
|
return "", fs.ErrorCantShareDirectories
|
||||||
@@ -990,7 +915,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
size := src.Size()
|
size := src.Size()
|
||||||
|
|
||||||
// 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
|
||||||
}
|
}
|
||||||
@@ -1002,6 +927,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
|||||||
Method: "POST",
|
Method: "POST",
|
||||||
Path: "/folder/uploadinfo",
|
Path: "/folder/uploadinfo",
|
||||||
Parameters: o.fs.baseParams(),
|
Parameters: o.fs.baseParams(),
|
||||||
|
Options: options,
|
||||||
MultipartParams: url.Values{
|
MultipartParams: url.Values{
|
||||||
"id": {directoryID},
|
"id": {directoryID},
|
||||||
},
|
},
|
||||||
|
|||||||
+49
-105
@@ -18,6 +18,7 @@ import (
|
|||||||
"github.com/rclone/rclone/fs"
|
"github.com/rclone/rclone/fs"
|
||||||
"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/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/oauthutil"
|
"github.com/rclone/rclone/lib/oauthutil"
|
||||||
@@ -34,7 +35,8 @@ type Fs struct {
|
|||||||
client *putio.Client // client for making API calls to Put.io
|
client *putio.Client // client for making API calls to Put.io
|
||||||
pacer *fs.Pacer // To pace the API calls
|
pacer *fs.Pacer // To pace the API calls
|
||||||
dirCache *dircache.DirCache // Map of directory path to directory id
|
dirCache *dircache.DirCache // Map of directory path to directory id
|
||||||
oAuthClient *http.Client
|
httpClient *http.Client // base http client
|
||||||
|
oAuthClient *http.Client // http client with oauth Authorization
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------
|
// ------------------------------------------------------------
|
||||||
@@ -59,6 +61,12 @@ func (f *Fs) Features() *fs.Features {
|
|||||||
return f.features
|
return f.features
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// parsePath parses a putio 'url'
|
||||||
|
func parsePath(path string) (root string) {
|
||||||
|
root = strings.Trim(path, "/")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// 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) (f fs.Fs, err error) {
|
func NewFs(name, root string, m configmap.Mapper) (f fs.Fs, err error) {
|
||||||
// defer log.Trace(name, "root=%v", root)("f=%+v, err=%v", &f, &err)
|
// defer log.Trace(name, "root=%v", root)("f=%+v, err=%v", &f, &err)
|
||||||
@@ -68,7 +76,9 @@ func NewFs(name, root string, m configmap.Mapper) (f fs.Fs, err error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
oAuthClient, _, err := oauthutil.NewClient(name, m, putioConfig)
|
root = parsePath(root)
|
||||||
|
httpClient := fshttp.NewClient(fs.Config)
|
||||||
|
oAuthClient, _, err := oauthutil.NewClientWithBaseClient(name, m, putioConfig, httpClient)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "failed to configure putio")
|
return nil, errors.Wrap(err, "failed to configure putio")
|
||||||
}
|
}
|
||||||
@@ -78,6 +88,7 @@ func NewFs(name, root string, m configmap.Mapper) (f fs.Fs, err error) {
|
|||||||
opt: *opt,
|
opt: *opt,
|
||||||
pacer: fs.NewPacer(pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
|
pacer: fs.NewPacer(pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
|
||||||
client: putio.NewClient(oAuthClient),
|
client: putio.NewClient(oAuthClient),
|
||||||
|
httpClient: httpClient,
|
||||||
oAuthClient: oAuthClient,
|
oAuthClient: oAuthClient,
|
||||||
}
|
}
|
||||||
p.features = (&fs.Features{
|
p.features = (&fs.Features{
|
||||||
@@ -186,10 +197,6 @@ func (f *Fs) FindLeaf(ctx context.Context, pathID, leaf string) (pathIDOut strin
|
|||||||
// 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(f, "dir=%v", dir)("err=%v", &err)
|
// defer log.Trace(f, "dir=%v", dir)("err=%v", &err)
|
||||||
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
|
||||||
@@ -249,11 +256,11 @@ func (f *Fs) PutUnchecked(ctx context.Context, in io.Reader, src fs.ObjectInfo,
|
|||||||
// defer log.Trace(f, "src=%+v", src)("o=%+v, err=%v", &o, &err)
|
// defer log.Trace(f, "src=%+v", src)("o=%+v, err=%v", &o, &err)
|
||||||
size := src.Size()
|
size := src.Size()
|
||||||
remote := src.Remote()
|
remote := src.Remote()
|
||||||
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
|
||||||
}
|
}
|
||||||
loc, err := f.createUpload(ctx, leaf, size, directoryID, src.ModTime(ctx))
|
loc, err := f.createUpload(ctx, leaf, size, directoryID, src.ModTime(ctx), options)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -273,7 +280,7 @@ func (f *Fs) PutUnchecked(ctx context.Context, in io.Reader, src fs.ObjectInfo,
|
|||||||
return f.newObjectWithInfo(ctx, remote, entry)
|
return f.newObjectWithInfo(ctx, remote, entry)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fs) createUpload(ctx context.Context, name string, size int64, parentID string, modTime time.Time) (location string, err error) {
|
func (f *Fs) createUpload(ctx context.Context, name string, size int64, parentID string, modTime time.Time, options []fs.OpenOption) (location string, err error) {
|
||||||
// defer log.Trace(f, "name=%v, size=%v, parentID=%v, modTime=%v", name, size, parentID, modTime.String())("location=%v, err=%v", location, &err)
|
// defer log.Trace(f, "name=%v, size=%v, parentID=%v, modTime=%v", name, size, parentID, modTime.String())("location=%v, err=%v", location, &err)
|
||||||
err = f.pacer.Call(func() (bool, error) {
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
req, err := http.NewRequest("POST", "https://upload.put.io/files/", nil)
|
req, err := http.NewRequest("POST", "https://upload.put.io/files/", nil)
|
||||||
@@ -288,6 +295,7 @@ func (f *Fs) createUpload(ctx context.Context, name string, size int64, parentID
|
|||||||
b64parentID := base64.StdEncoding.EncodeToString([]byte(parentID))
|
b64parentID := base64.StdEncoding.EncodeToString([]byte(parentID))
|
||||||
b64modifiedAt := base64.StdEncoding.EncodeToString([]byte(modTime.Format(time.RFC3339)))
|
b64modifiedAt := base64.StdEncoding.EncodeToString([]byte(modTime.Format(time.RFC3339)))
|
||||||
req.Header.Set("upload-metadata", fmt.Sprintf("name %s,no-torrent %s,parent_id %s,updated-at %s", b64name, b64true, b64parentID, b64modifiedAt))
|
req.Header.Set("upload-metadata", fmt.Sprintf("name %s,no-torrent %s,parent_id %s,updated-at %s", b64name, b64true, b64parentID, b64modifiedAt))
|
||||||
|
fs.OpenOptionAddHTTPHeaders(req.Header, options)
|
||||||
resp, err := f.oAuthClient.Do(req)
|
resp, err := f.oAuthClient.Do(req)
|
||||||
retry, err := shouldRetry(err)
|
retry, err := shouldRetry(err)
|
||||||
if retry {
|
if retry {
|
||||||
@@ -446,20 +454,13 @@ func (f *Fs) makeUploadPatchRequest(ctx context.Context, location string, in io.
|
|||||||
// 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) (err error) {
|
func (f *Fs) Mkdir(ctx context.Context, dir string) (err error) {
|
||||||
// defer log.Trace(f, "dir=%v", dir)("err=%v", &err)
|
// defer log.Trace(f, "dir=%v", dir)("err=%v", &err)
|
||||||
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
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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) (err error) {
|
|
||||||
// defer log.Trace(f, "dir=%v", dir)("err=%v", &err)
|
// defer log.Trace(f, "dir=%v", dir)("err=%v", &err)
|
||||||
|
|
||||||
root := strings.Trim(path.Join(f.root, dir), "/")
|
root := strings.Trim(path.Join(f.root, dir), "/")
|
||||||
@@ -476,18 +477,20 @@ func (f *Fs) Rmdir(ctx context.Context, dir string) (err error) {
|
|||||||
}
|
}
|
||||||
dirID := atoi(directoryID)
|
dirID := atoi(directoryID)
|
||||||
|
|
||||||
// check directory empty
|
if check {
|
||||||
var children []putio.File
|
// check directory empty
|
||||||
err = f.pacer.Call(func() (bool, error) {
|
var children []putio.File
|
||||||
// fs.Debugf(f, "listing files: %d", dirID)
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
children, _, err = f.client.Files.List(ctx, dirID)
|
// fs.Debugf(f, "listing files: %d", dirID)
|
||||||
return shouldRetry(err)
|
children, _, err = f.client.Files.List(ctx, dirID)
|
||||||
})
|
return shouldRetry(err)
|
||||||
if err != nil {
|
})
|
||||||
return errors.Wrap(err, "Rmdir")
|
if err != nil {
|
||||||
}
|
return errors.Wrap(err, "Rmdir")
|
||||||
if len(children) != 0 {
|
}
|
||||||
return errors.New("directory not empty")
|
if len(children) != 0 {
|
||||||
|
return errors.New("directory not empty")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// remove it
|
// remove it
|
||||||
@@ -500,36 +503,26 @@ func (f *Fs) Rmdir(ctx context.Context, dir string) (err 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) (err error) {
|
||||||
|
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
|
||||||
}
|
}
|
||||||
|
|
||||||
// Purge deletes all the files and the container
|
// 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) (err error) {
|
func (f *Fs) Purge(ctx context.Context, dir string) (err error) {
|
||||||
// defer log.Trace(f, "")("err=%v", &err)
|
// defer log.Trace(f, "")("err=%v", &err)
|
||||||
|
return f.purgeCheck(ctx, dir, false)
|
||||||
if f.root == "" {
|
|
||||||
return errors.New("can't purge root directory")
|
|
||||||
}
|
|
||||||
err = f.dirCache.FindRoot(ctx, false)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
rootID := atoi(f.dirCache.RootID())
|
|
||||||
// Let putio delete the filesystem tree
|
|
||||||
err = f.pacer.Call(func() (bool, error) {
|
|
||||||
// fs.Debugf(f, "deleting file: %d", rootID)
|
|
||||||
err = f.client.Files.Delete(ctx, rootID)
|
|
||||||
return shouldRetry(err)
|
|
||||||
})
|
|
||||||
f.dirCache.ResetRoot()
|
|
||||||
return err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Copy src to this remote using server side copy operations.
|
// Copy src to this remote using server side copy operations.
|
||||||
@@ -547,7 +540,7 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (o fs.Objec
|
|||||||
if !ok {
|
if !ok {
|
||||||
return nil, fs.ErrorCantCopy
|
return nil, fs.ErrorCantCopy
|
||||||
}
|
}
|
||||||
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
|
||||||
}
|
}
|
||||||
@@ -586,7 +579,7 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (o fs.Objec
|
|||||||
if !ok {
|
if !ok {
|
||||||
return nil, fs.ErrorCantMove
|
return nil, fs.ErrorCantMove
|
||||||
}
|
}
|
||||||
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
|
||||||
}
|
}
|
||||||
@@ -624,57 +617,8 @@ func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string
|
|||||||
if !ok {
|
if !ok {
|
||||||
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 == "" {
|
|
||||||
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, dstDirectoryID string
|
|
||||||
findPath := dstRemote
|
|
||||||
if dstRemote == "" {
|
|
||||||
findPath = f.root
|
|
||||||
}
|
|
||||||
leaf, dstDirectoryID, 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
|
||||||
}
|
}
|
||||||
@@ -683,7 +627,7 @@ func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string
|
|||||||
params := url.Values{}
|
params := url.Values{}
|
||||||
params.Set("file_id", srcID)
|
params.Set("file_id", srcID)
|
||||||
params.Set("parent_id", dstDirectoryID)
|
params.Set("parent_id", dstDirectoryID)
|
||||||
params.Set("name", f.opt.Enc.FromStandardName(leaf))
|
params.Set("name", f.opt.Enc.FromStandardName(dstLeaf))
|
||||||
req, err := f.client.NewRequest(ctx, "POST", "/v2/files/move", strings.NewReader(params.Encode()))
|
req, err := f.client.NewRequest(ctx, "POST", "/v2/files/move", strings.NewReader(params.Encode()))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
|
|||||||
@@ -125,7 +125,7 @@ func (o *Object) setMetadataFromEntry(info putio.File) error {
|
|||||||
// Reads the entry for a file from putio
|
// Reads the entry for a file from putio
|
||||||
func (o *Object) readEntry(ctx context.Context) (f *putio.File, err error) {
|
func (o *Object) readEntry(ctx context.Context) (f *putio.File, err error) {
|
||||||
// defer log.Trace(o, "")("f=%+v, err=%v", f, &err)
|
// defer log.Trace(o, "")("f=%+v, err=%v", f, &err)
|
||||||
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 nil, fs.ErrorObjectNotFound
|
return nil, fs.ErrorObjectNotFound
|
||||||
@@ -241,14 +241,17 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.Read
|
|||||||
req.Header.Set(header, value)
|
req.Header.Set(header, value)
|
||||||
}
|
}
|
||||||
// fs.Debugf(o, "opening file: id=%d", o.file.ID)
|
// fs.Debugf(o, "opening file: id=%d", o.file.ID)
|
||||||
resp, err = http.DefaultClient.Do(req)
|
resp, err = o.fs.httpClient.Do(req)
|
||||||
return shouldRetry(err)
|
return shouldRetry(err)
|
||||||
})
|
})
|
||||||
if perr, ok := err.(*putio.ErrorResponse); ok && perr.Response.StatusCode >= 400 && perr.Response.StatusCode <= 499 {
|
if perr, ok := err.(*putio.ErrorResponse); ok && perr.Response.StatusCode >= 400 && perr.Response.StatusCode <= 499 {
|
||||||
_ = resp.Body.Close()
|
_ = resp.Body.Close()
|
||||||
return nil, fserrors.NoRetryError(err)
|
return nil, fserrors.NoRetryError(err)
|
||||||
}
|
}
|
||||||
return resp.Body, err
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return resp.Body, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update the already existing object
|
// Update the already existing object
|
||||||
|
|||||||
@@ -60,7 +60,10 @@ func init() {
|
|||||||
Description: "Put.io",
|
Description: "Put.io",
|
||||||
NewFs: NewFs,
|
NewFs: NewFs,
|
||||||
Config: func(name string, m configmap.Mapper) {
|
Config: func(name string, m configmap.Mapper) {
|
||||||
err := oauthutil.ConfigNoOffline("putio", name, m, putioConfig)
|
opt := oauthutil.Options{
|
||||||
|
NoOffline: true,
|
||||||
|
}
|
||||||
|
err := oauthutil.Config("putio", name, m, putioConfig, &opt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Failed to configure token: %v", err)
|
log.Fatalf("Failed to configure token: %v", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
// Package qingstor provides an interface to QingStor object storage
|
// Package qingstor provides an interface to QingStor object storage
|
||||||
// Home: https://www.qingcloud.com/
|
// Home: https://www.qingcloud.com/
|
||||||
|
|
||||||
// +build !plan9
|
// +build !plan9,!js
|
||||||
|
|
||||||
package qingstor
|
package qingstor
|
||||||
|
|
||||||
@@ -56,7 +56,7 @@ func init() {
|
|||||||
Help: "QingStor Secret Access Key (password)\nLeave blank for anonymous access or runtime credentials.",
|
Help: "QingStor Secret Access Key (password)\nLeave blank for anonymous access or runtime credentials.",
|
||||||
}, {
|
}, {
|
||||||
Name: "endpoint",
|
Name: "endpoint",
|
||||||
Help: "Enter a endpoint URL to connection QingStor API.\nLeave blank will use the default value \"https://qingstor.com:443\"",
|
Help: "Enter an endpoint URL to connection QingStor API.\nLeave blank will use the default value \"https://qingstor.com:443\"",
|
||||||
}, {
|
}, {
|
||||||
Name: "zone",
|
Name: "zone",
|
||||||
Help: "Zone to connect to.\nDefault is \"pek3a\".",
|
Help: "Zone to connect to.\nDefault is \"pek3a\".",
|
||||||
@@ -203,10 +203,10 @@ func (o *Object) split() (bucket, bucketPath string) {
|
|||||||
return o.fs.split(o.remote)
|
return o.fs.split(o.remote)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Split an URL into three parts: protocol host and port
|
// Split a URL into three parts: protocol host and port
|
||||||
func qsParseEndpoint(endpoint string) (protocol, host, port string, err error) {
|
func qsParseEndpoint(endpoint string) (protocol, host, port string, err error) {
|
||||||
/*
|
/*
|
||||||
Pattern to match a endpoint,
|
Pattern to match an endpoint,
|
||||||
eg: "http(s)://qingstor.com:443" --> "http(s)", "qingstor.com", 443
|
eg: "http(s)://qingstor.com:443" --> "http(s)", "qingstor.com", 443
|
||||||
"http(s)//qingstor.com" --> "http(s)", "qingstor.com", ""
|
"http(s)//qingstor.com" --> "http(s)", "qingstor.com", ""
|
||||||
"qingstor.com" --> "", "qingstor.com", ""
|
"qingstor.com" --> "", "qingstor.com", ""
|
||||||
@@ -356,6 +356,7 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
WriteMimeType: true,
|
WriteMimeType: true,
|
||||||
BucketBased: true,
|
BucketBased: true,
|
||||||
BucketBasedRootOK: true,
|
BucketBasedRootOK: true,
|
||||||
|
SlowModTime: true,
|
||||||
}).Fill(f)
|
}).Fill(f)
|
||||||
|
|
||||||
if f.rootBucket != "" && f.rootDirectory != "" {
|
if f.rootBucket != "" && f.rootDirectory != "" {
|
||||||
@@ -864,6 +865,76 @@ func (f *Fs) Rmdir(ctx context.Context, dir string) error {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// cleanUpBucket removes all pending multipart uploads for a given bucket
|
||||||
|
func (f *Fs) cleanUpBucket(ctx context.Context, bucket string) (err error) {
|
||||||
|
fs.Infof(f, "cleaning bucket %q of pending multipart uploads older than 24 hours", bucket)
|
||||||
|
bucketInit, err := f.svc.Bucket(bucket, f.zone)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
maxLimit := int(listLimitSize)
|
||||||
|
var marker *string
|
||||||
|
for {
|
||||||
|
req := qs.ListMultipartUploadsInput{
|
||||||
|
Limit: &maxLimit,
|
||||||
|
KeyMarker: marker,
|
||||||
|
}
|
||||||
|
var resp *qs.ListMultipartUploadsOutput
|
||||||
|
resp, err = bucketInit.ListMultipartUploads(&req)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "clean up bucket list multipart uploads")
|
||||||
|
}
|
||||||
|
for _, upload := range resp.Uploads {
|
||||||
|
if upload.Created != nil && upload.Key != nil && upload.UploadID != nil {
|
||||||
|
age := time.Since(*upload.Created)
|
||||||
|
if age > 24*time.Hour {
|
||||||
|
fs.Infof(f, "removing pending multipart upload for %q dated %v (%v ago)", *upload.Key, upload.Created, age)
|
||||||
|
req := qs.AbortMultipartUploadInput{
|
||||||
|
UploadID: upload.UploadID,
|
||||||
|
}
|
||||||
|
_, abortErr := bucketInit.AbortMultipartUpload(*upload.Key, &req)
|
||||||
|
if abortErr != nil {
|
||||||
|
err = errors.Wrapf(abortErr, "failed to remove multipart upload for %q", *upload.Key)
|
||||||
|
fs.Errorf(f, "%v", err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
fs.Debugf(f, "ignoring pending multipart upload for %q dated %v (%v ago)", *upload.Key, upload.Created, age)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if resp.HasMore != nil && !*resp.HasMore {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
// Use NextMarker if set, otherwise use last Key
|
||||||
|
if resp.NextKeyMarker == nil || *resp.NextKeyMarker == "" {
|
||||||
|
fs.Errorf(f, "Expecting NextKeyMarker but didn't find one")
|
||||||
|
break
|
||||||
|
} else {
|
||||||
|
marker = resp.NextKeyMarker
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// CleanUp removes all pending multipart uploads
|
||||||
|
func (f *Fs) CleanUp(ctx context.Context) (err error) {
|
||||||
|
if f.rootBucket != "" {
|
||||||
|
return f.cleanUpBucket(ctx, f.rootBucket)
|
||||||
|
}
|
||||||
|
entries, err := f.listBuckets(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, entry := range entries {
|
||||||
|
cleanErr := f.cleanUpBucket(ctx, f.opt.Enc.FromStandardName(entry.Remote()))
|
||||||
|
if err != nil {
|
||||||
|
fs.Errorf(f, "Failed to cleanup bucket: %q", cleanErr)
|
||||||
|
err = cleanErr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
// readMetaData gets the metadata if it hasn't already been fetched
|
// readMetaData gets the metadata if it hasn't already been fetched
|
||||||
//
|
//
|
||||||
// it also sets the info
|
// it also sets the info
|
||||||
@@ -1090,9 +1161,10 @@ func (o *Object) MimeType(ctx context.Context) string {
|
|||||||
|
|
||||||
// Check the interfaces are satisfied
|
// Check the interfaces are satisfied
|
||||||
var (
|
var (
|
||||||
_ fs.Fs = &Fs{}
|
_ fs.Fs = &Fs{}
|
||||||
_ fs.Copier = &Fs{}
|
_ fs.CleanUpper = &Fs{}
|
||||||
_ fs.Object = &Object{}
|
_ fs.Copier = &Fs{}
|
||||||
_ fs.ListRer = &Fs{}
|
_ fs.Object = &Object{}
|
||||||
_ fs.MimeTyper = &Object{}
|
_ fs.ListRer = &Fs{}
|
||||||
|
_ fs.MimeTyper = &Object{}
|
||||||
)
|
)
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
// Test QingStor filesystem interface
|
// Test QingStor filesystem interface
|
||||||
|
|
||||||
// +build !plan9
|
// +build !plan9,!js
|
||||||
|
|
||||||
package qingstor
|
package qingstor
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// Build for unsupported platforms to stop go complaining
|
// Build 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 qingstor
|
package qingstor
|
||||||
+19
-14
@@ -1,6 +1,6 @@
|
|||||||
// Upload object to QingStor
|
// Upload object to QingStor
|
||||||
|
|
||||||
// +build !plan9
|
// +build !plan9,!js
|
||||||
|
|
||||||
package qingstor
|
package qingstor
|
||||||
|
|
||||||
@@ -15,6 +15,7 @@ import (
|
|||||||
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"github.com/rclone/rclone/fs"
|
"github.com/rclone/rclone/fs"
|
||||||
|
"github.com/rclone/rclone/lib/atexit"
|
||||||
qs "github.com/yunify/qingstor-sdk-go/v3/service"
|
qs "github.com/yunify/qingstor-sdk-go/v3/service"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -22,7 +23,7 @@ const (
|
|||||||
// maxSinglePartSize = 1024 * 1024 * 1024 * 5 // The maximum allowed size when uploading a single object to QingStor
|
// maxSinglePartSize = 1024 * 1024 * 1024 * 5 // The maximum allowed size when uploading a single object to QingStor
|
||||||
// maxMultiPartSize = 1024 * 1024 * 1024 * 1 // The maximum allowed part size when uploading a part to QingStor
|
// maxMultiPartSize = 1024 * 1024 * 1024 * 1 // The maximum allowed part size when uploading a part to QingStor
|
||||||
minMultiPartSize = 1024 * 1024 * 4 // The minimum allowed part size when uploading a part to QingStor
|
minMultiPartSize = 1024 * 1024 * 4 // The minimum allowed part size when uploading a part to QingStor
|
||||||
maxMultiParts = 10000 // The maximum allowed number of parts in an multi-part upload
|
maxMultiParts = 10000 // The maximum allowed number of parts in a multi-part upload
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -168,7 +169,7 @@ func (u *uploader) singlePartUpload(buf io.Reader, size int64) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Upload upload a object into QingStor
|
// Upload upload an object into QingStor
|
||||||
func (u *uploader) upload() error {
|
func (u *uploader) upload() error {
|
||||||
u.init()
|
u.init()
|
||||||
|
|
||||||
@@ -255,7 +256,7 @@ func (mu *multiUploader) readChunk(ch chan chunk) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// initiate init an Multiple Object and obtain UploadID
|
// initiate init a Multiple Object and obtain UploadID
|
||||||
func (mu *multiUploader) initiate() error {
|
func (mu *multiUploader) initiate() error {
|
||||||
bucketInit, _ := mu.bucketInit()
|
bucketInit, _ := mu.bucketInit()
|
||||||
req := qs.InitiateMultipartUploadInput{
|
req := qs.InitiateMultipartUploadInput{
|
||||||
@@ -297,7 +298,7 @@ func (mu *multiUploader) send(c chunk) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// complete complete an multipart upload
|
// complete complete a multipart upload
|
||||||
func (mu *multiUploader) complete() error {
|
func (mu *multiUploader) complete() error {
|
||||||
var err error
|
var err error
|
||||||
if err = mu.getErr(); err != nil {
|
if err = mu.getErr(); err != nil {
|
||||||
@@ -324,7 +325,7 @@ func (mu *multiUploader) complete() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// abort abort an multipart upload
|
// abort abort a multipart upload
|
||||||
func (mu *multiUploader) abort() error {
|
func (mu *multiUploader) abort() error {
|
||||||
var err error
|
var err error
|
||||||
bucketInit, _ := mu.bucketInit()
|
bucketInit, _ := mu.bucketInit()
|
||||||
@@ -341,13 +342,21 @@ func (mu *multiUploader) abort() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// multiPartUpload upload a multiple object into QingStor
|
// multiPartUpload upload a multiple object into QingStor
|
||||||
func (mu *multiUploader) multiPartUpload(firstBuf io.ReadSeeker) error {
|
func (mu *multiUploader) multiPartUpload(firstBuf io.ReadSeeker) (err error) {
|
||||||
var err error
|
// Initiate a multi-part upload
|
||||||
//Initiate an multi-part upload
|
|
||||||
if err = mu.initiate(); err != nil {
|
if err = mu.initiate(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Cancel the session if something went wrong
|
||||||
|
defer atexit.OnError(&err, func() {
|
||||||
|
fs.Debugf(mu, "Cancelling multipart upload: %v", err)
|
||||||
|
cancelErr := mu.abort()
|
||||||
|
if cancelErr != nil {
|
||||||
|
fs.Logf(mu, "Failed to cancel multipart upload: %v", cancelErr)
|
||||||
|
}
|
||||||
|
})()
|
||||||
|
|
||||||
ch := make(chan chunk, mu.cfg.concurrency)
|
ch := make(chan chunk, mu.cfg.concurrency)
|
||||||
for i := 0; i < mu.cfg.concurrency; i++ {
|
for i := 0; i < mu.cfg.concurrency; i++ {
|
||||||
mu.wg.Add(1)
|
mu.wg.Add(1)
|
||||||
@@ -400,9 +409,5 @@ func (mu *multiUploader) multiPartUpload(firstBuf io.ReadSeeker) error {
|
|||||||
close(ch)
|
close(ch)
|
||||||
mu.wg.Wait()
|
mu.wg.Wait()
|
||||||
// Complete Multipart Upload
|
// Complete Multipart Upload
|
||||||
err = mu.complete()
|
return mu.complete()
|
||||||
if mu.getErr() != nil || err != nil {
|
|
||||||
_ = mu.abort()
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
}
|
||||||
+802
-191
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,153 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
// Some api objects are duplicated with only small differences,
|
||||||
|
// it's because the returned JSON objects are very inconsistent between api calls
|
||||||
|
|
||||||
|
// AuthenticationRequest contains user credentials
|
||||||
|
type AuthenticationRequest struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// AuthenticationResult is returned by a call to the authentication api
|
||||||
|
type AuthenticationResult struct {
|
||||||
|
Token string `json:"token"`
|
||||||
|
Errors []string `json:"non_field_errors"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// AccountInfo contains simple user properties
|
||||||
|
type AccountInfo struct {
|
||||||
|
Usage int64 `json:"usage"`
|
||||||
|
Total int64 `json:"total"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ServerInfo contains server information
|
||||||
|
type ServerInfo struct {
|
||||||
|
Version string `json:"version"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultLibrary when none specified
|
||||||
|
type DefaultLibrary struct {
|
||||||
|
ID string `json:"repo_id"`
|
||||||
|
Exists bool `json:"exists"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateLibraryRequest contains the information needed to create a library
|
||||||
|
type CreateLibraryRequest struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Description string `json:"desc"`
|
||||||
|
Password string `json:"passwd"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Library properties. Please note not all properties are going to be useful for rclone
|
||||||
|
type Library struct {
|
||||||
|
Encrypted bool `json:"encrypted"`
|
||||||
|
Owner string `json:"owner"`
|
||||||
|
ID string `json:"id"`
|
||||||
|
Size int `json:"size"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Modified int64 `json:"mtime"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateLibrary properties. Seafile is not consistent and returns different types for different API calls
|
||||||
|
type CreateLibrary struct {
|
||||||
|
ID string `json:"repo_id"`
|
||||||
|
Name string `json:"repo_name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// FileType is either "dir" or "file"
|
||||||
|
type FileType string
|
||||||
|
|
||||||
|
// File types
|
||||||
|
var (
|
||||||
|
FileTypeDir FileType = "dir"
|
||||||
|
FileTypeFile FileType = "file"
|
||||||
|
)
|
||||||
|
|
||||||
|
// FileDetail contains file properties (for older api v2.0)
|
||||||
|
type FileDetail struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Type FileType `json:"type"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Size int64 `json:"size"`
|
||||||
|
Parent string `json:"parent_dir"`
|
||||||
|
Modified string `json:"last_modified"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DirEntries contains a list of DirEntry
|
||||||
|
type DirEntries struct {
|
||||||
|
Entries []DirEntry `json:"dirent_list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DirEntry contains a directory entry
|
||||||
|
type DirEntry struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Type FileType `json:"type"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Size int64 `json:"size"`
|
||||||
|
Path string `json:"parent_dir"`
|
||||||
|
Modified int64 `json:"mtime"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Operation is move, copy or rename
|
||||||
|
type Operation string
|
||||||
|
|
||||||
|
// Operations
|
||||||
|
var (
|
||||||
|
CopyFileOperation Operation = "copy"
|
||||||
|
MoveFileOperation Operation = "move"
|
||||||
|
RenameFileOperation Operation = "rename"
|
||||||
|
)
|
||||||
|
|
||||||
|
// FileOperationRequest is sent to the api to copy, move or rename a file
|
||||||
|
type FileOperationRequest struct {
|
||||||
|
Operation Operation `json:"operation"`
|
||||||
|
DestinationLibraryID string `json:"dst_repo"` // For copy/move operation
|
||||||
|
DestinationPath string `json:"dst_dir"` // For copy/move operation
|
||||||
|
NewName string `json:"newname"` // Only to be used by the rename operation
|
||||||
|
}
|
||||||
|
|
||||||
|
// FileInfo is returned by a server file copy/move/rename (new api v2.1)
|
||||||
|
type FileInfo struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
LibraryID string `json:"repo_id"`
|
||||||
|
Path string `json:"parent_dir"`
|
||||||
|
Name string `json:"obj_name"`
|
||||||
|
ID string `json:"obj_id"`
|
||||||
|
Size int64 `json:"size"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateDirRequest only contain an operation field
|
||||||
|
type CreateDirRequest struct {
|
||||||
|
Operation string `json:"operation"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DirectoryDetail contains the directory details specific to the getDirectoryDetails call
|
||||||
|
type DirectoryDetail struct {
|
||||||
|
ID string `json:"repo_id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Path string `json:"path"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShareLinkRequest contains the information needed to create or list shared links
|
||||||
|
type ShareLinkRequest struct {
|
||||||
|
LibraryID string `json:"repo_id"`
|
||||||
|
Path string `json:"path"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// SharedLink contains the information returned by a call to shared link creation
|
||||||
|
type SharedLink struct {
|
||||||
|
Link string `json:"link"`
|
||||||
|
IsExpired bool `json:"is_expired"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BatchSourceDestRequest contains JSON parameters for sending a batch copy or move operation
|
||||||
|
type BatchSourceDestRequest struct {
|
||||||
|
SrcLibraryID string `json:"src_repo_id"`
|
||||||
|
SrcParentDir string `json:"src_parent_dir"`
|
||||||
|
SrcItems []string `json:"src_dirents"`
|
||||||
|
DstLibraryID string `json:"dst_repo_id"`
|
||||||
|
DstParentDir string `json:"dst_parent_dir"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
package seafile
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/rclone/rclone/fs"
|
||||||
|
"github.com/rclone/rclone/fs/hash"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Object describes a seafile object (also commonly called a file)
|
||||||
|
type Object struct {
|
||||||
|
fs *Fs // what this object is part of
|
||||||
|
id string // internal ID of object
|
||||||
|
remote string // The remote path (full path containing library name if target at root)
|
||||||
|
pathInLibrary string // Path of the object without the library name
|
||||||
|
size int64 // size of the object
|
||||||
|
modTime time.Time // modification time of the object
|
||||||
|
libraryID string // Needed to download the file
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Interface fs.DirEntry ====================
|
||||||
|
|
||||||
|
// Return a string version
|
||||||
|
func (o *Object) String() string {
|
||||||
|
if o == nil {
|
||||||
|
return "<nil>"
|
||||||
|
}
|
||||||
|
return o.remote
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remote returns the remote string
|
||||||
|
func (o *Object) Remote() string {
|
||||||
|
return o.remote
|
||||||
|
}
|
||||||
|
|
||||||
|
// ModTime returns last modified time
|
||||||
|
func (o *Object) ModTime(context.Context) time.Time {
|
||||||
|
return o.modTime
|
||||||
|
}
|
||||||
|
|
||||||
|
// Size returns the size of an object in bytes
|
||||||
|
func (o *Object) Size() int64 {
|
||||||
|
return o.size
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Interface fs.ObjectInfo ====================
|
||||||
|
|
||||||
|
// Fs returns the parent Fs
|
||||||
|
func (o *Object) Fs() fs.Info {
|
||||||
|
return o.fs
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hash returns the selected checksum of the file
|
||||||
|
// If no checksum is available it returns ""
|
||||||
|
func (o *Object) Hash(ctx context.Context, ty hash.Type) (string, error) {
|
||||||
|
return "", hash.ErrUnsupported
|
||||||
|
}
|
||||||
|
|
||||||
|
// Storable says whether this object can be stored
|
||||||
|
func (o *Object) Storable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Interface fs.Object ====================
|
||||||
|
|
||||||
|
// SetModTime sets the metadata on the object to set the modification date
|
||||||
|
func (o *Object) SetModTime(ctx context.Context, t time.Time) error {
|
||||||
|
return fs.ErrorCantSetModTime
|
||||||
|
}
|
||||||
|
|
||||||
|
// Open opens the file for read. Call Close() on the returned io.ReadCloser
|
||||||
|
func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadCloser, error) {
|
||||||
|
downloadLink, err := o.fs.getDownloadLink(ctx, o.libraryID, o.pathInLibrary)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
reader, err := o.fs.download(ctx, downloadLink, o.Size(), options...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return reader, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update in to the object with the modTime given of the given size
|
||||||
|
//
|
||||||
|
// 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
|
||||||
|
// 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 {
|
||||||
|
// The upload sometimes return a temporary 500 error
|
||||||
|
// We cannot use the pacer to retry uploading the file as the upload link is single use only
|
||||||
|
for retry := 0; retry <= 3; retry++ {
|
||||||
|
uploadLink, err := o.fs.getUploadLink(ctx, o.libraryID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
uploaded, err := o.fs.upload(ctx, in, uploadLink, o.pathInLibrary)
|
||||||
|
if err == ErrorInternalDuringUpload {
|
||||||
|
// This is a temporary error, try again with a new upload link
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
// Set the properties from the upload back to the object
|
||||||
|
o.size = uploaded.Size
|
||||||
|
o.id = uploaded.ID
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return ErrorInternalDuringUpload
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove this object
|
||||||
|
func (o *Object) Remove(ctx context.Context) error {
|
||||||
|
return o.fs.deleteFile(ctx, o.libraryID, o.pathInLibrary)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Optional Interface fs.IDer ====================
|
||||||
|
|
||||||
|
// ID returns the ID of the Object if known, or "" if not
|
||||||
|
func (o *Object) ID() string {
|
||||||
|
return o.id
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package seafile
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/url"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/rclone/rclone/fs"
|
||||||
|
"github.com/rclone/rclone/lib/pacer"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
minSleep = 100 * time.Millisecond
|
||||||
|
maxSleep = 10 * time.Second
|
||||||
|
decayConstant = 2 // bigger for slower decay, exponential
|
||||||
|
)
|
||||||
|
|
||||||
|
// Use only one pacer per server URL
|
||||||
|
var (
|
||||||
|
pacers map[string]*fs.Pacer
|
||||||
|
pacerMutex sync.Mutex
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
pacers = make(map[string]*fs.Pacer, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// getPacer returns the unique pacer for that remote URL
|
||||||
|
func getPacer(remote string) *fs.Pacer {
|
||||||
|
pacerMutex.Lock()
|
||||||
|
defer pacerMutex.Unlock()
|
||||||
|
|
||||||
|
remote = parseRemote(remote)
|
||||||
|
if existing, found := pacers[remote]; found {
|
||||||
|
return existing
|
||||||
|
}
|
||||||
|
|
||||||
|
pacers[remote] = fs.NewPacer(
|
||||||
|
pacer.NewDefault(
|
||||||
|
pacer.MinSleep(minSleep),
|
||||||
|
pacer.MaxSleep(maxSleep),
|
||||||
|
pacer.DecayConstant(decayConstant),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
return pacers[remote]
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseRemote formats a remote url into "hostname:port"
|
||||||
|
func parseRemote(remote string) string {
|
||||||
|
remoteURL, err := url.Parse(remote)
|
||||||
|
if err != nil {
|
||||||
|
// Return a default value in the very unlikely event we're not going to parse remote
|
||||||
|
fs.Infof(nil, "Cannot parse remote %s", remote)
|
||||||
|
return "default"
|
||||||
|
}
|
||||||
|
host := remoteURL.Hostname()
|
||||||
|
port := remoteURL.Port()
|
||||||
|
if port == "" {
|
||||||
|
if remoteURL.Scheme == "https" {
|
||||||
|
port = "443"
|
||||||
|
} else {
|
||||||
|
port = "80"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%s:%s", host, port)
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,123 @@
|
|||||||
|
package seafile
|
||||||
|
|
||||||
|
import (
|
||||||
|
"path"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
type pathData struct {
|
||||||
|
configLibrary string // Library specified in the config
|
||||||
|
configRoot string // Root directory specified in the config
|
||||||
|
argumentPath string // Path given as an argument in the command line
|
||||||
|
expectedLibrary string
|
||||||
|
expectedPath string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test the method to split a library name and a path
|
||||||
|
// from a mix of configuration data and path command line argument
|
||||||
|
func TestSplitPath(t *testing.T) {
|
||||||
|
testData := []pathData{
|
||||||
|
pathData{
|
||||||
|
configLibrary: "",
|
||||||
|
configRoot: "",
|
||||||
|
argumentPath: "",
|
||||||
|
expectedLibrary: "",
|
||||||
|
expectedPath: "",
|
||||||
|
},
|
||||||
|
pathData{
|
||||||
|
configLibrary: "",
|
||||||
|
configRoot: "",
|
||||||
|
argumentPath: "Library",
|
||||||
|
expectedLibrary: "Library",
|
||||||
|
expectedPath: "",
|
||||||
|
},
|
||||||
|
pathData{
|
||||||
|
configLibrary: "",
|
||||||
|
configRoot: "",
|
||||||
|
argumentPath: path.Join("Library", "path", "to", "file"),
|
||||||
|
expectedLibrary: "Library",
|
||||||
|
expectedPath: path.Join("path", "to", "file"),
|
||||||
|
},
|
||||||
|
pathData{
|
||||||
|
configLibrary: "Library",
|
||||||
|
configRoot: "",
|
||||||
|
argumentPath: "",
|
||||||
|
expectedLibrary: "Library",
|
||||||
|
expectedPath: "",
|
||||||
|
},
|
||||||
|
pathData{
|
||||||
|
configLibrary: "Library",
|
||||||
|
configRoot: "",
|
||||||
|
argumentPath: "path",
|
||||||
|
expectedLibrary: "Library",
|
||||||
|
expectedPath: "path",
|
||||||
|
},
|
||||||
|
pathData{
|
||||||
|
configLibrary: "Library",
|
||||||
|
configRoot: "",
|
||||||
|
argumentPath: path.Join("path", "to", "file"),
|
||||||
|
expectedLibrary: "Library",
|
||||||
|
expectedPath: path.Join("path", "to", "file"),
|
||||||
|
},
|
||||||
|
pathData{
|
||||||
|
configLibrary: "Library",
|
||||||
|
configRoot: "root",
|
||||||
|
argumentPath: "",
|
||||||
|
expectedLibrary: "Library",
|
||||||
|
expectedPath: "root",
|
||||||
|
},
|
||||||
|
pathData{
|
||||||
|
configLibrary: "Library",
|
||||||
|
configRoot: path.Join("root", "path"),
|
||||||
|
argumentPath: "",
|
||||||
|
expectedLibrary: "Library",
|
||||||
|
expectedPath: path.Join("root", "path"),
|
||||||
|
},
|
||||||
|
pathData{
|
||||||
|
configLibrary: "Library",
|
||||||
|
configRoot: "root",
|
||||||
|
argumentPath: "path",
|
||||||
|
expectedLibrary: "Library",
|
||||||
|
expectedPath: path.Join("root", "path"),
|
||||||
|
},
|
||||||
|
pathData{
|
||||||
|
configLibrary: "Library",
|
||||||
|
configRoot: "root",
|
||||||
|
argumentPath: path.Join("path", "to", "file"),
|
||||||
|
expectedLibrary: "Library",
|
||||||
|
expectedPath: path.Join("root", "path", "to", "file"),
|
||||||
|
},
|
||||||
|
pathData{
|
||||||
|
configLibrary: "Library",
|
||||||
|
configRoot: path.Join("root", "path"),
|
||||||
|
argumentPath: path.Join("subpath", "to", "file"),
|
||||||
|
expectedLibrary: "Library",
|
||||||
|
expectedPath: path.Join("root", "path", "subpath", "to", "file"),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, test := range testData {
|
||||||
|
fs := &Fs{
|
||||||
|
libraryName: test.configLibrary,
|
||||||
|
rootDirectory: test.configRoot,
|
||||||
|
}
|
||||||
|
libraryName, path := fs.splitPath(test.argumentPath)
|
||||||
|
|
||||||
|
assert.Equal(t, test.expectedLibrary, libraryName)
|
||||||
|
assert.Equal(t, test.expectedPath, path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSplitPathIntoSlice(t *testing.T) {
|
||||||
|
testData := map[string][]string{
|
||||||
|
"1": {"1"},
|
||||||
|
"/1": {"1"},
|
||||||
|
"/1/": {"1"},
|
||||||
|
"1/2/3": {"1", "2", "3"},
|
||||||
|
}
|
||||||
|
for input, expected := range testData {
|
||||||
|
output := splitPath(input)
|
||||||
|
assert.Equal(t, expected, output)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
// Test Seafile filesystem interface
|
||||||
|
package seafile_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/rclone/rclone/backend/seafile"
|
||||||
|
"github.com/rclone/rclone/fstest/fstests"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestIntegration runs integration tests against the remote
|
||||||
|
func TestIntegration(t *testing.T) {
|
||||||
|
fstests.Run(t, &fstests.Opt{
|
||||||
|
RemoteName: "TestSeafile:",
|
||||||
|
NilObject: (*seafile.Object)(nil),
|
||||||
|
})
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
+102
-32
@@ -69,9 +69,12 @@ func init() {
|
|||||||
Name: "pass",
|
Name: "pass",
|
||||||
Help: "SSH password, leave blank to use ssh-agent.",
|
Help: "SSH password, leave blank to use ssh-agent.",
|
||||||
IsPassword: true,
|
IsPassword: true,
|
||||||
|
}, {
|
||||||
|
Name: "key_pem",
|
||||||
|
Help: "Raw PEM-encoded private key, If specified, will override key_file parameter.",
|
||||||
}, {
|
}, {
|
||||||
Name: "key_file",
|
Name: "key_file",
|
||||||
Help: "Path to PEM-encoded private key file, leave blank or set key-use-agent to use ssh-agent.",
|
Help: "Path to PEM-encoded private key file, leave blank or set key-use-agent to use ssh-agent." + env.ShellExpandHelp,
|
||||||
}, {
|
}, {
|
||||||
Name: "key_file_pass",
|
Name: "key_file_pass",
|
||||||
Help: `The passphrase to decrypt the PEM-encoded private key file.
|
Help: `The passphrase to decrypt the PEM-encoded private key file.
|
||||||
@@ -91,7 +94,7 @@ when the ssh-agent contains many keys.`,
|
|||||||
Name: "use_insecure_cipher",
|
Name: "use_insecure_cipher",
|
||||||
Help: `Enable the use of insecure ciphers and key exchange methods.
|
Help: `Enable the use of insecure ciphers and key exchange methods.
|
||||||
|
|
||||||
This enables the use of the the following insecure ciphers and key exchange methods:
|
This enables the use of the following insecure ciphers and key exchange methods:
|
||||||
|
|
||||||
- aes128-cbc
|
- aes128-cbc
|
||||||
- aes192-cbc
|
- aes192-cbc
|
||||||
@@ -161,6 +164,18 @@ Home directory can be found in a shared folder called "home"
|
|||||||
Default: false,
|
Default: false,
|
||||||
Help: "Set to skip any symlinks and any other non regular files.",
|
Help: "Set to skip any symlinks and any other non regular files.",
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: "subsystem",
|
||||||
|
Default: "sftp",
|
||||||
|
Help: "Specifies the SSH2 subsystem on the remote host.",
|
||||||
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: "server_command",
|
||||||
|
Default: "",
|
||||||
|
Help: `Specifies the path or command to run a sftp server on the remote host.
|
||||||
|
|
||||||
|
The subsystem option is ignored when server_command is defined.`,
|
||||||
|
Advanced: true,
|
||||||
}},
|
}},
|
||||||
}
|
}
|
||||||
fs.Register(fsi)
|
fs.Register(fsi)
|
||||||
@@ -172,6 +187,7 @@ type Options struct {
|
|||||||
User string `config:"user"`
|
User string `config:"user"`
|
||||||
Port string `config:"port"`
|
Port string `config:"port"`
|
||||||
Pass string `config:"pass"`
|
Pass string `config:"pass"`
|
||||||
|
KeyPem string `config:"key_pem"`
|
||||||
KeyFile string `config:"key_file"`
|
KeyFile string `config:"key_file"`
|
||||||
KeyFilePass string `config:"key_file_pass"`
|
KeyFilePass string `config:"key_file_pass"`
|
||||||
KeyUseAgent bool `config:"key_use_agent"`
|
KeyUseAgent bool `config:"key_use_agent"`
|
||||||
@@ -183,12 +199,15 @@ type Options struct {
|
|||||||
Md5sumCommand string `config:"md5sum_command"`
|
Md5sumCommand string `config:"md5sum_command"`
|
||||||
Sha1sumCommand string `config:"sha1sum_command"`
|
Sha1sumCommand string `config:"sha1sum_command"`
|
||||||
SkipLinks bool `config:"skip_links"`
|
SkipLinks bool `config:"skip_links"`
|
||||||
|
Subsystem string `config:"subsystem"`
|
||||||
|
ServerCommand string `config:"server_command"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fs stores the interface to the remote SFTP files
|
// Fs stores the interface to the remote SFTP files
|
||||||
type Fs struct {
|
type Fs struct {
|
||||||
name string
|
name string
|
||||||
root string
|
root string
|
||||||
|
absRoot string
|
||||||
opt Options // parsed options
|
opt Options // parsed options
|
||||||
m configmap.Mapper // config
|
m configmap.Mapper // config
|
||||||
features *fs.Features // optional features
|
features *fs.Features // optional features
|
||||||
@@ -285,7 +304,7 @@ func (f *Fs) sftpConnection() (c *conn, err error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "couldn't connect SSH")
|
return nil, errors.Wrap(err, "couldn't connect SSH")
|
||||||
}
|
}
|
||||||
c.sftpClient, err = sftp.NewClient(c.sshClient)
|
c.sftpClient, err = f.newSftpClient(c.sshClient)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = c.sshClient.Close()
|
_ = c.sshClient.Close()
|
||||||
return nil, errors.Wrap(err, "couldn't initialise SFTP")
|
return nil, errors.Wrap(err, "couldn't initialise SFTP")
|
||||||
@@ -294,6 +313,35 @@ func (f *Fs) sftpConnection() (c *conn, err error) {
|
|||||||
return c, nil
|
return c, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Creates a new SFTP client on conn, using the specified subsystem
|
||||||
|
// or sftp server, and zero or more option functions
|
||||||
|
func (f *Fs) newSftpClient(conn *ssh.Client, opts ...sftp.ClientOption) (*sftp.Client, error) {
|
||||||
|
s, err := conn.NewSession()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
pw, err := s.StdinPipe()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
pr, err := s.StdoutPipe()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if f.opt.ServerCommand != "" {
|
||||||
|
if err := s.Start(f.opt.ServerCommand); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if err := s.RequestSubsystem(f.opt.Subsystem); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return sftp.NewClientPipe(pr, pw, opts...)
|
||||||
|
}
|
||||||
|
|
||||||
// Get an SFTP connection from the pool, or open a new one
|
// Get an SFTP connection from the pool, or open a new one
|
||||||
func (f *Fs) getSftpConnection() (c *conn, err error) {
|
func (f *Fs) getSftpConnection() (c *conn, err error) {
|
||||||
f.poolMu.Lock()
|
f.poolMu.Lock()
|
||||||
@@ -390,8 +438,9 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
keyFile := env.ShellExpand(opt.KeyFile)
|
keyFile := env.ShellExpand(opt.KeyFile)
|
||||||
// Add ssh agent-auth if no password or file specified
|
//keyPem := env.ShellExpand(opt.KeyPem)
|
||||||
if (opt.Pass == "" && keyFile == "" && !opt.AskPassword) || opt.KeyUseAgent {
|
// Add ssh agent-auth if no password or file or key PEM specified
|
||||||
|
if (opt.Pass == "" && keyFile == "" && !opt.AskPassword && opt.KeyPem == "") || opt.KeyUseAgent {
|
||||||
sshAgentClient, _, err := sshagent.New()
|
sshAgentClient, _, err := sshagent.New()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "couldn't connect to ssh-agent")
|
return nil, errors.Wrap(err, "couldn't connect to ssh-agent")
|
||||||
@@ -427,10 +476,20 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Load key file if specified
|
// Load key file if specified
|
||||||
if keyFile != "" {
|
if keyFile != "" || opt.KeyPem != "" {
|
||||||
key, err := ioutil.ReadFile(keyFile)
|
var key []byte
|
||||||
if err != nil {
|
if opt.KeyPem == "" {
|
||||||
return nil, errors.Wrap(err, "failed to read private key file")
|
key, err = ioutil.ReadFile(keyFile)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "failed to read private key file")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// wrap in quotes because the config is a coming as a literal without them.
|
||||||
|
opt.KeyPem, err = strconv.Unquote("\"" + opt.KeyPem + "\"")
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "pem key not formatted properly")
|
||||||
|
}
|
||||||
|
key = []byte(opt.KeyPem)
|
||||||
}
|
}
|
||||||
clearpass := ""
|
clearpass := ""
|
||||||
if opt.KeyFilePass != "" {
|
if opt.KeyFilePass != "" {
|
||||||
@@ -470,12 +529,13 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
return NewFsWithConnection(ctx, name, root, m, opt, sshConfig)
|
return NewFsWithConnection(ctx, name, root, m, opt, sshConfig)
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewFsWithConnection creates a new Fs object from the name and root and a ssh.ClientConfig. It connects to
|
// NewFsWithConnection creates a new Fs object from the name and root and an ssh.ClientConfig. It connects to
|
||||||
// the host specified in the ssh.ClientConfig
|
// the host specified in the ssh.ClientConfig
|
||||||
func NewFsWithConnection(ctx context.Context, name string, root string, m configmap.Mapper, opt *Options, sshConfig *ssh.ClientConfig) (fs.Fs, error) {
|
func NewFsWithConnection(ctx context.Context, name string, root string, m configmap.Mapper, opt *Options, sshConfig *ssh.ClientConfig) (fs.Fs, error) {
|
||||||
f := &Fs{
|
f := &Fs{
|
||||||
name: name,
|
name: name,
|
||||||
root: root,
|
root: root,
|
||||||
|
absRoot: root,
|
||||||
opt: *opt,
|
opt: *opt,
|
||||||
m: m,
|
m: m,
|
||||||
config: sshConfig,
|
config: sshConfig,
|
||||||
@@ -485,17 +545,27 @@ func NewFsWithConnection(ctx context.Context, name string, root string, m config
|
|||||||
}
|
}
|
||||||
f.features = (&fs.Features{
|
f.features = (&fs.Features{
|
||||||
CanHaveEmptyDirectories: true,
|
CanHaveEmptyDirectories: true,
|
||||||
|
SlowHash: true,
|
||||||
}).Fill(f)
|
}).Fill(f)
|
||||||
// Make a connection and pool it to return errors early
|
// Make a connection and pool it to return errors early
|
||||||
c, err := f.getSftpConnection()
|
c, err := f.getSftpConnection()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "NewFs")
|
return nil, errors.Wrap(err, "NewFs")
|
||||||
}
|
}
|
||||||
|
cwd, err := c.sftpClient.Getwd()
|
||||||
f.putSftpConnection(&c, nil)
|
f.putSftpConnection(&c, nil)
|
||||||
|
if err != nil {
|
||||||
|
fs.Debugf(f, "Failed to read current directory - using relative paths: %v", err)
|
||||||
|
} else if !path.IsAbs(f.root) {
|
||||||
|
f.absRoot = path.Join(cwd, f.root)
|
||||||
|
fs.Debugf(f, "Using absolute root directory %q", f.absRoot)
|
||||||
|
}
|
||||||
if root != "" {
|
if root != "" {
|
||||||
// Check to see if the root actually an existing file
|
// Check to see if the root actually an existing file
|
||||||
|
oldAbsRoot := f.absRoot
|
||||||
remote := path.Base(root)
|
remote := path.Base(root)
|
||||||
f.root = path.Dir(root)
|
f.root = path.Dir(root)
|
||||||
|
f.absRoot = path.Dir(f.absRoot)
|
||||||
if f.root == "." {
|
if f.root == "." {
|
||||||
f.root = ""
|
f.root = ""
|
||||||
}
|
}
|
||||||
@@ -504,6 +574,7 @@ func NewFsWithConnection(ctx context.Context, name string, root string, m config
|
|||||||
if err == fs.ErrorObjectNotFound || errors.Cause(err) == fs.ErrorNotAFile {
|
if err == fs.ErrorObjectNotFound || errors.Cause(err) == fs.ErrorNotAFile {
|
||||||
// File doesn't exist so return old f
|
// File doesn't exist so return old f
|
||||||
f.root = root
|
f.root = root
|
||||||
|
f.absRoot = oldAbsRoot
|
||||||
return f, nil
|
return f, nil
|
||||||
}
|
}
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -586,7 +657,7 @@ func (f *Fs) dirExists(dir string) (bool, 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) {
|
||||||
root := path.Join(f.root, dir)
|
root := path.Join(f.absRoot, dir)
|
||||||
ok, err := f.dirExists(root)
|
ok, err := f.dirExists(root)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "List failed")
|
return nil, errors.Wrap(err, "List failed")
|
||||||
@@ -667,7 +738,7 @@ func (f *Fs) PutStream(ctx context.Context, in io.Reader, src fs.ObjectInfo, opt
|
|||||||
// directories above that
|
// directories above that
|
||||||
func (f *Fs) mkParentDir(remote string) error {
|
func (f *Fs) mkParentDir(remote string) error {
|
||||||
parent := path.Dir(remote)
|
parent := path.Dir(remote)
|
||||||
return f.mkdir(path.Join(f.root, parent))
|
return f.mkdir(path.Join(f.absRoot, parent))
|
||||||
}
|
}
|
||||||
|
|
||||||
// mkdir makes the directory and parents using native paths
|
// mkdir makes the directory and parents using native paths
|
||||||
@@ -703,7 +774,7 @@ func (f *Fs) mkdir(dirPath string) error {
|
|||||||
|
|
||||||
// Mkdir makes the root directory of the Fs object
|
// Mkdir makes the root directory of the Fs object
|
||||||
func (f *Fs) Mkdir(ctx context.Context, dir string) error {
|
func (f *Fs) Mkdir(ctx context.Context, dir string) error {
|
||||||
root := path.Join(f.root, dir)
|
root := path.Join(f.absRoot, dir)
|
||||||
return f.mkdir(root)
|
return f.mkdir(root)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -719,7 +790,7 @@ func (f *Fs) Rmdir(ctx context.Context, dir string) error {
|
|||||||
return fs.ErrorDirectoryNotEmpty
|
return fs.ErrorDirectoryNotEmpty
|
||||||
}
|
}
|
||||||
// Remove the directory
|
// Remove the directory
|
||||||
root := path.Join(f.root, dir)
|
root := path.Join(f.absRoot, dir)
|
||||||
c, err := f.getSftpConnection()
|
c, err := f.getSftpConnection()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.Wrap(err, "Rmdir")
|
return errors.Wrap(err, "Rmdir")
|
||||||
@@ -746,7 +817,7 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
|||||||
}
|
}
|
||||||
err = c.sftpClient.Rename(
|
err = c.sftpClient.Rename(
|
||||||
srcObj.path(),
|
srcObj.path(),
|
||||||
path.Join(f.root, remote),
|
path.Join(f.absRoot, remote),
|
||||||
)
|
)
|
||||||
f.putSftpConnection(&c, err)
|
f.putSftpConnection(&c, err)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -773,8 +844,8 @@ 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)
|
srcPath := path.Join(srcFs.absRoot, srcRemote)
|
||||||
dstPath := path.Join(f.root, dstRemote)
|
dstPath := path.Join(f.absRoot, dstRemote)
|
||||||
|
|
||||||
// Check if destination exists
|
// Check if destination exists
|
||||||
ok, err := f.dirExists(dstPath)
|
ok, err := f.dirExists(dstPath)
|
||||||
@@ -1021,7 +1092,7 @@ func parseHash(bytes []byte) string {
|
|||||||
|
|
||||||
// Parses the byte array output from the SSH session
|
// Parses the byte array output from the SSH session
|
||||||
// returned by an invocation of df into
|
// returned by an invocation of df into
|
||||||
// the disk size, used space, and avaliable space on the disk, in that order.
|
// the disk size, used space, and available space on the disk, in that order.
|
||||||
// Only works when `df` has output info on only one disk
|
// Only works when `df` has output info on only one disk
|
||||||
func parseUsage(bytes []byte) (spaceTotal int64, spaceUsed int64, spaceAvail int64) {
|
func parseUsage(bytes []byte) (spaceTotal int64, spaceUsed int64, spaceAvail int64) {
|
||||||
spaceTotal, spaceUsed, spaceAvail = -1, -1, -1
|
spaceTotal, spaceUsed, spaceAvail = -1, -1, -1
|
||||||
@@ -1060,7 +1131,7 @@ func (o *Object) ModTime(ctx context.Context) time.Time {
|
|||||||
|
|
||||||
// path returns the native path of the object
|
// path returns the native path of the object
|
||||||
func (o *Object) path() string {
|
func (o *Object) path() string {
|
||||||
return path.Join(o.fs.root, o.remote)
|
return path.Join(o.fs.absRoot, o.remote)
|
||||||
}
|
}
|
||||||
|
|
||||||
// setMetadata updates the info in the object from the stat result passed in
|
// setMetadata updates the info in the object from the stat result passed in
|
||||||
@@ -1076,7 +1147,7 @@ func (f *Fs) stat(remote string) (info os.FileInfo, err error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "stat")
|
return nil, errors.Wrap(err, "stat")
|
||||||
}
|
}
|
||||||
absPath := path.Join(f.root, remote)
|
absPath := path.Join(f.absRoot, remote)
|
||||||
info, err = c.sftpClient.Stat(absPath)
|
info, err = c.sftpClient.Stat(absPath)
|
||||||
f.putSftpConnection(&c, err)
|
f.putSftpConnection(&c, err)
|
||||||
return info, err
|
return info, err
|
||||||
@@ -1102,19 +1173,18 @@ func (o *Object) stat() error {
|
|||||||
//
|
//
|
||||||
// it also updates the info field
|
// it also updates the info field
|
||||||
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.SetModTime {
|
if o.fs.opt.SetModTime {
|
||||||
return nil
|
c, err := o.fs.getSftpConnection()
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "SetModTime")
|
||||||
|
}
|
||||||
|
err = c.sftpClient.Chtimes(o.path(), modTime, modTime)
|
||||||
|
o.fs.putSftpConnection(&c, err)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "SetModTime failed")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
c, err := o.fs.getSftpConnection()
|
err := o.stat()
|
||||||
if err != nil {
|
|
||||||
return errors.Wrap(err, "SetModTime")
|
|
||||||
}
|
|
||||||
err = c.sftpClient.Chtimes(o.path(), modTime, modTime)
|
|
||||||
o.fs.putSftpConnection(&c, err)
|
|
||||||
if err != nil {
|
|
||||||
return errors.Wrap(err, "SetModTime failed")
|
|
||||||
}
|
|
||||||
err = o.stat()
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.Wrap(err, "SetModTime stat failed")
|
return errors.Wrap(err, "SetModTime stat failed")
|
||||||
}
|
}
|
||||||
|
|||||||
Loaded 100 of 2681 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user