Compare commits
189
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2769321555 | ||
|
|
c496efe9a4 | ||
|
|
cf583e0237 | ||
|
|
f09d0f5fef | ||
|
|
1e6cbaa355 | ||
|
|
be643ecfbc | ||
|
|
0c4ed35b9b | ||
|
|
4e4feebf0a | ||
|
|
291f270904 | ||
|
|
f799be1d6a | ||
|
|
74297a0c55 | ||
|
|
7e13103ba2 | ||
|
|
34baf05d9d | ||
|
|
38c0018906 | ||
|
|
6f25e48cbb | ||
|
|
7e99abb5da | ||
|
|
629019c3e4 | ||
|
|
1402fcb234 | ||
|
|
b26276b416 | ||
|
|
e317f04098 | ||
|
|
65ff330602 | ||
|
|
52763e1918 | ||
|
|
23e06cedbd | ||
|
|
b369fcde28 | ||
|
|
c294068780 | ||
|
|
8a774a3dd4 | ||
|
|
53a8b5a275 | ||
|
|
bbd03f49a4 | ||
|
|
e31578e03c | ||
|
|
0855608bc1 | ||
|
|
f8dbf8292a | ||
|
|
144daec800 | ||
|
|
6a832b7173 | ||
|
|
184a9c8da6 | ||
|
|
88592a1779 | ||
|
|
92fa30a787 | ||
|
|
e4dfe78ef0 | ||
|
|
ba84eecd94 | ||
|
|
ea12d76c03 | ||
|
|
5f0a8a4e28 | ||
|
|
2fc095cd3e | ||
|
|
a2341cc412 | ||
|
|
9685be64cd | ||
|
|
39f5059d48 | ||
|
|
a30e80564d | ||
|
|
8e107b9657 | ||
|
|
21a0693b79 | ||
|
|
4846d9393d | ||
|
|
fc4f20d52f | ||
|
|
60558b5d37 | ||
|
|
5990573ccd | ||
|
|
bd11d3cb62 | ||
|
|
5e5578d2c3 | ||
|
|
1318c6aec8 | ||
|
|
f29757de3b | ||
|
|
f397c35935 | ||
|
|
f365230aea | ||
|
|
ff0b8e10af | ||
|
|
8d16a5693c | ||
|
|
781142a73f | ||
|
|
f471a7e3f5 | ||
|
|
d7a1fd2a6b | ||
|
|
7782eda88e | ||
|
|
d08453d402 | ||
|
|
71e98ea584 | ||
|
|
42d997f639 | ||
|
|
571b4c060b | ||
|
|
ff72059a94 | ||
|
|
2e6ef4f6ec | ||
|
|
0ec6dd9f4b | ||
|
|
0b7fdf16a2 | ||
|
|
5edfd31a6d | ||
|
|
7ee7bc87ae | ||
|
|
1433558c01 | ||
|
|
0458b961c5 | ||
|
|
c1998c4efe | ||
|
|
49da220b65 | ||
|
|
554ee0d963 | ||
|
|
2d2533a08a | ||
|
|
733b072d4f | ||
|
|
2d01a65e36 | ||
|
|
b8280521a5 | ||
|
|
60e6af2605 | ||
|
|
9d16822c63 | ||
|
|
38a0946071 | ||
|
|
95e52e1ac3 | ||
|
|
51ab1c940a | ||
|
|
6f30427357 | ||
|
|
3220acc729 | ||
|
|
3c97933416 | ||
|
|
039e2a9649 | ||
|
|
1c01d0b84a | ||
|
|
39eac7a765 | ||
|
|
082a7065b1 | ||
|
|
f7b08a6982 | ||
|
|
37e32d8c80 | ||
|
|
f2a1b991de | ||
|
|
4128e696d6 | ||
|
|
7e7f3de355 | ||
|
|
1f6a1cd26d | ||
|
|
2cfe2354df | ||
|
|
13387c0838 | ||
|
|
5babf2dc5c | ||
|
|
9012d7c6c1 | ||
|
|
df1faa9a8f | ||
|
|
3de7ad5223 | ||
|
|
9cb3a68c38 | ||
|
|
c1dd76788d | ||
|
|
5ee1816a71 | ||
|
|
63b51c6742 | ||
|
|
e7684b7ed5 | ||
|
|
dda23baf42 | ||
|
|
8575abf599 | ||
|
|
feea0532cd | ||
|
|
d3e8ae1820 | ||
|
|
91a9a959a2 | ||
|
|
04eae51d11 | ||
|
|
8fb707e16d | ||
|
|
4138d5aa75 | ||
|
|
fc654a4cec | ||
|
|
26b5f55cba | ||
|
|
3f572e6bf2 | ||
|
|
941ad6bc62 | ||
|
|
5d1d93e163 | ||
|
|
35fba5bfdd | ||
|
|
887834da91 | ||
|
|
107293c80e | ||
|
|
e3c4ebd59a | ||
|
|
d99ffde7c0 | ||
|
|
198c34ce21 | ||
|
|
0eba88bbfe | ||
|
|
aeea4430d5 | ||
|
|
4b15c4215c | ||
|
|
50452207d9 | ||
|
|
01fcad9b9c | ||
|
|
eb41253764 | ||
|
|
89625e54cf | ||
|
|
58f7141c96 | ||
|
|
e56c6402a7 | ||
|
|
d0eb8ddc30 | ||
|
|
a6c28a5faa | ||
|
|
d35bd15762 | ||
|
|
8b8220c4f7 | ||
|
|
5fe3b0ad71 | ||
|
|
4c8c87a935 | ||
|
|
bb10a51b39 | ||
|
|
df01f7a4eb | ||
|
|
e84790ef79 | ||
|
|
369a8ee17b | ||
|
|
84e21ade6b | ||
|
|
703b0535a4 | ||
|
|
155264ae12 | ||
|
|
31e2ce03c3 | ||
|
|
e969505ae4 | ||
|
|
26e2f1a998 | ||
|
|
2682d5a9cf | ||
|
|
2191592e80 | ||
|
|
18f758294e | ||
|
|
f95c1c61dd | ||
|
|
8c8dcdd521 | ||
|
|
141c133818 | ||
|
|
0f03e55cd1 | ||
|
|
9e6ba92a11 | ||
|
|
762561f88e | ||
|
|
084fe38922 | ||
|
|
63a2a935fc | ||
|
|
64fce8438b | ||
|
|
f92beb4e14 | ||
|
|
f7ce2e8d95 | ||
|
|
3975d82b3b | ||
|
|
d87aa33ec5 | ||
|
|
1b78f4d1ea | ||
|
|
b3704597f3 | ||
|
|
16f797a7d7 | ||
|
|
ee700ec01a | ||
|
|
9b3c951ab7 | ||
|
|
22d17e79e3 | ||
|
|
6d3088a00b | ||
|
|
84202c7471 | ||
|
|
96a05516f9 | ||
|
|
4f6a942595 | ||
|
|
c4b0a37b21 | ||
|
|
9322f4baef | ||
|
|
fa0a1e7261 | ||
|
|
4ad08794c9 | ||
|
|
c0f600764b | ||
|
|
f139e07380 | ||
|
|
c6786eeb2d | ||
|
|
57b85b8155 |
No files matched your search
+18
-2
@@ -1,3 +1,4 @@
|
|||||||
|
---
|
||||||
version: 2
|
version: 2
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
@@ -13,10 +14,10 @@ jobs:
|
|||||||
- run:
|
- run:
|
||||||
name: Cross-compile rclone
|
name: Cross-compile rclone
|
||||||
command: |
|
command: |
|
||||||
docker pull billziss/xgo-cgofuse
|
docker pull rclone/xgo-cgofuse
|
||||||
go get -v github.com/karalabe/xgo
|
go get -v github.com/karalabe/xgo
|
||||||
xgo \
|
xgo \
|
||||||
--image=billziss/xgo-cgofuse \
|
--image=rclone/xgo-cgofuse \
|
||||||
--targets=darwin/386,darwin/amd64,linux/386,linux/amd64,windows/386,windows/amd64 \
|
--targets=darwin/386,darwin/amd64,linux/386,linux/amd64,windows/386,windows/amd64 \
|
||||||
-tags cmount \
|
-tags cmount \
|
||||||
.
|
.
|
||||||
@@ -29,6 +30,21 @@ jobs:
|
|||||||
command: |
|
command: |
|
||||||
mkdir -p /tmp/rclone.dist
|
mkdir -p /tmp/rclone.dist
|
||||||
cp -R rclone-* /tmp/rclone.dist
|
cp -R rclone-* /tmp/rclone.dist
|
||||||
|
mkdir build
|
||||||
|
cp -R rclone-* build/
|
||||||
|
|
||||||
|
- run:
|
||||||
|
name: Build rclone
|
||||||
|
command: |
|
||||||
|
go version
|
||||||
|
go build
|
||||||
|
|
||||||
|
- run:
|
||||||
|
name: Upload artifacts
|
||||||
|
command: |
|
||||||
|
if [[ $CIRCLE_PULL_REQUEST != "" ]]; then
|
||||||
|
make circleci_upload
|
||||||
|
fi
|
||||||
|
|
||||||
- store_artifacts:
|
- store_artifacts:
|
||||||
path: /tmp/rclone.dist
|
path: /tmp/rclone.dist
|
||||||
+6
-1
@@ -351,6 +351,12 @@ Unit tests
|
|||||||
Integration tests
|
Integration tests
|
||||||
|
|
||||||
* Add your backend to `fstest/test_all/config.yaml`
|
* Add your backend to `fstest/test_all/config.yaml`
|
||||||
|
* Once you've done that then you can use the integration test framework from the project root:
|
||||||
|
* go install ./...
|
||||||
|
* test_all -backend remote
|
||||||
|
|
||||||
|
Or if you want to run the integration tests manually:
|
||||||
|
|
||||||
* Make sure integration tests pass with
|
* Make sure integration tests pass with
|
||||||
* `cd fs/operations`
|
* `cd fs/operations`
|
||||||
* `go test -v -remote TestRemote:`
|
* `go test -v -remote TestRemote:`
|
||||||
@@ -372,4 +378,3 @@ Add your fs to the docs - you'll need to pick an icon for it from [fontawesome](
|
|||||||
* `docs/content/about.md` - front page of rclone.org
|
* `docs/content/about.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
|
||||||
* `cmd/cmd.go` - the main help for rclone
|
|
||||||
+11
-8
@@ -1,14 +1,17 @@
|
|||||||
# Maintainers guide for rclone #
|
# Maintainers guide for rclone #
|
||||||
|
|
||||||
Current active maintainers of rclone are
|
Current active maintainers of rclone are:
|
||||||
|
|
||||||
* Nick Craig-Wood @ncw
|
| Name | GitHub ID | Specific Responsibilities |
|
||||||
* Stefan Breunig @breunigs
|
| :--------------- | :---------- | :-------------------------- |
|
||||||
* Ishuah Kariuki @ishuah
|
| Nick Craig-Wood | @ncw | overall project health |
|
||||||
* Remus Bunduc @remusb - cache subsystem maintainer
|
| Stefan Breunig | @breunigs | |
|
||||||
* Fabian Möller @B4dM4n
|
| Ishuah Kariuki | @ishuah | |
|
||||||
* Alex Chen @Cnly
|
| Remus Bunduc | @remusb | cache backend |
|
||||||
* Sandeep Ummadi @sandeepkru
|
| Fabian Möller | @B4dM4n | |
|
||||||
|
| Alex Chen | @Cnly | onedrive backend |
|
||||||
|
| Sandeep Ummadi | @sandeepkru | azureblob backend |
|
||||||
|
| Sebastian Bünger | @buengese | jottacloud & yandex backends |
|
||||||
|
|
||||||
**This is a work in progress Draft**
|
**This is a work in progress Draft**
|
||||||
|
|
||||||
|
|||||||
+569
-64
File diff suppressed because it is too large.
Load diff
+784
-39
File diff suppressed because it is too large.
Load diff
@@ -67,7 +67,7 @@ ifdef FULL_TESTS
|
|||||||
go vet $(BUILDTAGS) -printfuncs Debugf,Infof,Logf,Errorf ./...
|
go vet $(BUILDTAGS) -printfuncs Debugf,Infof,Logf,Errorf ./...
|
||||||
errcheck $(BUILDTAGS) ./...
|
errcheck $(BUILDTAGS) ./...
|
||||||
find . -name \*.go | grep -v /vendor/ | xargs goimports -d | grep . ; test $$? -eq 1
|
find . -name \*.go | grep -v /vendor/ | xargs goimports -d | grep . ; test $$? -eq 1
|
||||||
go list ./... | xargs -n1 golint | grep -E -v '(StorageUrl|CdnUrl)' ; test $$? -eq 1
|
go list ./... | xargs -n1 golint | grep -E -v '(StorageUrl|CdnUrl|ApplicationCredentialId)' ; test $$? -eq 1
|
||||||
else
|
else
|
||||||
@echo Skipping source quality tests as version of go too old
|
@echo Skipping source quality tests as version of go too old
|
||||||
endif
|
endif
|
||||||
@@ -116,7 +116,7 @@ MANUAL.txt: MANUAL.md
|
|||||||
pandoc -s --from markdown --to plain MANUAL.md -o MANUAL.txt
|
pandoc -s --from markdown --to plain MANUAL.md -o MANUAL.txt
|
||||||
|
|
||||||
commanddocs: rclone
|
commanddocs: rclone
|
||||||
rclone gendocs docs/content/commands/
|
XDG_CACHE_HOME="" XDG_CONFIG_HOME="" HOME="\$$HOME" USER="\$$USER" rclone gendocs docs/content/commands/
|
||||||
|
|
||||||
backenddocs: rclone bin/make_backend_docs.py
|
backenddocs: rclone bin/make_backend_docs.py
|
||||||
./bin/make_backend_docs.py
|
./bin/make_backend_docs.py
|
||||||
@@ -185,6 +185,13 @@ ifndef BRANCH_PATH
|
|||||||
endif
|
endif
|
||||||
@echo Beta release ready at $(BETA_URL)
|
@echo Beta release ready at $(BETA_URL)
|
||||||
|
|
||||||
|
circleci_upload:
|
||||||
|
./rclone --config bin/travis.rclone.conf -v copy build/ $(BETA_UPLOAD)/testbuilds
|
||||||
|
ifndef BRANCH_PATH
|
||||||
|
./rclone --config bin/travis.rclone.conf -v copy build/ $(BETA_UPLOAD_ROOT)/test/testbuilds-latest
|
||||||
|
endif
|
||||||
|
@echo Beta release ready at $(BETA_URL)/testbuilds
|
||||||
|
|
||||||
BUILD_FLAGS := -exclude "^(windows|darwin)/"
|
BUILD_FLAGS := -exclude "^(windows|darwin)/"
|
||||||
ifeq ($(TRAVIS_OS_NAME),osx)
|
ifeq ($(TRAVIS_OS_NAME),osx)
|
||||||
BUILD_FLAGS := -include "^darwin/" -cgo
|
BUILD_FLAGS := -include "^darwin/" -cgo
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ Rclone *("rsync for cloud storage")* is a command line program to sync files and
|
|||||||
|
|
||||||
## Storage providers
|
## Storage providers
|
||||||
|
|
||||||
|
* Alibaba Cloud (Aliyun) Object Storage System (OSS) [:page_facing_up:](https://rclone.org/s3/#alibaba-oss)
|
||||||
* Amazon Drive [:page_facing_up:](https://rclone.org/amazonclouddrive/) ([See note](https://rclone.org/amazonclouddrive/#status))
|
* Amazon Drive [:page_facing_up:](https://rclone.org/amazonclouddrive/) ([See note](https://rclone.org/amazonclouddrive/#status))
|
||||||
* Amazon S3 [:page_facing_up:](https://rclone.org/s3/)
|
* Amazon S3 [:page_facing_up:](https://rclone.org/s3/)
|
||||||
* Backblaze B2 [:page_facing_up:](https://rclone.org/b2/)
|
* Backblaze B2 [:page_facing_up:](https://rclone.org/b2/)
|
||||||
@@ -50,6 +51,7 @@ Rclone *("rsync for cloud storage")* is a command line program to sync files and
|
|||||||
* put.io [:page_facing_up:](https://rclone.org/webdav/#put-io)
|
* put.io [:page_facing_up:](https://rclone.org/webdav/#put-io)
|
||||||
* 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)
|
||||||
* SFTP [:page_facing_up:](https://rclone.org/sftp/)
|
* SFTP [:page_facing_up:](https://rclone.org/sftp/)
|
||||||
* 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/)
|
||||||
@@ -91,4 +93,4 @@ License
|
|||||||
-------
|
-------
|
||||||
|
|
||||||
This is free software under the terms of MIT the license (check the
|
This is free software under the terms of MIT the license (check the
|
||||||
[COPYING file](/rclone/COPYING) included in this package).
|
[COPYING file](/COPYING) included in this package).
|
||||||
@@ -21,7 +21,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/ncw/go-acd"
|
acd "github.com/ncw/go-acd"
|
||||||
"github.com/ncw/rclone/fs"
|
"github.com/ncw/rclone/fs"
|
||||||
"github.com/ncw/rclone/fs/config"
|
"github.com/ncw/rclone/fs/config"
|
||||||
"github.com/ncw/rclone/fs/config/configmap"
|
"github.com/ncw/rclone/fs/config/configmap"
|
||||||
@@ -264,7 +264,7 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
}
|
}
|
||||||
oAuthClient, ts, err := oauthutil.NewClientWithBaseClient(name, m, acdConfig, baseClient)
|
oAuthClient, ts, err := oauthutil.NewClientWithBaseClient(name, m, acdConfig, baseClient)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Failed to configure Amazon Drive: %v", err)
|
return nil, errors.Wrap(err, "failed to configure Amazon Drive")
|
||||||
}
|
}
|
||||||
|
|
||||||
c := acd.NewClient(oAuthClient)
|
c := acd.NewClient(oAuthClient)
|
||||||
|
|||||||
+153
-32
@@ -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 !freebsd,!netbsd,!openbsd,!plan9,!solaris,go1.8
|
// +build !plan9,!solaris,go1.8
|
||||||
|
|
||||||
package azureblob
|
package azureblob
|
||||||
|
|
||||||
@@ -22,12 +22,14 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/Azure/azure-pipeline-go/pipeline"
|
||||||
"github.com/Azure/azure-storage-blob-go/azblob"
|
"github.com/Azure/azure-storage-blob-go/azblob"
|
||||||
"github.com/ncw/rclone/fs"
|
"github.com/ncw/rclone/fs"
|
||||||
"github.com/ncw/rclone/fs/accounting"
|
"github.com/ncw/rclone/fs/accounting"
|
||||||
"github.com/ncw/rclone/fs/config/configmap"
|
"github.com/ncw/rclone/fs/config/configmap"
|
||||||
"github.com/ncw/rclone/fs/config/configstruct"
|
"github.com/ncw/rclone/fs/config/configstruct"
|
||||||
"github.com/ncw/rclone/fs/fserrors"
|
"github.com/ncw/rclone/fs/fserrors"
|
||||||
|
"github.com/ncw/rclone/fs/fshttp"
|
||||||
"github.com/ncw/rclone/fs/hash"
|
"github.com/ncw/rclone/fs/hash"
|
||||||
"github.com/ncw/rclone/fs/walk"
|
"github.com/ncw/rclone/fs/walk"
|
||||||
"github.com/ncw/rclone/lib/pacer"
|
"github.com/ncw/rclone/lib/pacer"
|
||||||
@@ -50,6 +52,7 @@ const (
|
|||||||
defaultUploadCutoff = 256 * fs.MebiByte
|
defaultUploadCutoff = 256 * fs.MebiByte
|
||||||
maxUploadCutoff = 256 * fs.MebiByte
|
maxUploadCutoff = 256 * fs.MebiByte
|
||||||
defaultAccessTier = azblob.AccessTierNone
|
defaultAccessTier = azblob.AccessTierNone
|
||||||
|
maxTryTimeout = time.Hour * 24 * 365 //max time of an azure web request response window (whether or not data is flowing)
|
||||||
)
|
)
|
||||||
|
|
||||||
// Register with Fs
|
// Register with Fs
|
||||||
@@ -134,6 +137,7 @@ type Fs struct {
|
|||||||
root string // the path we are working on if any
|
root string // the path we are working on if any
|
||||||
opt Options // parsed config options
|
opt Options // parsed config options
|
||||||
features *fs.Features // optional features
|
features *fs.Features // optional features
|
||||||
|
client *http.Client // http client we are using
|
||||||
svcURL *azblob.ServiceURL // reference to serviceURL
|
svcURL *azblob.ServiceURL // reference to serviceURL
|
||||||
cntURL *azblob.ContainerURL // reference to containerURL
|
cntURL *azblob.ContainerURL // reference to containerURL
|
||||||
container string // the container we are working on
|
container string // the container we are working on
|
||||||
@@ -271,6 +275,38 @@ func (f *Fs) setUploadCutoff(cs fs.SizeSuffix) (old fs.SizeSuffix, err error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// httpClientFactory creates a Factory object that sends HTTP requests
|
||||||
|
// to a rclone's http.Client.
|
||||||
|
//
|
||||||
|
// copied from azblob.newDefaultHTTPClientFactory
|
||||||
|
func httpClientFactory(client *http.Client) pipeline.Factory {
|
||||||
|
return pipeline.FactoryFunc(func(next pipeline.Policy, po *pipeline.PolicyOptions) pipeline.PolicyFunc {
|
||||||
|
return func(ctx context.Context, request pipeline.Request) (pipeline.Response, error) {
|
||||||
|
r, err := client.Do(request.WithContext(ctx))
|
||||||
|
if err != nil {
|
||||||
|
err = pipeline.NewError(err, "HTTP request failed")
|
||||||
|
}
|
||||||
|
return pipeline.NewHTTPResponse(r), err
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// newPipeline creates a Pipeline using the specified credentials and options.
|
||||||
|
//
|
||||||
|
// this code was copied from azblob.NewPipeline
|
||||||
|
func (f *Fs) newPipeline(c azblob.Credential, o azblob.PipelineOptions) pipeline.Pipeline {
|
||||||
|
// Closest to API goes first; closest to the wire goes last
|
||||||
|
factories := []pipeline.Factory{
|
||||||
|
azblob.NewTelemetryPolicyFactory(o.Telemetry),
|
||||||
|
azblob.NewUniqueRequestIDPolicyFactory(),
|
||||||
|
azblob.NewRetryPolicyFactory(o.Retry),
|
||||||
|
c,
|
||||||
|
pipeline.MethodFactoryMarker(), // indicates at what stage in the pipeline the method factory is invoked
|
||||||
|
azblob.NewRequestLogPolicyFactory(o.RequestLog),
|
||||||
|
}
|
||||||
|
return pipeline.NewPipeline(factories, pipeline.Options{HTTPSender: httpClientFactory(f.client), Log: o.Log})
|
||||||
|
}
|
||||||
|
|
||||||
// NewFs contstructs an Fs from the path, container:path
|
// NewFs contstructs 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) {
|
||||||
// Parse config into Options struct
|
// Parse config into Options struct
|
||||||
@@ -306,6 +342,23 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
string(azblob.AccessTierHot), string(azblob.AccessTierCool), string(azblob.AccessTierArchive))
|
string(azblob.AccessTierHot), string(azblob.AccessTierCool), string(azblob.AccessTierArchive))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
f := &Fs{
|
||||||
|
name: name,
|
||||||
|
opt: *opt,
|
||||||
|
container: container,
|
||||||
|
root: directory,
|
||||||
|
pacer: pacer.New().SetMinSleep(minSleep).SetMaxSleep(maxSleep).SetDecayConstant(decayConstant).SetPacer(pacer.S3Pacer),
|
||||||
|
uploadToken: pacer.NewTokenDispenser(fs.Config.Transfers),
|
||||||
|
client: fshttp.NewClient(fs.Config),
|
||||||
|
}
|
||||||
|
f.features = (&fs.Features{
|
||||||
|
ReadMimeType: true,
|
||||||
|
WriteMimeType: true,
|
||||||
|
BucketBased: true,
|
||||||
|
SetTier: true,
|
||||||
|
GetTier: true,
|
||||||
|
}).Fill(f)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
u *url.URL
|
u *url.URL
|
||||||
serviceURL azblob.ServiceURL
|
serviceURL azblob.ServiceURL
|
||||||
@@ -322,7 +375,7 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "failed to make azure storage url from account and endpoint")
|
return nil, errors.Wrap(err, "failed to make azure storage url from account and endpoint")
|
||||||
}
|
}
|
||||||
pipeline := azblob.NewPipeline(credential, azblob.PipelineOptions{})
|
pipeline := f.newPipeline(credential, azblob.PipelineOptions{Retry: azblob.RetryOptions{TryTimeout: maxTryTimeout}})
|
||||||
serviceURL = azblob.NewServiceURL(*u, pipeline)
|
serviceURL = azblob.NewServiceURL(*u, pipeline)
|
||||||
containerURL = serviceURL.NewContainerURL(container)
|
containerURL = serviceURL.NewContainerURL(container)
|
||||||
case opt.SASURL != "":
|
case opt.SASURL != "":
|
||||||
@@ -331,7 +384,7 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
return nil, errors.Wrapf(err, "failed to parse SAS URL")
|
return nil, errors.Wrapf(err, "failed to parse SAS URL")
|
||||||
}
|
}
|
||||||
// use anonymous credentials in case of sas url
|
// use anonymous credentials in case of sas url
|
||||||
pipeline := azblob.NewPipeline(azblob.NewAnonymousCredential(), azblob.PipelineOptions{})
|
pipeline := f.newPipeline(azblob.NewAnonymousCredential(), azblob.PipelineOptions{Retry: azblob.RetryOptions{TryTimeout: maxTryTimeout}})
|
||||||
// Check if we have container level SAS or account level sas
|
// Check if we have container level SAS or account level sas
|
||||||
parts := azblob.NewBlobURLParts(*u)
|
parts := azblob.NewBlobURLParts(*u)
|
||||||
if parts.ContainerName != "" {
|
if parts.ContainerName != "" {
|
||||||
@@ -348,24 +401,9 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
default:
|
default:
|
||||||
return nil, errors.New("Need account+key or connectionString or sasURL")
|
return nil, errors.New("Need account+key or connectionString or sasURL")
|
||||||
}
|
}
|
||||||
|
f.svcURL = &serviceURL
|
||||||
|
f.cntURL = &containerURL
|
||||||
|
|
||||||
f := &Fs{
|
|
||||||
name: name,
|
|
||||||
opt: *opt,
|
|
||||||
container: container,
|
|
||||||
root: directory,
|
|
||||||
svcURL: &serviceURL,
|
|
||||||
cntURL: &containerURL,
|
|
||||||
pacer: pacer.New().SetMinSleep(minSleep).SetMaxSleep(maxSleep).SetDecayConstant(decayConstant),
|
|
||||||
uploadToken: pacer.NewTokenDispenser(fs.Config.Transfers),
|
|
||||||
}
|
|
||||||
f.features = (&fs.Features{
|
|
||||||
ReadMimeType: true,
|
|
||||||
WriteMimeType: true,
|
|
||||||
BucketBased: true,
|
|
||||||
SetTier: true,
|
|
||||||
GetTier: true,
|
|
||||||
}).Fill(f)
|
|
||||||
if f.root != "" {
|
if f.root != "" {
|
||||||
f.root += "/"
|
f.root += "/"
|
||||||
// Check to see if the (container,directory) is actually an existing file
|
// Check to see if the (container,directory) is actually an existing file
|
||||||
@@ -379,8 +417,8 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
}
|
}
|
||||||
_, err := f.NewObject(remote)
|
_, err := f.NewObject(remote)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err == fs.ErrorObjectNotFound {
|
if err == fs.ErrorObjectNotFound || err == fs.ErrorNotAFile {
|
||||||
// File doesn't exist so return old f
|
// File doesn't exist or is a directory so return old f
|
||||||
f.root = oldRoot
|
f.root = oldRoot
|
||||||
return f, nil
|
return f, nil
|
||||||
}
|
}
|
||||||
@@ -436,6 +474,21 @@ func (o *Object) updateMetadataWithModTime(modTime time.Time) {
|
|||||||
o.meta[modTimeKey] = modTime.Format(timeFormatOut)
|
o.meta[modTimeKey] = modTime.Format(timeFormatOut)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Returns whether file is a directory marker or not
|
||||||
|
func isDirectoryMarker(size int64, metadata azblob.Metadata, remote string) bool {
|
||||||
|
// Directory markers are 0 length
|
||||||
|
if size == 0 {
|
||||||
|
// Note that metadata with hdi_isfolder = true seems to be a
|
||||||
|
// defacto standard for marking blobs as directories.
|
||||||
|
endsWithSlash := strings.HasSuffix(remote, "/")
|
||||||
|
if endsWithSlash || remote == "" || metadata["hdi_isfolder"] == "true" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
// listFn is called from list to handle an object
|
// listFn is called from list to handle an object
|
||||||
type listFn func(remote string, object *azblob.BlobItem, isDirectory bool) error
|
type listFn func(remote string, object *azblob.BlobItem, isDirectory bool) error
|
||||||
|
|
||||||
@@ -471,6 +524,7 @@ func (f *Fs) list(dir string, recurse bool, maxResults uint, fn listFn) error {
|
|||||||
MaxResults: int32(maxResults),
|
MaxResults: int32(maxResults),
|
||||||
}
|
}
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
directoryMarkers := map[string]struct{}{}
|
||||||
for marker := (azblob.Marker{}); marker.NotDone(); {
|
for marker := (azblob.Marker{}); marker.NotDone(); {
|
||||||
var response *azblob.ListBlobsHierarchySegmentResponse
|
var response *azblob.ListBlobsHierarchySegmentResponse
|
||||||
err := f.pacer.Call(func() (bool, error) {
|
err := f.pacer.Call(func() (bool, error) {
|
||||||
@@ -500,13 +554,23 @@ func (f *Fs) list(dir string, recurse bool, maxResults uint, fn listFn) error {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
remote := file.Name[len(f.root):]
|
remote := file.Name[len(f.root):]
|
||||||
// Check for directory
|
if isDirectoryMarker(*file.Properties.ContentLength, file.Metadata, remote) {
|
||||||
isDirectory := strings.HasSuffix(remote, "/")
|
if strings.HasSuffix(remote, "/") {
|
||||||
if isDirectory {
|
remote = remote[:len(remote)-1]
|
||||||
remote = remote[:len(remote)-1]
|
}
|
||||||
|
err = fn(remote, file, true)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
// Keep track of directory markers. If recursing then
|
||||||
|
// there will be no Prefixes so no need to keep track
|
||||||
|
if !recurse {
|
||||||
|
directoryMarkers[remote] = struct{}{}
|
||||||
|
}
|
||||||
|
continue // skip directory marker
|
||||||
}
|
}
|
||||||
// Send object
|
// Send object
|
||||||
err = fn(remote, file, isDirectory)
|
err = fn(remote, file, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -519,6 +583,10 @@ func (f *Fs) list(dir string, recurse bool, maxResults uint, fn listFn) error {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
remote = remote[len(f.root):]
|
remote = remote[len(f.root):]
|
||||||
|
// Don't send if already sent as a directory marker
|
||||||
|
if _, found := directoryMarkers[remote]; found {
|
||||||
|
continue
|
||||||
|
}
|
||||||
// Send object
|
// Send object
|
||||||
err = fn(remote, nil, true)
|
err = fn(remote, nil, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -686,6 +754,35 @@ func (f *Fs) Put(in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.
|
|||||||
return fs, fs.Update(in, src, options...)
|
return fs, fs.Update(in, src, options...)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check if the container exists
|
||||||
|
//
|
||||||
|
// NB this can return incorrect results if called immediately after container deletion
|
||||||
|
func (f *Fs) dirExists() (bool, error) {
|
||||||
|
options := azblob.ListBlobsSegmentOptions{
|
||||||
|
Details: azblob.BlobListingDetails{
|
||||||
|
Copy: false,
|
||||||
|
Metadata: false,
|
||||||
|
Snapshots: false,
|
||||||
|
UncommittedBlobs: false,
|
||||||
|
Deleted: false,
|
||||||
|
},
|
||||||
|
MaxResults: 1,
|
||||||
|
}
|
||||||
|
err := f.pacer.Call(func() (bool, error) {
|
||||||
|
ctx := context.Background()
|
||||||
|
_, err := f.cntURL.ListBlobsHierarchySegment(ctx, azblob.Marker{}, "", options)
|
||||||
|
return f.shouldRetry(err)
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
// Check http error code along with service code, current SDK doesn't populate service code correctly sometimes
|
||||||
|
if storageErr, ok := err.(azblob.StorageError); ok && (storageErr.ServiceCode() == azblob.ServiceCodeContainerNotFound || storageErr.Response().StatusCode == http.StatusNotFound) {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
// Mkdir creates the container if it doesn't exist
|
// Mkdir creates the container if it doesn't exist
|
||||||
func (f *Fs) Mkdir(dir string) error {
|
func (f *Fs) Mkdir(dir string) error {
|
||||||
f.containerOKMu.Lock()
|
f.containerOKMu.Lock()
|
||||||
@@ -693,6 +790,15 @@ func (f *Fs) Mkdir(dir string) error {
|
|||||||
if f.containerOK {
|
if f.containerOK {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
if !f.containerDeleted {
|
||||||
|
exists, err := f.dirExists()
|
||||||
|
if err == nil {
|
||||||
|
f.containerOK = exists
|
||||||
|
}
|
||||||
|
if err != nil || exists {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// now try to create the container
|
// now try to create the container
|
||||||
err := f.pacer.Call(func() (bool, error) {
|
err := f.pacer.Call(func() (bool, error) {
|
||||||
@@ -705,6 +811,11 @@ func (f *Fs) Mkdir(dir string) error {
|
|||||||
f.containerOK = true
|
f.containerOK = true
|
||||||
return false, nil
|
return false, nil
|
||||||
case azblob.ServiceCodeContainerBeingDeleted:
|
case azblob.ServiceCodeContainerBeingDeleted:
|
||||||
|
// From https://docs.microsoft.com/en-us/rest/api/storageservices/delete-container
|
||||||
|
// When a container is deleted, a container with the same name cannot be created
|
||||||
|
// for at least 30 seconds; the container may not be available for more than 30
|
||||||
|
// seconds if the service is still processing the request.
|
||||||
|
time.Sleep(6 * time.Second) // default 10 retries will be 60 seconds
|
||||||
f.containerDeleted = true
|
f.containerDeleted = true
|
||||||
return true, err
|
return true, err
|
||||||
}
|
}
|
||||||
@@ -722,7 +833,7 @@ func (f *Fs) Mkdir(dir string) error {
|
|||||||
// isEmpty checks to see if a given directory is empty and returns an error if not
|
// isEmpty checks to see if a given directory is empty and returns an error if not
|
||||||
func (f *Fs) isEmpty(dir string) (err error) {
|
func (f *Fs) isEmpty(dir string) (err error) {
|
||||||
empty := true
|
empty := true
|
||||||
err = f.list("", true, 1, func(remote string, object *azblob.BlobItem, isDirectory bool) error {
|
err = f.list(dir, true, 1, func(remote string, object *azblob.BlobItem, isDirectory bool) error {
|
||||||
empty = false
|
empty = false
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
@@ -917,27 +1028,37 @@ func (o *Object) setMetadata(metadata azblob.Metadata) {
|
|||||||
// o.md5
|
// o.md5
|
||||||
// o.meta
|
// o.meta
|
||||||
func (o *Object) decodeMetaDataFromPropertiesResponse(info *azblob.BlobGetPropertiesResponse) (err error) {
|
func (o *Object) decodeMetaDataFromPropertiesResponse(info *azblob.BlobGetPropertiesResponse) (err error) {
|
||||||
|
metadata := info.NewMetadata()
|
||||||
|
size := info.ContentLength()
|
||||||
|
if isDirectoryMarker(size, metadata, o.remote) {
|
||||||
|
return fs.ErrorNotAFile
|
||||||
|
}
|
||||||
// NOTE - Client library always returns MD5 as base64 decoded string, Object needs to maintain
|
// NOTE - Client library always returns MD5 as base64 decoded string, Object needs to maintain
|
||||||
// this as base64 encoded string.
|
// this as base64 encoded string.
|
||||||
o.md5 = base64.StdEncoding.EncodeToString(info.ContentMD5())
|
o.md5 = base64.StdEncoding.EncodeToString(info.ContentMD5())
|
||||||
o.mimeType = info.ContentType()
|
o.mimeType = info.ContentType()
|
||||||
o.size = info.ContentLength()
|
o.size = size
|
||||||
o.modTime = time.Time(info.LastModified())
|
o.modTime = time.Time(info.LastModified())
|
||||||
o.accessTier = azblob.AccessTierType(info.AccessTier())
|
o.accessTier = azblob.AccessTierType(info.AccessTier())
|
||||||
o.setMetadata(info.NewMetadata())
|
o.setMetadata(metadata)
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *Object) decodeMetaDataFromBlob(info *azblob.BlobItem) (err error) {
|
func (o *Object) decodeMetaDataFromBlob(info *azblob.BlobItem) (err error) {
|
||||||
|
metadata := info.Metadata
|
||||||
|
size := *info.Properties.ContentLength
|
||||||
|
if isDirectoryMarker(size, metadata, o.remote) {
|
||||||
|
return fs.ErrorNotAFile
|
||||||
|
}
|
||||||
// NOTE - Client library always returns MD5 as base64 decoded string, Object needs to maintain
|
// NOTE - Client library always returns MD5 as base64 decoded string, Object needs to maintain
|
||||||
// this as base64 encoded string.
|
// this as base64 encoded string.
|
||||||
o.md5 = base64.StdEncoding.EncodeToString(info.Properties.ContentMD5)
|
o.md5 = base64.StdEncoding.EncodeToString(info.Properties.ContentMD5)
|
||||||
o.mimeType = *info.Properties.ContentType
|
o.mimeType = *info.Properties.ContentType
|
||||||
o.size = *info.Properties.ContentLength
|
o.size = size
|
||||||
o.modTime = info.Properties.LastModified
|
o.modTime = info.Properties.LastModified
|
||||||
o.accessTier = info.Properties.AccessTier
|
o.accessTier = info.Properties.AccessTier
|
||||||
o.setMetadata(info.Metadata)
|
o.setMetadata(metadata)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
// +build !freebsd,!netbsd,!openbsd,!plan9,!solaris,go1.8
|
// +build !plan9,!solaris,go1.8
|
||||||
|
|
||||||
package azureblob
|
package azureblob
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// Test AzureBlob filesystem interface
|
// Test AzureBlob filesystem interface
|
||||||
|
|
||||||
// +build !freebsd,!netbsd,!openbsd,!plan9,!solaris,go1.8
|
// +build !plan9,!solaris,go1.8
|
||||||
|
|
||||||
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 freebsd netbsd openbsd plan9 solaris !go1.8
|
// +build plan9 solaris !go1.8
|
||||||
|
|
||||||
package azureblob
|
package azureblob
|
||||||
@@ -136,6 +136,7 @@ type AuthorizeAccountResponse struct {
|
|||||||
AccountID string `json:"accountId"` // The identifier for the account.
|
AccountID string `json:"accountId"` // The identifier for the account.
|
||||||
Allowed struct { // An object (see below) containing the capabilities of this auth token, and any restrictions on using it.
|
Allowed struct { // An object (see below) containing the capabilities of this auth token, and any restrictions on using it.
|
||||||
BucketID string `json:"bucketId"` // When present, access is restricted to one bucket.
|
BucketID string `json:"bucketId"` // When present, access is restricted to one bucket.
|
||||||
|
BucketName string `json:"bucketName"` // When present, name of bucket - may be empty
|
||||||
Capabilities []string `json:"capabilities"` // A list of strings, each one naming a capability the key has.
|
Capabilities []string `json:"capabilities"` // A list of strings, each one naming a capability the key has.
|
||||||
NamePrefix interface{} `json:"namePrefix"` // When present, access is restricted to files whose names start with the prefix
|
NamePrefix interface{} `json:"namePrefix"` // When present, access is restricted to files whose names start with the prefix
|
||||||
} `json:"allowed"`
|
} `json:"allowed"`
|
||||||
|
|||||||
+30
-13
@@ -120,20 +120,26 @@ these chunks are buffered in memory and there might a maximum of
|
|||||||
minimim size.`,
|
minimim size.`,
|
||||||
Default: fs.SizeSuffix(defaultChunkSize),
|
Default: fs.SizeSuffix(defaultChunkSize),
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: "disable_checksum",
|
||||||
|
Help: `Disable checksums for large (> upload cutoff) files`,
|
||||||
|
Default: false,
|
||||||
|
Advanced: true,
|
||||||
}},
|
}},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Options defines the configuration for this backend
|
// Options defines the configuration for this backend
|
||||||
type Options struct {
|
type Options struct {
|
||||||
Account string `config:"account"`
|
Account string `config:"account"`
|
||||||
Key string `config:"key"`
|
Key string `config:"key"`
|
||||||
Endpoint string `config:"endpoint"`
|
Endpoint string `config:"endpoint"`
|
||||||
TestMode string `config:"test_mode"`
|
TestMode string `config:"test_mode"`
|
||||||
Versions bool `config:"versions"`
|
Versions bool `config:"versions"`
|
||||||
HardDelete bool `config:"hard_delete"`
|
HardDelete bool `config:"hard_delete"`
|
||||||
UploadCutoff fs.SizeSuffix `config:"upload_cutoff"`
|
UploadCutoff fs.SizeSuffix `config:"upload_cutoff"`
|
||||||
ChunkSize fs.SizeSuffix `config:"chunk_size"`
|
ChunkSize fs.SizeSuffix `config:"chunk_size"`
|
||||||
|
DisableCheckSum bool `config:"disable_checksum"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fs represents a remote b2 server
|
// Fs represents a remote b2 server
|
||||||
@@ -368,6 +374,13 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
}
|
}
|
||||||
// If this is a key limited to a single bucket, it must exist already
|
// If this is a key limited to a single bucket, it must exist already
|
||||||
if f.bucket != "" && f.info.Allowed.BucketID != "" {
|
if f.bucket != "" && f.info.Allowed.BucketID != "" {
|
||||||
|
allowedBucket := f.info.Allowed.BucketName
|
||||||
|
if allowedBucket == "" {
|
||||||
|
return nil, errors.New("bucket that application key is restricted to no longer exists")
|
||||||
|
}
|
||||||
|
if allowedBucket != f.bucket {
|
||||||
|
return nil, errors.Errorf("you must use bucket %q with this application key", allowedBucket)
|
||||||
|
}
|
||||||
f.markBucketOK()
|
f.markBucketOK()
|
||||||
f.setBucketID(f.info.Allowed.BucketID)
|
f.setBucketID(f.info.Allowed.BucketID)
|
||||||
}
|
}
|
||||||
@@ -980,6 +993,12 @@ func (f *Fs) purge(oldOnly bool) error {
|
|||||||
errReturn = err
|
errReturn = err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
var isUnfinishedUploadStale = func(timestamp api.Timestamp) bool {
|
||||||
|
if time.Since(time.Time(timestamp)).Hours() > 24 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
// Delete Config.Transfers in parallel
|
// Delete Config.Transfers in parallel
|
||||||
toBeDeleted := make(chan *api.File, fs.Config.Transfers)
|
toBeDeleted := make(chan *api.File, fs.Config.Transfers)
|
||||||
@@ -1003,6 +1022,9 @@ func (f *Fs) purge(oldOnly bool) error {
|
|||||||
if object.Action == "hide" {
|
if object.Action == "hide" {
|
||||||
fs.Debugf(remote, "Deleting current version (id %q) as it is a hide marker", object.ID)
|
fs.Debugf(remote, "Deleting current version (id %q) as it is a hide marker", object.ID)
|
||||||
toBeDeleted <- object
|
toBeDeleted <- object
|
||||||
|
} else if object.Action == "start" && isUnfinishedUploadStale(object.UploadTimestamp) {
|
||||||
|
fs.Debugf(remote, "Deleting current version (id %q) as it is a start marker (upload started at %s)", object.ID, time.Time(object.UploadTimestamp).Local())
|
||||||
|
toBeDeleted <- object
|
||||||
} else {
|
} else {
|
||||||
fs.Debugf(remote, "Not deleting current version (id %q) %q", object.ID, object.Action)
|
fs.Debugf(remote, "Not deleting current version (id %q) %q", object.ID, object.Action)
|
||||||
}
|
}
|
||||||
@@ -1484,11 +1506,6 @@ func (o *Object) Update(in io.Reader, src fs.ObjectInfo, options ...fs.OpenOptio
|
|||||||
},
|
},
|
||||||
ContentLength: &size,
|
ContentLength: &size,
|
||||||
}
|
}
|
||||||
// for go1.8 (see release notes) we must nil the Body if we want a
|
|
||||||
// "Content-Length: 0" header which b2 requires for all files.
|
|
||||||
if size == 0 {
|
|
||||||
opts.Body = nil
|
|
||||||
}
|
|
||||||
var response api.FileInfo
|
var response api.FileInfo
|
||||||
// Don't retry, return a retry error instead
|
// Don't retry, return a retry error instead
|
||||||
err = o.fs.pacer.CallNoRetry(func() (bool, error) {
|
err = o.fs.pacer.CallNoRetry(func() (bool, error) {
|
||||||
|
|||||||
@@ -116,8 +116,10 @@ func (f *Fs) newLargeUpload(o *Object, in io.Reader, src fs.ObjectInfo) (up *lar
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
// Set the SHA1 if known
|
// Set the SHA1 if known
|
||||||
if calculatedSha1, err := src.Hash(hash.SHA1); err == nil && calculatedSha1 != "" {
|
if !o.fs.opt.DisableCheckSum {
|
||||||
request.Info[sha1Key] = calculatedSha1
|
if calculatedSha1, err := src.Hash(hash.SHA1); err == nil && calculatedSha1 != "" {
|
||||||
|
request.Info[sha1Key] = calculatedSha1
|
||||||
|
}
|
||||||
}
|
}
|
||||||
var response api.StartLargeFileResponse
|
var response api.StartLargeFileResponse
|
||||||
err = f.pacer.Call(func() (bool, error) {
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
|
|||||||
+1
-1
@@ -252,7 +252,7 @@ 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)
|
oAuthClient, ts, err := oauthutil.NewClient(name, m, oauthConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Failed to configure Box: %v", err)
|
return nil, errors.Wrap(err, "failed to configure Box")
|
||||||
}
|
}
|
||||||
|
|
||||||
f := &Fs{
|
f := &Fs{
|
||||||
|
|||||||
Vendored
+1
-1
@@ -15,7 +15,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/ncw/rclone/fs"
|
"github.com/ncw/rclone/fs"
|
||||||
"github.com/patrickmn/go-cache"
|
cache "github.com/patrickmn/go-cache"
|
||||||
"golang.org/x/net/websocket"
|
"golang.org/x/net/websocket"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
Vendored
+1
-1
@@ -8,7 +8,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/ncw/rclone/fs"
|
"github.com/ncw/rclone/fs"
|
||||||
"github.com/patrickmn/go-cache"
|
cache "github.com/patrickmn/go-cache"
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
+14
-1
@@ -41,6 +41,7 @@ var (
|
|||||||
ErrorBadDecryptControlChar = errors.New("bad decryption - contains control chars")
|
ErrorBadDecryptControlChar = errors.New("bad decryption - contains control chars")
|
||||||
ErrorNotAMultipleOfBlocksize = errors.New("not a multiple of blocksize")
|
ErrorNotAMultipleOfBlocksize = errors.New("not a multiple of blocksize")
|
||||||
ErrorTooShortAfterDecode = errors.New("too short after base32 decode")
|
ErrorTooShortAfterDecode = errors.New("too short after base32 decode")
|
||||||
|
ErrorTooLongAfterDecode = errors.New("too long after base32 decode")
|
||||||
ErrorEncryptedFileTooShort = errors.New("file is too short to be encrypted")
|
ErrorEncryptedFileTooShort = errors.New("file is too short to be encrypted")
|
||||||
ErrorEncryptedFileBadHeader = errors.New("file has truncated block header")
|
ErrorEncryptedFileBadHeader = errors.New("file has truncated block header")
|
||||||
ErrorEncryptedBadMagic = errors.New("not an encrypted file - bad magic string")
|
ErrorEncryptedBadMagic = errors.New("not an encrypted file - bad magic string")
|
||||||
@@ -143,6 +144,7 @@ type cipher struct {
|
|||||||
buffers sync.Pool // encrypt/decrypt buffers
|
buffers sync.Pool // encrypt/decrypt buffers
|
||||||
cryptoRand io.Reader // read crypto random numbers from here
|
cryptoRand io.Reader // read crypto random numbers from here
|
||||||
dirNameEncrypt bool
|
dirNameEncrypt bool
|
||||||
|
passCorrupted bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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
|
||||||
@@ -162,6 +164,11 @@ func newCipher(mode NameEncryptionMode, password, salt string, dirNameEncrypt bo
|
|||||||
return c, nil
|
return c, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Set to pass corrupted blocks
|
||||||
|
func (c *cipher) setPassCorrupted(passCorrupted bool) {
|
||||||
|
c.passCorrupted = passCorrupted
|
||||||
|
}
|
||||||
|
|
||||||
// Key creates all the internal keys from the password passed in using
|
// Key creates all the internal keys from the password passed in using
|
||||||
// scrypt.
|
// scrypt.
|
||||||
//
|
//
|
||||||
@@ -284,6 +291,9 @@ func (c *cipher) decryptSegment(ciphertext string) (string, error) {
|
|||||||
// not possible if decodeFilename() working correctly
|
// not possible if decodeFilename() working correctly
|
||||||
return "", ErrorTooShortAfterDecode
|
return "", ErrorTooShortAfterDecode
|
||||||
}
|
}
|
||||||
|
if len(rawCiphertext) > 2048 {
|
||||||
|
return "", ErrorTooLongAfterDecode
|
||||||
|
}
|
||||||
paddedPlaintext := eme.Transform(c.block, c.nameTweak[:], rawCiphertext, eme.DirectionDecrypt)
|
paddedPlaintext := eme.Transform(c.block, c.nameTweak[:], rawCiphertext, eme.DirectionDecrypt)
|
||||||
plaintext, err := pkcs7.Unpad(nameCipherBlockSize, paddedPlaintext)
|
plaintext, err := pkcs7.Unpad(nameCipherBlockSize, paddedPlaintext)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -818,7 +828,10 @@ func (fh *decrypter) fillBuffer() (err error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err // return pending error as it is likely more accurate
|
return err // return pending error as it is likely more accurate
|
||||||
}
|
}
|
||||||
return ErrorEncryptedBadBlock
|
if !fh.c.passCorrupted {
|
||||||
|
return ErrorEncryptedBadBlock
|
||||||
|
}
|
||||||
|
fs.Errorf(nil, "passing corrupted block")
|
||||||
}
|
}
|
||||||
fh.bufIndex = 0
|
fh.bufIndex = 0
|
||||||
fh.bufSize = n - blockHeaderSize
|
fh.bufSize = n - blockHeaderSize
|
||||||
|
|||||||
@@ -194,6 +194,10 @@ func TestEncryptSegment(t *testing.T) {
|
|||||||
|
|
||||||
func TestDecryptSegment(t *testing.T) {
|
func TestDecryptSegment(t *testing.T) {
|
||||||
// We've tested the forwards above, now concentrate on the errors
|
// We've tested the forwards above, now concentrate on the errors
|
||||||
|
longName := make([]byte, 3328)
|
||||||
|
for i := range longName {
|
||||||
|
longName[i] = 'a'
|
||||||
|
}
|
||||||
c, _ := newCipher(NameEncryptionStandard, "", "", true)
|
c, _ := newCipher(NameEncryptionStandard, "", "", true)
|
||||||
for _, test := range []struct {
|
for _, test := range []struct {
|
||||||
in string
|
in string
|
||||||
@@ -201,6 +205,7 @@ func TestDecryptSegment(t *testing.T) {
|
|||||||
}{
|
}{
|
||||||
{"64=", ErrorBadBase32Encoding},
|
{"64=", ErrorBadBase32Encoding},
|
||||||
{"!", base32.CorruptInputError(0)},
|
{"!", base32.CorruptInputError(0)},
|
||||||
|
{string(longName), ErrorTooLongAfterDecode},
|
||||||
{encodeFileName([]byte("a")), ErrorNotAMultipleOfBlocksize},
|
{encodeFileName([]byte("a")), ErrorNotAMultipleOfBlocksize},
|
||||||
{encodeFileName([]byte("123456789abcdef")), ErrorNotAMultipleOfBlocksize},
|
{encodeFileName([]byte("123456789abcdef")), ErrorNotAMultipleOfBlocksize},
|
||||||
{encodeFileName([]byte("123456789abcdef0")), pkcs7.ErrorPaddingTooLong},
|
{encodeFileName([]byte("123456789abcdef0")), pkcs7.ErrorPaddingTooLong},
|
||||||
|
|||||||
+11
-1
@@ -17,7 +17,6 @@ import (
|
|||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Globals
|
|
||||||
// Register with Fs
|
// Register with Fs
|
||||||
func init() {
|
func init() {
|
||||||
fs.Register(&fs.RegInfo{
|
fs.Register(&fs.RegInfo{
|
||||||
@@ -80,6 +79,15 @@ names, or for debugging purposes.`,
|
|||||||
Default: false,
|
Default: false,
|
||||||
Hide: fs.OptionHideConfigurator,
|
Hide: fs.OptionHideConfigurator,
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: "pass_corrupted_blocks",
|
||||||
|
Help: `Pass through corrupted blocks to the output.
|
||||||
|
|
||||||
|
This is for debugging corruption problems in crypt - it shouldn't be needed normally.
|
||||||
|
`,
|
||||||
|
Default: false,
|
||||||
|
Hide: fs.OptionHideConfigurator,
|
||||||
|
Advanced: true,
|
||||||
}},
|
}},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -108,6 +116,7 @@ func newCipherForConfig(opt *Options) (Cipher, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "failed to make cipher")
|
return nil, errors.Wrap(err, "failed to make cipher")
|
||||||
}
|
}
|
||||||
|
cipher.setPassCorrupted(opt.PassCorruptedBlocks)
|
||||||
return cipher, nil
|
return cipher, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -197,6 +206,7 @@ type Options struct {
|
|||||||
Password string `config:"password"`
|
Password string `config:"password"`
|
||||||
Password2 string `config:"password2"`
|
Password2 string `config:"password2"`
|
||||||
ShowMapping bool `config:"show_mapping"`
|
ShowMapping bool `config:"show_mapping"`
|
||||||
|
PassCorruptedBlocks bool `config:"pass_corrupted_blocks"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fs represents a wrapped fs.Fs
|
// Fs represents a wrapped fs.Fs
|
||||||
|
|||||||
+76
-19
@@ -1,4 +1,7 @@
|
|||||||
// Package drive interfaces with the Google Drive object storage system
|
// Package drive interfaces with the Google Drive object storage system
|
||||||
|
|
||||||
|
// +build go1.9
|
||||||
|
|
||||||
package drive
|
package drive
|
||||||
|
|
||||||
// FIXME need to deal with some corner cases
|
// FIXME need to deal with some corner cases
|
||||||
@@ -36,6 +39,7 @@ import (
|
|||||||
"github.com/ncw/rclone/lib/dircache"
|
"github.com/ncw/rclone/lib/dircache"
|
||||||
"github.com/ncw/rclone/lib/oauthutil"
|
"github.com/ncw/rclone/lib/oauthutil"
|
||||||
"github.com/ncw/rclone/lib/pacer"
|
"github.com/ncw/rclone/lib/pacer"
|
||||||
|
"github.com/ncw/rclone/lib/readers"
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"golang.org/x/oauth2"
|
"golang.org/x/oauth2"
|
||||||
"golang.org/x/oauth2/google"
|
"golang.org/x/oauth2/google"
|
||||||
@@ -51,7 +55,8 @@ const (
|
|||||||
driveFolderType = "application/vnd.google-apps.folder"
|
driveFolderType = "application/vnd.google-apps.folder"
|
||||||
timeFormatIn = time.RFC3339
|
timeFormatIn = time.RFC3339
|
||||||
timeFormatOut = "2006-01-02T15:04:05.000000000Z07:00"
|
timeFormatOut = "2006-01-02T15:04:05.000000000Z07:00"
|
||||||
minSleep = 10 * time.Millisecond
|
defaultMinSleep = fs.Duration(100 * time.Millisecond)
|
||||||
|
defaultBurst = 100
|
||||||
defaultExportExtensions = "docx,xlsx,pptx,svg"
|
defaultExportExtensions = "docx,xlsx,pptx,svg"
|
||||||
scopePrefix = "https://www.googleapis.com/auth/"
|
scopePrefix = "https://www.googleapis.com/auth/"
|
||||||
defaultScope = "drive"
|
defaultScope = "drive"
|
||||||
@@ -122,6 +127,29 @@ var (
|
|||||||
_linkTemplates map[string]*template.Template // available link types
|
_linkTemplates map[string]*template.Template // available link types
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Parse the scopes option returning a slice of scopes
|
||||||
|
func driveScopes(scopesString string) (scopes []string) {
|
||||||
|
if scopesString == "" {
|
||||||
|
scopesString = defaultScope
|
||||||
|
}
|
||||||
|
for _, scope := range strings.Split(scopesString, ",") {
|
||||||
|
scope = strings.TrimSpace(scope)
|
||||||
|
scopes = append(scopes, scopePrefix+scope)
|
||||||
|
}
|
||||||
|
return scopes
|
||||||
|
}
|
||||||
|
|
||||||
|
// Returns true if one of the scopes was "drive.appfolder"
|
||||||
|
func driveScopesContainsAppFolder(scopes []string) bool {
|
||||||
|
for _, scope := range scopes {
|
||||||
|
if scope == scopePrefix+"drive.appfolder" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
// Register with Fs
|
// Register with Fs
|
||||||
func init() {
|
func init() {
|
||||||
fs.Register(&fs.RegInfo{
|
fs.Register(&fs.RegInfo{
|
||||||
@@ -136,18 +164,14 @@ func init() {
|
|||||||
fs.Errorf(nil, "Couldn't parse config into struct: %v", err)
|
fs.Errorf(nil, "Couldn't parse config into struct: %v", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fill in the scopes
|
// Fill in the scopes
|
||||||
if opt.Scope == "" {
|
driveConfig.Scopes = driveScopes(opt.Scope)
|
||||||
opt.Scope = defaultScope
|
// Set the root_folder_id if using drive.appfolder
|
||||||
}
|
if driveScopesContainsAppFolder(driveConfig.Scopes) {
|
||||||
driveConfig.Scopes = nil
|
m.Set("root_folder_id", "appDataFolder")
|
||||||
for _, scope := range strings.Split(opt.Scope, ",") {
|
|
||||||
driveConfig.Scopes = append(driveConfig.Scopes, scopePrefix+strings.TrimSpace(scope))
|
|
||||||
// Set the root_folder_id if using drive.appfolder
|
|
||||||
if scope == "drive.appfolder" {
|
|
||||||
m.Set("root_folder_id", "appDataFolder")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if opt.ServiceAccountFile == "" {
|
if opt.ServiceAccountFile == "" {
|
||||||
err = oauthutil.Config("drive", name, m, driveConfig)
|
err = oauthutil.Config("drive", name, m, driveConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -334,6 +358,16 @@ will download it anyway.`,
|
|||||||
Default: fs.SizeSuffix(-1),
|
Default: fs.SizeSuffix(-1),
|
||||||
Help: "If Object's are greater, use drive v2 API to download.",
|
Help: "If Object's are greater, use drive v2 API to download.",
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: "pacer_min_sleep",
|
||||||
|
Default: defaultMinSleep,
|
||||||
|
Help: "Minimum time to sleep between API calls.",
|
||||||
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: "pacer_burst",
|
||||||
|
Default: defaultBurst,
|
||||||
|
Help: "Number of API calls to allow without sleeping.",
|
||||||
|
Advanced: true,
|
||||||
}},
|
}},
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -376,6 +410,8 @@ type Options struct {
|
|||||||
AcknowledgeAbuse bool `config:"acknowledge_abuse"`
|
AcknowledgeAbuse bool `config:"acknowledge_abuse"`
|
||||||
KeepRevisionForever bool `config:"keep_revision_forever"`
|
KeepRevisionForever bool `config:"keep_revision_forever"`
|
||||||
V2DownloadMinSize fs.SizeSuffix `config:"v2_download_min_size"`
|
V2DownloadMinSize fs.SizeSuffix `config:"v2_download_min_size"`
|
||||||
|
PacerMinSleep fs.Duration `config:"pacer_min_sleep"`
|
||||||
|
PacerBurst int `config:"pacer_burst"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fs represents a remote drive server
|
// Fs represents a remote drive server
|
||||||
@@ -696,12 +732,16 @@ func parseExtensions(extensionsIn ...string) (extensions, mimeTypes []string, er
|
|||||||
|
|
||||||
// Figure out if the user wants to use a team drive
|
// Figure out if the user wants to use a team drive
|
||||||
func configTeamDrive(opt *Options, m configmap.Mapper, name string) error {
|
func configTeamDrive(opt *Options, m configmap.Mapper, name string) error {
|
||||||
|
// Stop if we are running non-interactive config
|
||||||
|
if fs.Config.AutoConfirm {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
if opt.TeamDriveID == "" {
|
if opt.TeamDriveID == "" {
|
||||||
fmt.Printf("Configure this as a team drive?\n")
|
fmt.Printf("Configure this as a team drive?\n")
|
||||||
} else {
|
} else {
|
||||||
fmt.Printf("Change current team drive ID %q?\n", opt.TeamDriveID)
|
fmt.Printf("Change current team drive ID %q?\n", opt.TeamDriveID)
|
||||||
}
|
}
|
||||||
if !config.ConfirmWithDefault(false) {
|
if !config.Confirm() {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
client, err := createOAuthClient(opt, name, m)
|
client, err := createOAuthClient(opt, name, m)
|
||||||
@@ -718,7 +758,7 @@ func configTeamDrive(opt *Options, m configmap.Mapper, name string) error {
|
|||||||
listFailed := false
|
listFailed := false
|
||||||
for {
|
for {
|
||||||
var teamDrives *drive.TeamDriveList
|
var teamDrives *drive.TeamDriveList
|
||||||
err = newPacer().Call(func() (bool, error) {
|
err = newPacer(opt).Call(func() (bool, error) {
|
||||||
teamDrives, err = listTeamDrives.Do()
|
teamDrives, err = listTeamDrives.Do()
|
||||||
return shouldRetry(err)
|
return shouldRetry(err)
|
||||||
})
|
})
|
||||||
@@ -748,12 +788,13 @@ func configTeamDrive(opt *Options, m configmap.Mapper, name string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// newPacer makes a pacer configured for drive
|
// newPacer makes a pacer configured for drive
|
||||||
func newPacer() *pacer.Pacer {
|
func newPacer(opt *Options) *pacer.Pacer {
|
||||||
return pacer.New().SetMinSleep(minSleep).SetPacer(pacer.GoogleDrivePacer)
|
return pacer.New().SetMinSleep(time.Duration(opt.PacerMinSleep)).SetBurst(opt.PacerBurst).SetPacer(pacer.GoogleDrivePacer)
|
||||||
}
|
}
|
||||||
|
|
||||||
func getServiceAccountClient(opt *Options, credentialsData []byte) (*http.Client, error) {
|
func getServiceAccountClient(opt *Options, credentialsData []byte) (*http.Client, error) {
|
||||||
conf, err := google.JWTConfigFromJSON(credentialsData, driveConfig.Scopes...)
|
scopes := driveScopes(opt.Scope)
|
||||||
|
conf, err := google.JWTConfigFromJSON(credentialsData, scopes...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "error processing credentials")
|
return nil, errors.Wrap(err, "error processing credentials")
|
||||||
}
|
}
|
||||||
@@ -852,7 +893,7 @@ func NewFs(name, path string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
name: name,
|
name: name,
|
||||||
root: root,
|
root: root,
|
||||||
opt: *opt,
|
opt: *opt,
|
||||||
pacer: newPacer(),
|
pacer: newPacer(opt),
|
||||||
}
|
}
|
||||||
f.isTeamDrive = opt.TeamDriveID != ""
|
f.isTeamDrive = opt.TeamDriveID != ""
|
||||||
f.features = (&fs.Features{
|
f.features = (&fs.Features{
|
||||||
@@ -2454,16 +2495,32 @@ func (o *documentObject) Open(options ...fs.OpenOption) (in io.ReadCloser, err e
|
|||||||
// Update the size with what we are reading as it can change from
|
// Update the size with what we are reading as it can change from
|
||||||
// the HEAD in the listing to this GET. This stops rclone marking
|
// the HEAD in the listing to this GET. This stops rclone marking
|
||||||
// the transfer as corrupted.
|
// the transfer as corrupted.
|
||||||
|
var offset, end int64 = 0, -1
|
||||||
|
var newOptions = options[:0]
|
||||||
for _, o := range options {
|
for _, o := range options {
|
||||||
|
// Note that Range requests don't work on Google docs:
|
||||||
// https://developers.google.com/drive/v3/web/manage-downloads#partial_download
|
// https://developers.google.com/drive/v3/web/manage-downloads#partial_download
|
||||||
if _, ok := o.(*fs.RangeOption); ok {
|
// So do a subset of them manually
|
||||||
return nil, errors.New("partial downloads are not supported while exporting Google Documents")
|
switch x := o.(type) {
|
||||||
|
case *fs.RangeOption:
|
||||||
|
offset, end = x.Start, x.End
|
||||||
|
case *fs.SeekOption:
|
||||||
|
offset, end = x.Offset, -1
|
||||||
|
default:
|
||||||
|
newOptions = append(newOptions, o)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
options = newOptions
|
||||||
|
if offset != 0 {
|
||||||
|
return nil, errors.New("partial downloads are not supported while exporting Google Documents")
|
||||||
|
}
|
||||||
in, err = o.baseObject.open(o.url, options...)
|
in, err = o.baseObject.open(o.url, options...)
|
||||||
if in != nil {
|
if in != nil {
|
||||||
in = &openDocumentFile{o: o, in: in}
|
in = &openDocumentFile{o: o, in: in}
|
||||||
}
|
}
|
||||||
|
if end >= 0 {
|
||||||
|
in = readers.NewLimitedReadCloser(in, end-offset+1)
|
||||||
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
func (o *linkObject) Open(options ...fs.OpenOption) (in io.ReadCloser, err error) {
|
func (o *linkObject) Open(options ...fs.OpenOption) (in io.ReadCloser, err error) {
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
// +build go1.9
|
||||||
|
|
||||||
package drive
|
package drive
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -20,6 +22,31 @@ import (
|
|||||||
"google.golang.org/api/drive/v3"
|
"google.golang.org/api/drive/v3"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestDriveScopes(t *testing.T) {
|
||||||
|
for _, test := range []struct {
|
||||||
|
in string
|
||||||
|
want []string
|
||||||
|
wantFlag bool
|
||||||
|
}{
|
||||||
|
{"", []string{
|
||||||
|
"https://www.googleapis.com/auth/drive",
|
||||||
|
}, false},
|
||||||
|
{" drive.file , drive.readonly", []string{
|
||||||
|
"https://www.googleapis.com/auth/drive.file",
|
||||||
|
"https://www.googleapis.com/auth/drive.readonly",
|
||||||
|
}, false},
|
||||||
|
{" drive.file , drive.appfolder", []string{
|
||||||
|
"https://www.googleapis.com/auth/drive.file",
|
||||||
|
"https://www.googleapis.com/auth/drive.appfolder",
|
||||||
|
}, true},
|
||||||
|
} {
|
||||||
|
got := driveScopes(test.in)
|
||||||
|
assert.Equal(t, test.want, got, test.in)
|
||||||
|
gotFlag := driveScopesContainsAppFolder(got)
|
||||||
|
assert.Equal(t, test.wantFlag, gotFlag, test.in)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
var additionalMimeTypes = map[string]string{
|
var additionalMimeTypes = map[string]string{
|
||||||
"application/vnd.ms-excel.sheet.macroenabled.12": ".xlsm",
|
"application/vnd.ms-excel.sheet.macroenabled.12": ".xlsm",
|
||||||
@@ -243,10 +270,19 @@ func (f *Fs) InternalTestDocumentLink(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fs) InternalTest(t *testing.T) {
|
func (f *Fs) InternalTest(t *testing.T) {
|
||||||
t.Run("DocumentImport", f.InternalTestDocumentImport)
|
// These tests all depend on each other so run them as nested tests
|
||||||
t.Run("DocumentUpdate", f.InternalTestDocumentUpdate)
|
t.Run("DocumentImport", func(t *testing.T) {
|
||||||
t.Run("DocumentExport", f.InternalTestDocumentExport)
|
f.InternalTestDocumentImport(t)
|
||||||
t.Run("DocumentLink", f.InternalTestDocumentLink)
|
t.Run("DocumentUpdate", func(t *testing.T) {
|
||||||
|
f.InternalTestDocumentUpdate(t)
|
||||||
|
t.Run("DocumentExport", func(t *testing.T) {
|
||||||
|
f.InternalTestDocumentExport(t)
|
||||||
|
t.Run("DocumentLink", func(t *testing.T) {
|
||||||
|
f.InternalTestDocumentLink(t)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
var _ fstests.InternalTester = (*Fs)(nil)
|
var _ fstests.InternalTester = (*Fs)(nil)
|
||||||
@@ -1,4 +1,7 @@
|
|||||||
// Test Drive filesystem interface
|
// Test Drive filesystem interface
|
||||||
|
|
||||||
|
// +build go1.9
|
||||||
|
|
||||||
package drive
|
package drive
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
// Build for unsupported platforms to stop go complaining
|
||||||
|
// about "no buildable Go source files "
|
||||||
|
|
||||||
|
// +build !go1.9
|
||||||
|
|
||||||
|
package drive
|
||||||
@@ -8,6 +8,8 @@
|
|||||||
//
|
//
|
||||||
// This contains code adapted from google.golang.org/api (C) the GO AUTHORS
|
// This contains code adapted from google.golang.org/api (C) the GO AUTHORS
|
||||||
|
|
||||||
|
// +build go1.9
|
||||||
|
|
||||||
package drive
|
package drive
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
|||||||
@@ -31,9 +31,11 @@ import (
|
|||||||
"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/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"
|
||||||
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/sharing"
|
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/sharing"
|
||||||
|
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/team"
|
||||||
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/users"
|
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/users"
|
||||||
"github.com/ncw/rclone/fs"
|
"github.com/ncw/rclone/fs"
|
||||||
"github.com/ncw/rclone/fs/config"
|
"github.com/ncw/rclone/fs/config"
|
||||||
@@ -131,13 +133,19 @@ slightly (at most 10%% for 128MB in tests) at the cost of using more
|
|||||||
memory. It can be set smaller if you are tight on memory.`, fs.SizeSuffix(maxChunkSize)),
|
memory. It can be set smaller if you are tight on memory.`, fs.SizeSuffix(maxChunkSize)),
|
||||||
Default: fs.SizeSuffix(defaultChunkSize),
|
Default: fs.SizeSuffix(defaultChunkSize),
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: "impersonate",
|
||||||
|
Help: "Impersonate this user when using a business account.",
|
||||||
|
Default: "",
|
||||||
|
Advanced: true,
|
||||||
}},
|
}},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Options defines the configuration for this backend
|
// Options defines the configuration for this backend
|
||||||
type Options struct {
|
type Options struct {
|
||||||
ChunkSize fs.SizeSuffix `config:"chunk_size"`
|
ChunkSize fs.SizeSuffix `config:"chunk_size"`
|
||||||
|
Impersonate string `config:"impersonate"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fs represents a remote dropbox server
|
// Fs represents a remote dropbox server
|
||||||
@@ -149,6 +157,7 @@ type Fs struct {
|
|||||||
srv files.Client // the connection to the dropbox server
|
srv files.Client // the connection to the dropbox server
|
||||||
sharing sharing.Client // as above, but for generating sharing links
|
sharing sharing.Client // as above, but for generating sharing links
|
||||||
users users.Client // as above, but for accessing user information
|
users users.Client // as above, but for accessing user information
|
||||||
|
team team.Client // for the Teams API
|
||||||
slashRoot string // root with "/" prefix, lowercase
|
slashRoot string // root with "/" prefix, lowercase
|
||||||
slashRootSlash string // root with "/" prefix and postfix, lowercase
|
slashRootSlash string // root with "/" prefix and postfix, lowercase
|
||||||
pacer *pacer.Pacer // To pace the API calls
|
pacer *pacer.Pacer // To pace the API calls
|
||||||
@@ -195,7 +204,16 @@ func shouldRetry(err error) (bool, error) {
|
|||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
baseErrString := errors.Cause(err).Error()
|
baseErrString := errors.Cause(err).Error()
|
||||||
// FIXME there is probably a better way of doing this!
|
// handle any official Retry-After header from Dropbox's SDK first
|
||||||
|
switch e := err.(type) {
|
||||||
|
case auth.RateLimitAPIError:
|
||||||
|
if e.RateLimitError.RetryAfter > 0 {
|
||||||
|
fs.Debugf(baseErrString, "Too many requests or write operations. Trying again in %d seconds.", e.RateLimitError.RetryAfter)
|
||||||
|
time.Sleep(time.Duration(e.RateLimitError.RetryAfter) * time.Second)
|
||||||
|
}
|
||||||
|
return true, err
|
||||||
|
}
|
||||||
|
// Keep old behaviour for backward compatibility
|
||||||
if strings.Contains(baseErrString, "too_many_write_operations") || strings.Contains(baseErrString, "too_many_requests") {
|
if strings.Contains(baseErrString, "too_many_write_operations") || strings.Contains(baseErrString, "too_many_requests") {
|
||||||
return true, err
|
return true, err
|
||||||
}
|
}
|
||||||
@@ -262,6 +280,29 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
Client: oAuthClient, // maybe???
|
Client: oAuthClient, // maybe???
|
||||||
HeaderGenerator: f.headerGenerator,
|
HeaderGenerator: f.headerGenerator,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NOTE: needs to be created pre-impersonation so we can look up the impersonated user
|
||||||
|
f.team = team.New(config)
|
||||||
|
|
||||||
|
if opt.Impersonate != "" {
|
||||||
|
|
||||||
|
user := team.UserSelectorArg{
|
||||||
|
Email: opt.Impersonate,
|
||||||
|
}
|
||||||
|
user.Tag = "email"
|
||||||
|
|
||||||
|
members := []*team.UserSelectorArg{&user}
|
||||||
|
args := team.NewMembersGetInfoArgs(members)
|
||||||
|
|
||||||
|
memberIds, err := f.team.MembersGetInfo(args)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrapf(err, "invalid dropbox team member: %q", opt.Impersonate)
|
||||||
|
}
|
||||||
|
|
||||||
|
config.AsMemberID = memberIds[0].MemberInfo.Profile.MemberProfile.TeamMemberId
|
||||||
|
}
|
||||||
|
|
||||||
f.srv = files.New(config)
|
f.srv = files.New(config)
|
||||||
f.sharing = sharing.New(config)
|
f.sharing = sharing.New(config)
|
||||||
f.users = users.New(config)
|
f.users = users.New(config)
|
||||||
|
|||||||
+15
-1
@@ -646,7 +646,21 @@ func (f *ftpReadCloser) Read(p []byte) (n int, err error) {
|
|||||||
|
|
||||||
// Close the FTP reader and return the connection to the pool
|
// Close the FTP reader and return the connection to the pool
|
||||||
func (f *ftpReadCloser) Close() error {
|
func (f *ftpReadCloser) Close() error {
|
||||||
err := f.rc.Close()
|
var err error
|
||||||
|
errchan := make(chan error, 1)
|
||||||
|
go func() {
|
||||||
|
errchan <- f.rc.Close()
|
||||||
|
}()
|
||||||
|
// Wait for Close for up to 60 seconds
|
||||||
|
timer := time.NewTimer(60 * time.Second)
|
||||||
|
select {
|
||||||
|
case err = <-errchan:
|
||||||
|
timer.Stop()
|
||||||
|
case <-timer.C:
|
||||||
|
// if timer fired assume no error but connection dead
|
||||||
|
fs.Errorf(f.f, "Timeout when waiting for connection Close")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
// if errors while reading or closing, dump the connection
|
// if errors while reading or closing, dump the connection
|
||||||
if err != nil || f.err != nil {
|
if err != nil || f.err != nil {
|
||||||
_ = f.c.Quit()
|
_ = f.c.Quit()
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
// Package googlecloudstorage provides an interface to Google Cloud Storage
|
// Package googlecloudstorage provides an interface to Google Cloud Storage
|
||||||
|
|
||||||
|
// +build go1.9
|
||||||
|
|
||||||
package googlecloudstorage
|
package googlecloudstorage
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
// Test GoogleCloudStorage filesystem interface
|
// Test GoogleCloudStorage filesystem interface
|
||||||
|
|
||||||
|
// +build go1.9
|
||||||
|
|
||||||
package googlecloudstorage_test
|
package googlecloudstorage_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
// Build for unsupported platforms to stop go complaining
|
||||||
|
// about "no buildable Go source files "
|
||||||
|
|
||||||
|
// +build !go1.9
|
||||||
|
|
||||||
|
package googlecloudstorage
|
||||||
@@ -193,7 +193,7 @@ func (f *Fs) NewObject(remote string) (fs.Object, error) {
|
|||||||
}
|
}
|
||||||
err := o.stat()
|
err := o.stat()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "Stat failed")
|
return nil, err
|
||||||
}
|
}
|
||||||
return o, nil
|
return o, nil
|
||||||
}
|
}
|
||||||
@@ -416,6 +416,9 @@ func (o *Object) url() string {
|
|||||||
func (o *Object) stat() error {
|
func (o *Object) stat() error {
|
||||||
url := o.url()
|
url := o.url()
|
||||||
res, err := o.fs.httpClient.Head(url)
|
res, err := o.fs.httpClient.Head(url)
|
||||||
|
if err == nil && res.StatusCode == http.StatusNotFound {
|
||||||
|
return fs.ErrorObjectNotFound
|
||||||
|
}
|
||||||
err = statusError(res, err)
|
err = statusError(res, err)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.Wrap(err, "failed to stat")
|
return errors.Wrap(err, "failed to stat")
|
||||||
|
|||||||
@@ -144,6 +144,11 @@ func TestNewObject(t *testing.T) {
|
|||||||
|
|
||||||
dt, ok := fstest.CheckTimeEqualWithPrecision(tObj, tFile, time.Second)
|
dt, ok := fstest.CheckTimeEqualWithPrecision(tObj, tFile, 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))
|
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
|
||||||
|
o, err = f.NewObject("not found.txt")
|
||||||
|
assert.Nil(t, o)
|
||||||
|
assert.Equal(t, fs.ErrorObjectNotFound, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestOpen(t *testing.T) {
|
func TestOpen(t *testing.T) {
|
||||||
|
|||||||
@@ -9,7 +9,10 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
// default time format for almost all request and responses
|
||||||
timeFormat = "2006-01-02-T15:04:05Z0700"
|
timeFormat = "2006-01-02-T15:04:05Z0700"
|
||||||
|
// the API server seems to use a different format
|
||||||
|
apiTimeFormat = "2006-01-02T15:04:05Z07:00"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Time represents time values in the Jottacloud API. It uses a custom RFC3339 like format.
|
// Time represents time values in the Jottacloud API. It uses a custom RFC3339 like format.
|
||||||
@@ -40,6 +43,9 @@ func (t *Time) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
|
|||||||
// Return Time string in Jottacloud format
|
// Return Time string in Jottacloud format
|
||||||
func (t Time) String() string { return time.Time(t).Format(timeFormat) }
|
func (t Time) String() string { return time.Time(t).Format(timeFormat) }
|
||||||
|
|
||||||
|
// APIString returns Time string in Jottacloud API format
|
||||||
|
func (t Time) APIString() string { return time.Time(t).Format(apiTimeFormat) }
|
||||||
|
|
||||||
// Flag is a hacky type for checking if an attribute is present
|
// Flag is a hacky type for checking if an attribute is present
|
||||||
type Flag bool
|
type Flag bool
|
||||||
|
|
||||||
@@ -58,6 +64,15 @@ func (f *Flag) MarshalXMLAttr(name xml.Name) (xml.Attr, error) {
|
|||||||
return attr, errors.New("unimplemented")
|
return attr, errors.New("unimplemented")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TokenJSON is the struct representing the HTTP response from OAuth2
|
||||||
|
// providers returning a token in JSON form.
|
||||||
|
type TokenJSON struct {
|
||||||
|
AccessToken string `json:"access_token"`
|
||||||
|
TokenType string `json:"token_type"`
|
||||||
|
RefreshToken string `json:"refresh_token"`
|
||||||
|
ExpiresIn int32 `json:"expires_in"` // at least PayPal returns string, while most return number
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
GET http://www.jottacloud.com/JFS/<account>
|
GET http://www.jottacloud.com/JFS/<account>
|
||||||
|
|
||||||
@@ -265,3 +280,37 @@ func (e *Error) Error() string {
|
|||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// AllocateFileRequest to prepare an upload to Jottacloud
|
||||||
|
type AllocateFileRequest struct {
|
||||||
|
Bytes int64 `json:"bytes"`
|
||||||
|
Created string `json:"created"`
|
||||||
|
Md5 string `json:"md5"`
|
||||||
|
Modified string `json:"modified"`
|
||||||
|
Path string `json:"path"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// AllocateFileResponse for upload requests
|
||||||
|
type AllocateFileResponse struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Path string `json:"path"`
|
||||||
|
State string `json:"state"`
|
||||||
|
UploadID string `json:"upload_id"`
|
||||||
|
UploadURL string `json:"upload_url"`
|
||||||
|
Bytes int64 `json:"bytes"`
|
||||||
|
ResumePos int64 `json:"resume_pos"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// UploadResponse after an upload
|
||||||
|
type UploadResponse struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Path string `json:"path"`
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
ContentID string `json:"content_id"`
|
||||||
|
Bytes int64 `json:"bytes"`
|
||||||
|
Md5 string `json:"md5"`
|
||||||
|
Created int64 `json:"created"`
|
||||||
|
Modified int64 `json:"modified"`
|
||||||
|
Deleted interface{} `json:"deleted"`
|
||||||
|
Mime string `json:"mime"`
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
@@ -26,22 +27,41 @@ import (
|
|||||||
"github.com/ncw/rclone/fs/fshttp"
|
"github.com/ncw/rclone/fs/fshttp"
|
||||||
"github.com/ncw/rclone/fs/hash"
|
"github.com/ncw/rclone/fs/hash"
|
||||||
"github.com/ncw/rclone/fs/walk"
|
"github.com/ncw/rclone/fs/walk"
|
||||||
|
"github.com/ncw/rclone/lib/oauthutil"
|
||||||
"github.com/ncw/rclone/lib/pacer"
|
"github.com/ncw/rclone/lib/pacer"
|
||||||
"github.com/ncw/rclone/lib/rest"
|
"github.com/ncw/rclone/lib/rest"
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
|
"golang.org/x/oauth2"
|
||||||
)
|
)
|
||||||
|
|
||||||
// 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 = "Sync"
|
defaultMountpoint = "Sync"
|
||||||
rootURL = "https://www.jottacloud.com/jfs/"
|
rootURL = "https://www.jottacloud.com/jfs/"
|
||||||
apiURL = "https://api.jottacloud.com"
|
apiURL = "https://api.jottacloud.com/files/v1/"
|
||||||
shareURL = "https://www.jottacloud.com/"
|
baseURL = "https://www.jottacloud.com/"
|
||||||
cachePrefix = "rclone-jcmd5-"
|
tokenURL = "https://api.jottacloud.com/auth/v1/token"
|
||||||
|
cachePrefix = "rclone-jcmd5-"
|
||||||
|
rcloneClientID = "nibfk8biu12ju7hpqomr8b1e40"
|
||||||
|
rcloneEncryptedClientSecret = "Vp8eAv7eVElMnQwN-kgU9cbhgApNDaMqWdlDi5qFydlQoji4JBxrGMF2"
|
||||||
|
configUsername = "user"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// Description of how to auth for this app for a personal account
|
||||||
|
oauthConfig = &oauth2.Config{
|
||||||
|
Endpoint: oauth2.Endpoint{
|
||||||
|
AuthURL: tokenURL,
|
||||||
|
TokenURL: tokenURL,
|
||||||
|
},
|
||||||
|
ClientID: rcloneClientID,
|
||||||
|
ClientSecret: obscure.MustReveal(rcloneEncryptedClientSecret),
|
||||||
|
RedirectURL: oauthutil.RedirectLocalhostURL,
|
||||||
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
// Register with Fs
|
// Register with Fs
|
||||||
@@ -50,13 +70,71 @@ func init() {
|
|||||||
Name: "jottacloud",
|
Name: "jottacloud",
|
||||||
Description: "JottaCloud",
|
Description: "JottaCloud",
|
||||||
NewFs: NewFs,
|
NewFs: NewFs,
|
||||||
|
Config: func(name string, m configmap.Mapper) {
|
||||||
|
tokenString, ok := m.Get("token")
|
||||||
|
if ok && tokenString != "" {
|
||||||
|
fmt.Printf("Already have a token - refresh?\n")
|
||||||
|
if !config.Confirm() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
username, ok := m.Get(configUsername)
|
||||||
|
if !ok {
|
||||||
|
log.Fatalf("No username defined")
|
||||||
|
}
|
||||||
|
password := config.GetPassword("Your Jottacloud password is only required during config and will not be stored.")
|
||||||
|
|
||||||
|
// prepare out token request with username and password
|
||||||
|
srv := rest.NewClient(fshttp.NewClient(fs.Config))
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
|
||||||
|
var jsonToken api.TokenJSON
|
||||||
|
resp, err := srv.CallJSON(&opts, nil, &jsonToken)
|
||||||
|
if err != nil {
|
||||||
|
// if 2fa is enabled the first request is expected to fail. we'lls 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 has 2 factor authentication enabled you will receive a verification code via SMS.\n")
|
||||||
|
fmt.Printf("Enter verification code> ")
|
||||||
|
authCode := config.ReadLine()
|
||||||
|
authCode = strings.Replace(authCode, "-", "", -1) // the sms received contains a pair of 3 digit numbers seperated by '-' but wants a single 6 digit number
|
||||||
|
opts.ExtraHeaders = make(map[string]string)
|
||||||
|
opts.ExtraHeaders["X-Jottacloud-Otp"] = authCode
|
||||||
|
resp, err = srv.CallJSON(&opts, nil, &jsonToken)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to get resource token: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var token oauth2.Token
|
||||||
|
token.AccessToken = jsonToken.AccessToken
|
||||||
|
token.RefreshToken = jsonToken.RefreshToken
|
||||||
|
token.TokenType = jsonToken.TokenType
|
||||||
|
token.Expiry = time.Now().Add(time.Duration(jsonToken.ExpiresIn) * time.Second)
|
||||||
|
|
||||||
|
// finally save them in the config
|
||||||
|
err = oauthutil.PutToken(name, m, &token, true)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Error while setting token: %s", err)
|
||||||
|
}
|
||||||
|
},
|
||||||
Options: []fs.Option{{
|
Options: []fs.Option{{
|
||||||
Name: "user",
|
Name: configUsername,
|
||||||
Help: "User Name",
|
Help: "User Name:",
|
||||||
}, {
|
|
||||||
Name: "pass",
|
|
||||||
Help: "Password.",
|
|
||||||
IsPassword: true,
|
|
||||||
}, {
|
}, {
|
||||||
Name: "mountpoint",
|
Name: "mountpoint",
|
||||||
Help: "The mountpoint to use.",
|
Help: "The mountpoint to use.",
|
||||||
@@ -83,6 +161,11 @@ func init() {
|
|||||||
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: "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.",
|
||||||
Default: false,
|
Default: false,
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: "upload_resume_limit",
|
||||||
|
Help: "Files bigger than this can be resumed if the upload failes.",
|
||||||
|
Default: fs.SizeSuffix(10 * 1024 * 1024),
|
||||||
|
Advanced: true,
|
||||||
}},
|
}},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -90,23 +173,25 @@ func init() {
|
|||||||
// Options defines the configuration for this backend
|
// Options defines the configuration for this backend
|
||||||
type Options struct {
|
type Options struct {
|
||||||
User string `config:"user"`
|
User string `config:"user"`
|
||||||
Pass string `config:"pass"`
|
|
||||||
Mountpoint string `config:"mountpoint"`
|
Mountpoint string `config:"mountpoint"`
|
||||||
MD5MemoryThreshold fs.SizeSuffix `config:"md5_memory_limit"`
|
MD5MemoryThreshold fs.SizeSuffix `config:"md5_memory_limit"`
|
||||||
HardDelete bool `config:"hard_delete"`
|
HardDelete bool `config:"hard_delete"`
|
||||||
Unlink bool `config:"unlink"`
|
Unlink bool `config:"unlink"`
|
||||||
|
UploadThreshold fs.SizeSuffix `config:"upload_resume_limit"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fs represents a remote jottacloud
|
// Fs represents a remote jottacloud
|
||||||
type Fs struct {
|
type Fs struct {
|
||||||
name string
|
name string
|
||||||
root string
|
root string
|
||||||
user string
|
user string
|
||||||
opt Options
|
opt Options
|
||||||
features *fs.Features
|
features *fs.Features
|
||||||
endpointURL string
|
endpointURL string
|
||||||
srv *rest.Client
|
srv *rest.Client
|
||||||
pacer *pacer.Pacer
|
apiSrv *rest.Client
|
||||||
|
pacer *pacer.Pacer
|
||||||
|
tokenRenewer *oauthutil.Renew // renew the token on expiry
|
||||||
}
|
}
|
||||||
|
|
||||||
// Object describes a jottacloud object
|
// Object describes a jottacloud object
|
||||||
@@ -261,6 +346,29 @@ func (o *Object) filePath() string {
|
|||||||
return o.fs.filePath(o.remote)
|
return o.fs.filePath(o.remote)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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 tokenURL == req.URL.String() {
|
||||||
|
// read the entire body
|
||||||
|
refreshBody, err := ioutil.ReadAll(req.Body)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_ = req.Body.Close()
|
||||||
|
|
||||||
|
// make the refesh 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) {
|
||||||
// Parse config into Options struct
|
// Parse config into Options struct
|
||||||
@@ -273,25 +381,29 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
rootIsDir := strings.HasSuffix(root, "/")
|
rootIsDir := strings.HasSuffix(root, "/")
|
||||||
root = parsePath(root)
|
root = parsePath(root)
|
||||||
|
|
||||||
user := config.FileGet(name, "user")
|
// the oauth client for the api servers needs
|
||||||
pass := config.FileGet(name, "pass")
|
// a filter to fix the grant_type issues (see above)
|
||||||
|
baseClient := fshttp.NewClient(fs.Config)
|
||||||
if opt.Pass != "" {
|
if do, ok := baseClient.Transport.(interface {
|
||||||
var err error
|
SetRequestFilter(f func(req *http.Request))
|
||||||
opt.Pass, err = obscure.Reveal(opt.Pass)
|
}); ok {
|
||||||
if err != nil {
|
do.SetRequestFilter(grantTypeFilter)
|
||||||
return nil, errors.Wrap(err, "couldn't decrypt password")
|
} else {
|
||||||
}
|
fs.Debugf(name+":", "Couldn't add request filter - uploads will fail")
|
||||||
|
}
|
||||||
|
oAuthClient, ts, err := oauthutil.NewClientWithBaseClient(name, m, oauthConfig, baseClient)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "Failed to configure Jottacloud oauth client")
|
||||||
}
|
}
|
||||||
|
|
||||||
f := &Fs{
|
f := &Fs{
|
||||||
name: name,
|
name: name,
|
||||||
root: root,
|
root: root,
|
||||||
user: opt.User,
|
user: opt.User,
|
||||||
opt: *opt,
|
opt: *opt,
|
||||||
//endpointURL: rest.URLPathEscape(path.Join(user, defaultDevice, opt.Mountpoint)),
|
srv: rest.NewClient(oAuthClient).SetRoot(rootURL),
|
||||||
srv: rest.NewClient(fshttp.NewClient(fs.Config)).SetRoot(rootURL),
|
apiSrv: rest.NewClient(oAuthClient).SetRoot(apiURL),
|
||||||
pacer: pacer.New().SetMinSleep(minSleep).SetMaxSleep(maxSleep).SetDecayConstant(decayConstant),
|
pacer: pacer.New().SetMinSleep(minSleep).SetMaxSleep(maxSleep).SetDecayConstant(decayConstant),
|
||||||
}
|
}
|
||||||
f.features = (&fs.Features{
|
f.features = (&fs.Features{
|
||||||
CaseInsensitive: true,
|
CaseInsensitive: true,
|
||||||
@@ -299,14 +411,14 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
ReadMimeType: true,
|
ReadMimeType: true,
|
||||||
WriteMimeType: true,
|
WriteMimeType: true,
|
||||||
}).Fill(f)
|
}).Fill(f)
|
||||||
|
|
||||||
if user == "" || pass == "" {
|
|
||||||
return nil, errors.New("jottacloud needs user and password")
|
|
||||||
}
|
|
||||||
|
|
||||||
f.srv.SetUserPass(opt.User, opt.Pass)
|
|
||||||
f.srv.SetErrorHandler(errorHandler)
|
f.srv.SetErrorHandler(errorHandler)
|
||||||
|
|
||||||
|
// Renew the token in the background
|
||||||
|
f.tokenRenewer = oauthutil.NewRenew(f.String(), ts, func() error {
|
||||||
|
_, err := f.readMetaDataForPath("")
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
|
||||||
err = f.setEndpointURL(opt.Mountpoint)
|
err = f.setEndpointURL(opt.Mountpoint)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "couldn't get account info")
|
return nil, errors.Wrap(err, "couldn't get account info")
|
||||||
@@ -331,7 +443,6 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
// return an error with an fs which points to the parent
|
// return an error with an fs which points to the parent
|
||||||
return f, fs.ErrorIsFile
|
return f, fs.ErrorIsFile
|
||||||
}
|
}
|
||||||
|
|
||||||
return f, nil
|
return f, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -348,7 +459,7 @@ func (f *Fs) newObjectWithInfo(remote string, info *api.JottaFile) (fs.Object, e
|
|||||||
// Set info
|
// Set info
|
||||||
err = o.setMetaData(info)
|
err = o.setMetaData(info)
|
||||||
} else {
|
} else {
|
||||||
err = o.readMetaData() // reads info and meta, returning an error
|
err = o.readMetaData(false) // reads info and meta, returning an error
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -396,7 +507,7 @@ func (f *Fs) CreateDir(path string) (jf *api.JottaFolder, err 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(dir string) (entries fs.DirEntries, err error) {
|
func (f *Fs) List(dir string) (entries fs.DirEntries, err error) {
|
||||||
//fmt.Printf("List: %s\n", dir)
|
//fmt.Printf("List: %s\n", f.filePath(dir))
|
||||||
opts := rest.Opts{
|
opts := rest.Opts{
|
||||||
Method: "GET",
|
Method: "GET",
|
||||||
Path: f.filePath(dir),
|
Path: f.filePath(dir),
|
||||||
@@ -676,7 +787,6 @@ func (f *Fs) copyOrMove(method, src, dest string) (info *api.JottaFile, err erro
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return info, nil
|
return info, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -824,7 +934,7 @@ func (f *Fs) PublicLink(remote string) (link string, err error) {
|
|||||||
if result.PublicSharePath == "" {
|
if result.PublicSharePath == "" {
|
||||||
return "", errors.New("couldn't create public link - no link path received")
|
return "", errors.New("couldn't create public link - no link path received")
|
||||||
}
|
}
|
||||||
link = path.Join(shareURL, result.PublicSharePath)
|
link = path.Join(baseURL, result.PublicSharePath)
|
||||||
return link, nil
|
return link, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -880,7 +990,7 @@ func (o *Object) Hash(t hash.Type) (string, error) {
|
|||||||
|
|
||||||
// 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 {
|
||||||
err := o.readMetaData()
|
err := o.readMetaData(false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fs.Logf(o, "Failed to read metadata: %v", err)
|
fs.Logf(o, "Failed to read metadata: %v", err)
|
||||||
return 0
|
return 0
|
||||||
@@ -903,14 +1013,17 @@ func (o *Object) setMetaData(info *api.JottaFile) (err error) {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *Object) readMetaData() (err error) {
|
func (o *Object) readMetaData(force bool) (err error) {
|
||||||
if o.hasMetaData {
|
if o.hasMetaData && !force {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
info, err := o.fs.readMetaDataForPath(o.remote)
|
info, err := o.fs.readMetaDataForPath(o.remote)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
if info.Deleted {
|
||||||
|
return fs.ErrorObjectNotFound
|
||||||
|
}
|
||||||
return o.setMetaData(info)
|
return o.setMetaData(info)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -919,7 +1032,7 @@ func (o *Object) readMetaData() (err error) {
|
|||||||
// It attempts to read the objects mtime and if that isn't present the
|
// It attempts to read the objects mtime and if that isn't present the
|
||||||
// LastModified returned in the http headers
|
// LastModified returned in the http headers
|
||||||
func (o *Object) ModTime() time.Time {
|
func (o *Object) ModTime() time.Time {
|
||||||
err := o.readMetaData()
|
err := o.readMetaData(false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fs.Logf(o, "Failed to read metadata: %v", err)
|
fs.Logf(o, "Failed to read metadata: %v", err)
|
||||||
return time.Now()
|
return time.Now()
|
||||||
@@ -1040,43 +1153,74 @@ func (o *Object) Update(in io.Reader, src fs.ObjectInfo, options ...fs.OpenOptio
|
|||||||
in = wrap(in)
|
in = wrap(in)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// use the api to allocate the file first and get resume / deduplication info
|
||||||
var resp *http.Response
|
var resp *http.Response
|
||||||
var result api.JottaFile
|
|
||||||
opts := rest.Opts{
|
opts := rest.Opts{
|
||||||
Method: "POST",
|
Method: "POST",
|
||||||
Path: o.filePath(),
|
Path: "allocate",
|
||||||
Body: in,
|
ExtraHeaders: make(map[string]string),
|
||||||
ContentType: fs.MimeType(src),
|
}
|
||||||
ContentLength: &size,
|
fileDate := api.Time(src.ModTime()).APIString()
|
||||||
ExtraHeaders: make(map[string]string),
|
|
||||||
Parameters: url.Values{},
|
// the allocate request
|
||||||
|
var request = api.AllocateFileRequest{
|
||||||
|
Bytes: size,
|
||||||
|
Created: fileDate,
|
||||||
|
Modified: fileDate,
|
||||||
|
Md5: md5String,
|
||||||
|
Path: path.Join(o.fs.opt.Mountpoint, replaceReservedChars(path.Join(o.fs.root, o.remote))),
|
||||||
}
|
}
|
||||||
|
|
||||||
opts.ExtraHeaders["JMd5"] = md5String
|
// send it
|
||||||
opts.Parameters.Set("cphash", md5String)
|
var response api.AllocateFileResponse
|
||||||
opts.ExtraHeaders["JSize"] = strconv.FormatInt(size, 10)
|
|
||||||
// opts.ExtraHeaders["JCreated"] = api.Time(src.ModTime()).String()
|
|
||||||
opts.ExtraHeaders["JModified"] = api.Time(src.ModTime()).String()
|
|
||||||
|
|
||||||
// Parameters observed in other implementations
|
|
||||||
//opts.ExtraHeaders["X-Jfs-DeviceName"] = "Jotta"
|
|
||||||
//opts.ExtraHeaders["X-Jfs-Devicename-Base64"] = ""
|
|
||||||
//opts.ExtraHeaders["X-Jftp-Version"] = "2.4" this appears to be the current version
|
|
||||||
//opts.ExtraHeaders["jx_csid"] = ""
|
|
||||||
//opts.ExtraHeaders["jx_lisence"] = ""
|
|
||||||
|
|
||||||
opts.Parameters.Set("umode", "nomultipart")
|
|
||||||
|
|
||||||
err = o.fs.pacer.CallNoRetry(func() (bool, error) {
|
err = o.fs.pacer.CallNoRetry(func() (bool, error) {
|
||||||
resp, err = o.fs.srv.CallXML(&opts, nil, &result)
|
resp, err = o.fs.apiSrv.CallJSON(&opts, &request, &response)
|
||||||
return shouldRetry(resp, err)
|
return shouldRetry(resp, err)
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Check returned Metadata? Timeout on big uploads?
|
// If the file state is INCOMPLETE and CORRPUT, try to upload a then
|
||||||
return o.setMetaData(&result)
|
if response.State != "COMPLETED" {
|
||||||
|
// how much do we still have to upload?
|
||||||
|
remainingBytes := size - response.ResumePos
|
||||||
|
opts = rest.Opts{
|
||||||
|
Method: "POST",
|
||||||
|
RootURL: response.UploadURL,
|
||||||
|
ContentLength: &remainingBytes,
|
||||||
|
ContentType: "application/octet-stream",
|
||||||
|
Body: in,
|
||||||
|
ExtraHeaders: make(map[string]string),
|
||||||
|
}
|
||||||
|
if response.ResumePos != 0 {
|
||||||
|
opts.ExtraHeaders["Range"] = "bytes=" + strconv.FormatInt(response.ResumePos, 10) + "-" + strconv.FormatInt(size-1, 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
// copy the already uploaded bytes into the trash :)
|
||||||
|
var result api.UploadResponse
|
||||||
|
_, err = io.CopyN(ioutil.Discard, in, response.ResumePos)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// send the remaining bytes
|
||||||
|
resp, err = o.fs.apiSrv.CallJSON(&opts, nil, &result)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// finally update the meta data
|
||||||
|
o.hasMetaData = true
|
||||||
|
o.size = int64(result.Bytes)
|
||||||
|
o.md5 = result.Md5
|
||||||
|
o.modTime = time.Unix(result.Modified/1000, 0)
|
||||||
|
} else {
|
||||||
|
// If the file state is COMPLETE we don't need to upload it because the file was allready found but we still ned to update our metadata
|
||||||
|
return o.readMetaData(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Remove an object
|
// Remove an object
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
// +build windows plan9
|
||||||
|
|
||||||
|
package local
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const haveLChtimes = false
|
||||||
|
|
||||||
|
// lChtimes changes the access and modification times of the named
|
||||||
|
// link, similar to the Unix utime() or utimes() functions.
|
||||||
|
//
|
||||||
|
// The underlying filesystem may truncate or round the values to a
|
||||||
|
// less precise time unit.
|
||||||
|
// If there is an error, it will be of type *PathError.
|
||||||
|
func lChtimes(name string, atime time.Time, mtime time.Time) error {
|
||||||
|
// Does nothing
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
// +build !windows,!plan9
|
||||||
|
|
||||||
|
package local
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
|
)
|
||||||
|
|
||||||
|
const haveLChtimes = true
|
||||||
|
|
||||||
|
// lChtimes changes the access and modification times of the named
|
||||||
|
// link, similar to the Unix utime() or utimes() functions.
|
||||||
|
//
|
||||||
|
// The underlying filesystem may truncate or round the values to a
|
||||||
|
// less precise time unit.
|
||||||
|
// If there is an error, it will be of type *PathError.
|
||||||
|
func lChtimes(name string, atime time.Time, mtime time.Time) error {
|
||||||
|
var utimes [2]unix.Timespec
|
||||||
|
utimes[0] = unix.NsecToTimespec(atime.UnixNano())
|
||||||
|
utimes[1] = unix.NsecToTimespec(mtime.UnixNano())
|
||||||
|
if e := unix.UtimesNanoAt(unix.AT_FDCWD, name, utimes[0:], unix.AT_SYMLINK_NOFOLLOW); e != nil {
|
||||||
|
return &os.PathError{Op: "lchtimes", Path: name, Err: e}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
+157
-31
@@ -2,6 +2,7 @@
|
|||||||
package local
|
package local
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
@@ -21,12 +22,14 @@ import (
|
|||||||
"github.com/ncw/rclone/fs/config/configstruct"
|
"github.com/ncw/rclone/fs/config/configstruct"
|
||||||
"github.com/ncw/rclone/fs/fserrors"
|
"github.com/ncw/rclone/fs/fserrors"
|
||||||
"github.com/ncw/rclone/fs/hash"
|
"github.com/ncw/rclone/fs/hash"
|
||||||
|
"github.com/ncw/rclone/lib/file"
|
||||||
"github.com/ncw/rclone/lib/readers"
|
"github.com/ncw/rclone/lib/readers"
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Constants
|
// Constants
|
||||||
const devUnset = 0xdeadbeefcafebabe // a device id meaning it is unset
|
const devUnset = 0xdeadbeefcafebabe // a device id meaning it is unset
|
||||||
|
const linkSuffix = ".rclonelink" // The suffix added to a translated symbolic link
|
||||||
|
|
||||||
// Register with Fs
|
// Register with Fs
|
||||||
func init() {
|
func init() {
|
||||||
@@ -48,6 +51,13 @@ func init() {
|
|||||||
NoPrefix: true,
|
NoPrefix: true,
|
||||||
ShortOpt: "L",
|
ShortOpt: "L",
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: "links",
|
||||||
|
Help: "Translate symlinks to/from regular files with a '" + linkSuffix + "' extension",
|
||||||
|
Default: false,
|
||||||
|
NoPrefix: true,
|
||||||
|
ShortOpt: "l",
|
||||||
|
Advanced: true,
|
||||||
}, {
|
}, {
|
||||||
Name: "skip_links",
|
Name: "skip_links",
|
||||||
Help: `Don't warn about skipped symlinks.
|
Help: `Don't warn about skipped symlinks.
|
||||||
@@ -92,12 +102,13 @@ check can be disabled with this flag.`,
|
|||||||
|
|
||||||
// Options defines the configuration for this backend
|
// Options defines the configuration for this backend
|
||||||
type Options struct {
|
type Options struct {
|
||||||
FollowSymlinks bool `config:"copy_links"`
|
FollowSymlinks bool `config:"copy_links"`
|
||||||
SkipSymlinks bool `config:"skip_links"`
|
TranslateSymlinks bool `config:"links"`
|
||||||
NoUTFNorm bool `config:"no_unicode_normalization"`
|
SkipSymlinks bool `config:"skip_links"`
|
||||||
NoCheckUpdated bool `config:"no_check_updated"`
|
NoUTFNorm bool `config:"no_unicode_normalization"`
|
||||||
NoUNC bool `config:"nounc"`
|
NoCheckUpdated bool `config:"no_check_updated"`
|
||||||
OneFileSystem bool `config:"one_file_system"`
|
NoUNC bool `config:"nounc"`
|
||||||
|
OneFileSystem bool `config:"one_file_system"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fs represents a local filesystem rooted at root
|
// Fs represents a local filesystem rooted at root
|
||||||
@@ -119,17 +130,20 @@ type Fs struct {
|
|||||||
|
|
||||||
// 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 - properly UTF-8 encoded - for rclone
|
remote string // The remote path - properly UTF-8 encoded - for rclone
|
||||||
path string // The local path - may not be properly UTF-8 encoded - for OS
|
path string // The local path - may not be properly UTF-8 encoded - for OS
|
||||||
size int64 // file metadata - always present
|
size int64 // file metadata - always present
|
||||||
mode os.FileMode
|
mode os.FileMode
|
||||||
modTime time.Time
|
modTime time.Time
|
||||||
hashes map[hash.Type]string // Hashes
|
hashes map[hash.Type]string // Hashes
|
||||||
|
translatedLink bool // Is this object a translated link
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------
|
// ------------------------------------------------------------
|
||||||
|
|
||||||
|
var errLinksAndCopyLinks = errors.New("can't use -l/--links with -L/--copy-links")
|
||||||
|
|
||||||
// NewFs constructs an Fs from the path
|
// NewFs constructs an Fs from the path
|
||||||
func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
||||||
// Parse config into Options struct
|
// Parse config into Options struct
|
||||||
@@ -138,6 +152,9 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if opt.TranslateSymlinks && opt.FollowSymlinks {
|
||||||
|
return nil, errLinksAndCopyLinks
|
||||||
|
}
|
||||||
|
|
||||||
if opt.NoUTFNorm {
|
if opt.NoUTFNorm {
|
||||||
fs.Errorf(nil, "The --local-no-unicode-normalization flag is deprecated and will be removed")
|
fs.Errorf(nil, "The --local-no-unicode-normalization flag is deprecated and will be removed")
|
||||||
@@ -165,7 +182,7 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
if err == nil {
|
if err == nil {
|
||||||
f.dev = readDevice(fi, f.opt.OneFileSystem)
|
f.dev = readDevice(fi, f.opt.OneFileSystem)
|
||||||
}
|
}
|
||||||
if err == nil && fi.Mode().IsRegular() {
|
if err == nil && f.isRegular(fi.Mode()) {
|
||||||
// It is a file, so use the parent as the root
|
// It is a file, so use the parent as the root
|
||||||
f.root = filepath.Dir(f.root)
|
f.root = filepath.Dir(f.root)
|
||||||
// return an error with an fs which points to the parent
|
// return an error with an fs which points to the parent
|
||||||
@@ -174,6 +191,20 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
return f, nil
|
return f, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Determine whether a file is a 'regular' file,
|
||||||
|
// Symlinks are regular files, only if the TranslateSymlink
|
||||||
|
// option is in-effect
|
||||||
|
func (f *Fs) isRegular(mode os.FileMode) bool {
|
||||||
|
if !f.opt.TranslateSymlinks {
|
||||||
|
return mode.IsRegular()
|
||||||
|
}
|
||||||
|
|
||||||
|
// fi.Mode().IsRegular() tests that all mode bits are zero
|
||||||
|
// Since symlinks are accepted, test that all other bits are zero,
|
||||||
|
// except the symlink bit
|
||||||
|
return mode&os.ModeType&^os.ModeSymlink == 0
|
||||||
|
}
|
||||||
|
|
||||||
// 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
|
||||||
@@ -204,18 +235,38 @@ func (f *Fs) caseInsensitive() bool {
|
|||||||
return runtime.GOOS == "windows" || runtime.GOOS == "darwin"
|
return runtime.GOOS == "windows" || runtime.GOOS == "darwin"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// translateLink checks whether the remote is a translated link
|
||||||
|
// and returns a new path, removing the suffix as needed,
|
||||||
|
// It also returns whether this is a translated link at all
|
||||||
|
//
|
||||||
|
// for regular files, dstPath is returned unchanged
|
||||||
|
func translateLink(remote, dstPath string) (newDstPath string, isTranslatedLink bool) {
|
||||||
|
isTranslatedLink = strings.HasSuffix(remote, linkSuffix)
|
||||||
|
newDstPath = strings.TrimSuffix(dstPath, linkSuffix)
|
||||||
|
return newDstPath, isTranslatedLink
|
||||||
|
}
|
||||||
|
|
||||||
// newObject makes a half completed Object
|
// newObject makes a half completed Object
|
||||||
//
|
//
|
||||||
// if dstPath is empty then it is made from remote
|
// if dstPath is empty then it is made from remote
|
||||||
func (f *Fs) newObject(remote, dstPath string) *Object {
|
func (f *Fs) newObject(remote, dstPath string) *Object {
|
||||||
|
translatedLink := false
|
||||||
|
|
||||||
if dstPath == "" {
|
if dstPath == "" {
|
||||||
dstPath = f.cleanPath(filepath.Join(f.root, remote))
|
dstPath = f.cleanPath(filepath.Join(f.root, remote))
|
||||||
}
|
}
|
||||||
remote = f.cleanRemote(remote)
|
remote = f.cleanRemote(remote)
|
||||||
|
|
||||||
|
if f.opt.TranslateSymlinks {
|
||||||
|
// Possibly receive a new name for dstPath
|
||||||
|
dstPath, translatedLink = translateLink(remote, dstPath)
|
||||||
|
}
|
||||||
|
|
||||||
return &Object{
|
return &Object{
|
||||||
fs: f,
|
fs: f,
|
||||||
remote: remote,
|
remote: remote,
|
||||||
path: dstPath,
|
path: dstPath,
|
||||||
|
translatedLink: translatedLink,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -237,6 +288,11 @@ func (f *Fs) newObjectWithInfo(remote, dstPath string, info os.FileInfo) (fs.Obj
|
|||||||
}
|
}
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
// Handle the odd case, that a symlink was specfied by name without the link suffix
|
||||||
|
if o.fs.opt.TranslateSymlinks && o.mode&os.ModeSymlink != 0 && !o.translatedLink {
|
||||||
|
return nil, fs.ErrorObjectNotFound
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
if o.mode.IsDir() {
|
if o.mode.IsDir() {
|
||||||
return nil, errors.Wrapf(fs.ErrorNotAFile, "%q", remote)
|
return nil, errors.Wrapf(fs.ErrorNotAFile, "%q", remote)
|
||||||
@@ -260,6 +316,7 @@ func (f *Fs) NewObject(remote string) (fs.Object, error) {
|
|||||||
// This should return ErrDirNotFound if the directory isn't
|
// This should return ErrDirNotFound if the directory isn't
|
||||||
// found.
|
// found.
|
||||||
func (f *Fs) List(dir string) (entries fs.DirEntries, err error) {
|
func (f *Fs) List(dir string) (entries fs.DirEntries, err error) {
|
||||||
|
|
||||||
dir = f.dirNames.Load(dir)
|
dir = f.dirNames.Load(dir)
|
||||||
fsDirPath := f.cleanPath(filepath.Join(f.root, dir))
|
fsDirPath := f.cleanPath(filepath.Join(f.root, dir))
|
||||||
remote := f.cleanRemote(dir)
|
remote := f.cleanRemote(dir)
|
||||||
@@ -316,6 +373,10 @@ func (f *Fs) List(dir string) (entries fs.DirEntries, err error) {
|
|||||||
entries = append(entries, d)
|
entries = append(entries, d)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
// Check whether this link should be translated
|
||||||
|
if f.opt.TranslateSymlinks && fi.Mode()&os.ModeSymlink != 0 {
|
||||||
|
newRemote += linkSuffix
|
||||||
|
}
|
||||||
fso, err := f.newObjectWithInfo(newRemote, newPath, fi)
|
fso, err := f.newObjectWithInfo(newRemote, newPath, fi)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -529,7 +590,7 @@ func (f *Fs) Move(src fs.Object, remote string) (fs.Object, error) {
|
|||||||
// OK
|
// OK
|
||||||
} else if err != nil {
|
} else if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
} else if !dstObj.mode.IsRegular() {
|
} else if !dstObj.fs.isRegular(dstObj.mode) {
|
||||||
// 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")
|
||||||
}
|
}
|
||||||
@@ -651,7 +712,13 @@ func (o *Object) Hash(r hash.Type) (string, error) {
|
|||||||
o.fs.objectHashesMu.Unlock()
|
o.fs.objectHashesMu.Unlock()
|
||||||
|
|
||||||
if !o.modTime.Equal(oldtime) || oldsize != o.size || hashes == nil {
|
if !o.modTime.Equal(oldtime) || oldsize != o.size || hashes == nil {
|
||||||
in, err := os.Open(o.path)
|
var in io.ReadCloser
|
||||||
|
|
||||||
|
if !o.translatedLink {
|
||||||
|
in, err = file.Open(o.path)
|
||||||
|
} else {
|
||||||
|
in, err = o.openTranslatedLink(0, -1)
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", errors.Wrap(err, "hash: failed to open")
|
return "", errors.Wrap(err, "hash: failed to open")
|
||||||
}
|
}
|
||||||
@@ -682,7 +749,12 @@ func (o *Object) ModTime() time.Time {
|
|||||||
|
|
||||||
// SetModTime sets the modification time of the local fs object
|
// SetModTime sets the modification time of the local fs object
|
||||||
func (o *Object) SetModTime(modTime time.Time) error {
|
func (o *Object) SetModTime(modTime time.Time) error {
|
||||||
err := os.Chtimes(o.path, modTime, modTime)
|
var err error
|
||||||
|
if o.translatedLink {
|
||||||
|
err = lChtimes(o.path, modTime, modTime)
|
||||||
|
} else {
|
||||||
|
err = os.Chtimes(o.path, modTime, modTime)
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -700,7 +772,7 @@ func (o *Object) Storable() bool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
mode := o.mode
|
mode := o.mode
|
||||||
if mode&os.ModeSymlink != 0 {
|
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")
|
||||||
}
|
}
|
||||||
@@ -761,6 +833,16 @@ func (file *localOpenFile) Close() (err error) {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Returns a ReadCloser() object that contains the contents of a symbolic link
|
||||||
|
func (o *Object) openTranslatedLink(offset, limit int64) (lrc io.ReadCloser, err error) {
|
||||||
|
// Read the link and return the destination it as the contents of the object
|
||||||
|
linkdst, err := os.Readlink(o.path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return readers.NewLimitedReadCloser(ioutil.NopCloser(strings.NewReader(linkdst[offset:])), limit), nil
|
||||||
|
}
|
||||||
|
|
||||||
// Open an object for read
|
// Open an object for read
|
||||||
func (o *Object) Open(options ...fs.OpenOption) (in io.ReadCloser, err error) {
|
func (o *Object) Open(options ...fs.OpenOption) (in io.ReadCloser, err error) {
|
||||||
var offset, limit int64 = 0, -1
|
var offset, limit int64 = 0, -1
|
||||||
@@ -780,7 +862,12 @@ func (o *Object) Open(options ...fs.OpenOption) (in io.ReadCloser, err error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fd, err := os.Open(o.path)
|
// Handle a translated link
|
||||||
|
if o.translatedLink {
|
||||||
|
return o.openTranslatedLink(offset, limit)
|
||||||
|
}
|
||||||
|
|
||||||
|
fd, err := file.Open(o.path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -811,8 +898,19 @@ func (o *Object) mkdirAll() error {
|
|||||||
return os.MkdirAll(dir, 0777)
|
return os.MkdirAll(dir, 0777)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type nopWriterCloser struct {
|
||||||
|
*bytes.Buffer
|
||||||
|
}
|
||||||
|
|
||||||
|
func (nwc nopWriterCloser) Close() error {
|
||||||
|
// noop
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// Update the object from in with modTime and size
|
// Update the object from in with modTime and size
|
||||||
func (o *Object) Update(in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) error {
|
func (o *Object) Update(in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) error {
|
||||||
|
var out io.WriteCloser
|
||||||
|
|
||||||
hashes := hash.Supported
|
hashes := hash.Supported
|
||||||
for _, option := range options {
|
for _, option := range options {
|
||||||
switch x := option.(type) {
|
switch x := option.(type) {
|
||||||
@@ -826,15 +924,23 @@ func (o *Object) Update(in io.Reader, src fs.ObjectInfo, options ...fs.OpenOptio
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
out, err := os.OpenFile(o.path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
|
var symlinkData bytes.Buffer
|
||||||
if err != nil {
|
// If the object is a regular file, create it.
|
||||||
return err
|
// If it is a translated link, just read in the contents, and
|
||||||
}
|
// then create a symlink
|
||||||
|
if !o.translatedLink {
|
||||||
// Pre-allocate the file for performance reasons
|
f, err := file.OpenFile(o.path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
|
||||||
err = preAllocate(src.Size(), out)
|
if err != nil {
|
||||||
if err != nil {
|
return err
|
||||||
fs.Debugf(o, "Failed to pre-allocate: %v", err)
|
}
|
||||||
|
// Pre-allocate the file for performance reasons
|
||||||
|
err = preAllocate(src.Size(), f)
|
||||||
|
if err != nil {
|
||||||
|
fs.Debugf(o, "Failed to pre-allocate: %v", err)
|
||||||
|
}
|
||||||
|
out = f
|
||||||
|
} else {
|
||||||
|
out = nopWriterCloser{&symlinkData}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Calculate the hash of the object we are reading as we go along
|
// Calculate the hash of the object we are reading as we go along
|
||||||
@@ -849,6 +955,26 @@ func (o *Object) Update(in io.Reader, src fs.ObjectInfo, options ...fs.OpenOptio
|
|||||||
if err == nil {
|
if err == nil {
|
||||||
err = closeErr
|
err = closeErr
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if o.translatedLink {
|
||||||
|
if err == nil {
|
||||||
|
// Remove any current symlink or file, if one exsits
|
||||||
|
if _, err := os.Lstat(o.path); err == nil {
|
||||||
|
if removeErr := os.Remove(o.path); removeErr != nil {
|
||||||
|
fs.Errorf(o, "Failed to remove previous file: %v", removeErr)
|
||||||
|
return removeErr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Use the contents for the copied object to create a symlink
|
||||||
|
err = os.Symlink(symlinkData.String(), o.path)
|
||||||
|
}
|
||||||
|
|
||||||
|
// only continue if symlink creation succeeded
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fs.Logf(o, "Removing partially written file on error: %v", err)
|
fs.Logf(o, "Removing partially written file on error: %v", err)
|
||||||
if removeErr := os.Remove(o.path); removeErr != nil {
|
if removeErr := os.Remove(o.path); removeErr != nil {
|
||||||
|
|||||||
@@ -1,13 +1,19 @@
|
|||||||
package local
|
package local
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"io/ioutil"
|
||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/ncw/rclone/fs"
|
||||||
|
"github.com/ncw/rclone/fs/config/configmap"
|
||||||
"github.com/ncw/rclone/fs/hash"
|
"github.com/ncw/rclone/fs/hash"
|
||||||
"github.com/ncw/rclone/fstest"
|
"github.com/ncw/rclone/fstest"
|
||||||
|
"github.com/ncw/rclone/lib/file"
|
||||||
"github.com/ncw/rclone/lib/readers"
|
"github.com/ncw/rclone/lib/readers"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
@@ -38,10 +44,13 @@ func TestUpdatingCheck(t *testing.T) {
|
|||||||
filePath := "sub dir/local test"
|
filePath := "sub dir/local test"
|
||||||
r.WriteFile(filePath, "content", time.Now())
|
r.WriteFile(filePath, "content", time.Now())
|
||||||
|
|
||||||
fd, err := os.Open(path.Join(r.LocalName, filePath))
|
fd, err := file.Open(path.Join(r.LocalName, filePath))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("failed opening file %q: %v", filePath, err)
|
t.Fatalf("failed opening file %q: %v", filePath, err)
|
||||||
}
|
}
|
||||||
|
defer func() {
|
||||||
|
require.NoError(t, fd.Close())
|
||||||
|
}()
|
||||||
|
|
||||||
fi, err := fd.Stat()
|
fi, err := fd.Stat()
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
@@ -72,3 +81,108 @@ func TestUpdatingCheck(t *testing.T) {
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSymlink(t *testing.T) {
|
||||||
|
r := fstest.NewRun(t)
|
||||||
|
defer r.Finalise()
|
||||||
|
f := r.Flocal.(*Fs)
|
||||||
|
dir := f.root
|
||||||
|
|
||||||
|
// Write a file
|
||||||
|
modTime1 := fstest.Time("2001-02-03T04:05:10.123123123Z")
|
||||||
|
file1 := r.WriteFile("file.txt", "hello", modTime1)
|
||||||
|
|
||||||
|
// Write a symlink
|
||||||
|
modTime2 := fstest.Time("2002-02-03T04:05:10.123123123Z")
|
||||||
|
symlinkPath := filepath.Join(dir, "symlink.txt")
|
||||||
|
require.NoError(t, os.Symlink("file.txt", symlinkPath))
|
||||||
|
require.NoError(t, lChtimes(symlinkPath, modTime2, modTime2))
|
||||||
|
|
||||||
|
// Object viewed as symlink
|
||||||
|
file2 := fstest.NewItem("symlink.txt"+linkSuffix, "file.txt", modTime2)
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
file2.Size = 0 // symlinks are 0 length under Windows
|
||||||
|
}
|
||||||
|
|
||||||
|
// Object viewed as destination
|
||||||
|
file2d := fstest.NewItem("symlink.txt", "hello", modTime1)
|
||||||
|
|
||||||
|
// Check with no symlink flags
|
||||||
|
fstest.CheckItems(t, r.Flocal, file1)
|
||||||
|
fstest.CheckItems(t, r.Fremote)
|
||||||
|
|
||||||
|
// Set fs into "-L" mode
|
||||||
|
f.opt.FollowSymlinks = true
|
||||||
|
f.opt.TranslateSymlinks = false
|
||||||
|
f.lstat = os.Stat
|
||||||
|
|
||||||
|
fstest.CheckItems(t, r.Flocal, file1, file2d)
|
||||||
|
fstest.CheckItems(t, r.Fremote)
|
||||||
|
|
||||||
|
// Set fs into "-l" mode
|
||||||
|
f.opt.FollowSymlinks = false
|
||||||
|
f.opt.TranslateSymlinks = true
|
||||||
|
f.lstat = os.Lstat
|
||||||
|
|
||||||
|
fstest.CheckListingWithPrecision(t, r.Flocal, []fstest.Item{file1, file2}, nil, fs.ModTimeNotSupported)
|
||||||
|
if haveLChtimes {
|
||||||
|
fstest.CheckItems(t, r.Flocal, file1, file2)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create a symlink
|
||||||
|
modTime3 := fstest.Time("2002-03-03T04:05:10.123123123Z")
|
||||||
|
file3 := r.WriteObjectTo(r.Flocal, "symlink2.txt"+linkSuffix, "file.txt", modTime3, false)
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
file3.Size = 0 // symlinks are 0 length under Windows
|
||||||
|
}
|
||||||
|
fstest.CheckListingWithPrecision(t, r.Flocal, []fstest.Item{file1, file2, file3}, nil, fs.ModTimeNotSupported)
|
||||||
|
if haveLChtimes {
|
||||||
|
fstest.CheckItems(t, r.Flocal, file1, file2, file3)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check it got the correct contents
|
||||||
|
symlinkPath = filepath.Join(dir, "symlink2.txt")
|
||||||
|
fi, err := os.Lstat(symlinkPath)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.False(t, fi.Mode().IsRegular())
|
||||||
|
linkText, err := os.Readlink(symlinkPath)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, "file.txt", linkText)
|
||||||
|
|
||||||
|
// Check that NewObject gets the correct object
|
||||||
|
o, err := r.Flocal.NewObject("symlink2.txt" + linkSuffix)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, "symlink2.txt"+linkSuffix, o.Remote())
|
||||||
|
if runtime.GOOS != "windows" {
|
||||||
|
assert.Equal(t, int64(8), o.Size())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check that NewObject doesn't see the non suffixed version
|
||||||
|
_, err = r.Flocal.NewObject("symlink2.txt")
|
||||||
|
require.Equal(t, fs.ErrorObjectNotFound, err)
|
||||||
|
|
||||||
|
// Check reading the object
|
||||||
|
in, err := o.Open()
|
||||||
|
require.NoError(t, err)
|
||||||
|
contents, err := ioutil.ReadAll(in)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Equal(t, "file.txt", string(contents))
|
||||||
|
require.NoError(t, in.Close())
|
||||||
|
|
||||||
|
// Check reading the object with range
|
||||||
|
in, err = o.Open(&fs.RangeOption{Start: 2, End: 5})
|
||||||
|
require.NoError(t, err)
|
||||||
|
contents, err = ioutil.ReadAll(in)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Equal(t, "file.txt"[2:5+1], string(contents))
|
||||||
|
require.NoError(t, in.Close())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSymlinkError(t *testing.T) {
|
||||||
|
m := configmap.Simple{
|
||||||
|
"links": "true",
|
||||||
|
"copy_links": "true",
|
||||||
|
}
|
||||||
|
_, err := NewFs("local", "/", m)
|
||||||
|
assert.Equal(t, errLinksAndCopyLinks, err)
|
||||||
|
}
|
||||||
@@ -285,6 +285,7 @@ type AsyncOperationStatus struct {
|
|||||||
|
|
||||||
// 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 # seperator
|
||||||
|
// 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 != "" {
|
||||||
return i.RemoteItem.ParentReference.DriveID + "#" + i.RemoteItem.ID
|
return i.RemoteItem.ParentReference.DriveID + "#" + i.RemoteItem.ID
|
||||||
|
|||||||
+138
-60
@@ -75,9 +75,8 @@ func init() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Are we running headless?
|
// Stop if we are running non-interactive config
|
||||||
if automatic, _ := m.Get(config.ConfigAutomatic); automatic != "" {
|
if fs.Config.AutoConfirm {
|
||||||
// Yes, okay we are done
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -199,7 +198,7 @@ func init() {
|
|||||||
|
|
||||||
fmt.Printf("Found drive '%s' of type '%s', URL: %s\nIs that okay?\n", rootItem.Name, rootItem.ParentReference.DriveType, rootItem.WebURL)
|
fmt.Printf("Found drive '%s' of type '%s', URL: %s\nIs that okay?\n", rootItem.Name, rootItem.ParentReference.DriveType, rootItem.WebURL)
|
||||||
// This does not work, YET :)
|
// This does not work, YET :)
|
||||||
if !config.Confirm() {
|
if !config.ConfirmWithConfig(m, "config_drive_ok", true) {
|
||||||
log.Fatalf("Cancelled by user")
|
log.Fatalf("Cancelled by user")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -334,20 +333,10 @@ func shouldRetry(resp *http.Response, err error) (bool, error) {
|
|||||||
return authRety || fserrors.ShouldRetry(err) || fserrors.ShouldRetryHTTP(resp, retryErrorCodes), err
|
return authRety || fserrors.ShouldRetry(err) || fserrors.ShouldRetryHTTP(resp, retryErrorCodes), err
|
||||||
}
|
}
|
||||||
|
|
||||||
// readMetaDataForPath reads the metadata from the path
|
// readMetaDataForPathRelativeToID reads the metadata for a path relative to an item that is addressed by its normalized ID.
|
||||||
func (f *Fs) readMetaDataForPath(path string) (info *api.Item, resp *http.Response, err error) {
|
// if `relPath` == "", it reads the metadata for the item with that ID.
|
||||||
var opts rest.Opts
|
func (f *Fs) readMetaDataForPathRelativeToID(normalizedID string, relPath string) (info *api.Item, resp *http.Response, err error) {
|
||||||
if len(path) == 0 {
|
opts := newOptsCall(normalizedID, "GET", ":/"+rest.URLPathEscape(replaceReservedChars(relPath)))
|
||||||
opts = rest.Opts{
|
|
||||||
Method: "GET",
|
|
||||||
Path: "/root",
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
opts = rest.Opts{
|
|
||||||
Method: "GET",
|
|
||||||
Path: "/root:/" + rest.URLPathEscape(replaceReservedChars(path)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
err = f.pacer.Call(func() (bool, error) {
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
resp, err = f.srv.CallJSON(&opts, nil, &info)
|
resp, err = f.srv.CallJSON(&opts, nil, &info)
|
||||||
return shouldRetry(resp, err)
|
return shouldRetry(resp, err)
|
||||||
@@ -356,6 +345,72 @@ func (f *Fs) readMetaDataForPath(path string) (info *api.Item, resp *http.Respon
|
|||||||
return info, resp, err
|
return info, resp, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// readMetaDataForPath reads the metadata from the path (relative to the absolute root)
|
||||||
|
func (f *Fs) readMetaDataForPath(path string) (info *api.Item, resp *http.Response, err error) {
|
||||||
|
firstSlashIndex := strings.IndexRune(path, '/')
|
||||||
|
|
||||||
|
if f.driveType != driveTypePersonal || firstSlashIndex == -1 {
|
||||||
|
var opts rest.Opts
|
||||||
|
if len(path) == 0 {
|
||||||
|
opts = rest.Opts{
|
||||||
|
Method: "GET",
|
||||||
|
Path: "/root",
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
opts = rest.Opts{
|
||||||
|
Method: "GET",
|
||||||
|
Path: "/root:/" + rest.URLPathEscape(replaceReservedChars(path)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
|
resp, err = f.srv.CallJSON(&opts, nil, &info)
|
||||||
|
return shouldRetry(resp, err)
|
||||||
|
})
|
||||||
|
return info, resp, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// The following branch handles the case when we're using OneDrive Personal and the path is in a folder.
|
||||||
|
// For OneDrive Personal, we need to consider the "shared with me" folders.
|
||||||
|
// An item in such a folder can only be addressed by its ID relative to the sharer's driveID or
|
||||||
|
// by its path relative to the folder's ID relative to the sharer's driveID.
|
||||||
|
// Note: A "shared with me" folder can only be placed in the sharee's absolute root.
|
||||||
|
// So we read metadata relative to a suitable folder's normalized ID.
|
||||||
|
var dirCacheFoundRoot bool
|
||||||
|
var rootNormalizedID string
|
||||||
|
if f.dirCache != nil {
|
||||||
|
var ok bool
|
||||||
|
if rootNormalizedID, ok = f.dirCache.Get(""); ok {
|
||||||
|
dirCacheFoundRoot = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
relPath, insideRoot := getRelativePathInsideBase(f.root, path)
|
||||||
|
var firstDir, baseNormalizedID string
|
||||||
|
if !insideRoot || !dirCacheFoundRoot {
|
||||||
|
// We do not have the normalized ID in dirCache for our query to base on. Query it manually.
|
||||||
|
firstDir, relPath = path[:firstSlashIndex], path[firstSlashIndex+1:]
|
||||||
|
info, resp, err := f.readMetaDataForPath(firstDir)
|
||||||
|
if err != nil {
|
||||||
|
return info, resp, err
|
||||||
|
}
|
||||||
|
baseNormalizedID = info.GetID()
|
||||||
|
} else {
|
||||||
|
if f.root != "" {
|
||||||
|
// Read metadata based on root
|
||||||
|
baseNormalizedID = rootNormalizedID
|
||||||
|
} else {
|
||||||
|
// Read metadata based on firstDir
|
||||||
|
firstDir, relPath = path[:firstSlashIndex], path[firstSlashIndex+1:]
|
||||||
|
baseNormalizedID, err = f.dirCache.FindDir(firstDir, false)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return f.readMetaDataForPathRelativeToID(baseNormalizedID, relPath)
|
||||||
|
}
|
||||||
|
|
||||||
// errorHandler parses a non 2xx error response into an error
|
// errorHandler parses a non 2xx error response into an error
|
||||||
func errorHandler(resp *http.Response) error {
|
func errorHandler(resp *http.Response) error {
|
||||||
// Decode error response
|
// Decode error response
|
||||||
@@ -404,13 +459,13 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if opt.DriveID == "" || opt.DriveType == "" {
|
if opt.DriveID == "" || opt.DriveType == "" {
|
||||||
log.Fatalf("Unable to get drive_id and drive_type. If you are upgrading from older versions of rclone, please run `rclone config` and re-configure this backend.")
|
return nil, errors.New("unable to get drive_id and drive_type - if you are upgrading from older versions of rclone, please run `rclone config` and re-configure this backend")
|
||||||
}
|
}
|
||||||
|
|
||||||
root = parsePath(root)
|
root = parsePath(root)
|
||||||
oAuthClient, ts, err := oauthutil.NewClient(name, m, oauthConfig)
|
oAuthClient, ts, err := oauthutil.NewClient(name, m, oauthConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Failed to configure OneDrive: %v", err)
|
return nil, errors.Wrap(err, "failed to configure OneDrive")
|
||||||
}
|
}
|
||||||
|
|
||||||
f := &Fs{
|
f := &Fs{
|
||||||
@@ -437,11 +492,11 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
|
|
||||||
// Get rootID
|
// Get rootID
|
||||||
rootInfo, _, err := f.readMetaDataForPath("")
|
rootInfo, _, err := f.readMetaDataForPath("")
|
||||||
if err != nil || rootInfo.ID == "" {
|
if err != nil || rootInfo.GetID() == "" {
|
||||||
return nil, errors.Wrap(err, "failed to get root")
|
return nil, errors.Wrap(err, "failed to get root")
|
||||||
}
|
}
|
||||||
|
|
||||||
f.dirCache = dircache.New(root, rootInfo.ID, f)
|
f.dirCache = dircache.New(root, rootInfo.GetID(), f)
|
||||||
|
|
||||||
// Find the current root
|
// Find the current root
|
||||||
err = f.dirCache.FindRoot(false)
|
err = f.dirCache.FindRoot(false)
|
||||||
@@ -514,18 +569,11 @@ func (f *Fs) NewObject(remote string) (fs.Object, error) {
|
|||||||
// FindLeaf finds a directory of name leaf in the folder with ID pathID
|
// FindLeaf finds a directory of name leaf in the folder with ID pathID
|
||||||
func (f *Fs) FindLeaf(pathID, leaf string) (pathIDOut string, found bool, err error) {
|
func (f *Fs) FindLeaf(pathID, leaf string) (pathIDOut string, found bool, err error) {
|
||||||
// fs.Debugf(f, "FindLeaf(%q, %q)", pathID, leaf)
|
// fs.Debugf(f, "FindLeaf(%q, %q)", pathID, leaf)
|
||||||
parent, ok := f.dirCache.GetInv(pathID)
|
_, ok := f.dirCache.GetInv(pathID)
|
||||||
if !ok {
|
if !ok {
|
||||||
return "", false, errors.New("couldn't find parent ID")
|
return "", false, errors.New("couldn't find parent ID")
|
||||||
}
|
}
|
||||||
path := leaf
|
info, resp, err := f.readMetaDataForPathRelativeToID(pathID, leaf)
|
||||||
if parent != "" {
|
|
||||||
path = parent + "/" + path
|
|
||||||
}
|
|
||||||
if f.dirCache.FoundRoot() {
|
|
||||||
path = f.rootSlash() + path
|
|
||||||
}
|
|
||||||
info, resp, err := f.readMetaDataForPath(path)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if resp != nil && resp.StatusCode == http.StatusNotFound {
|
if resp != nil && resp.StatusCode == http.StatusNotFound {
|
||||||
return "", false, nil
|
return "", false, nil
|
||||||
@@ -867,13 +915,13 @@ func (f *Fs) Copy(src fs.Object, remote string) (fs.Object, error) {
|
|||||||
opts.ExtraHeaders = map[string]string{"Prefer": "respond-async"}
|
opts.ExtraHeaders = map[string]string{"Prefer": "respond-async"}
|
||||||
opts.NoResponse = true
|
opts.NoResponse = true
|
||||||
|
|
||||||
id, _, _ := parseDirID(directoryID)
|
id, dstDriveID, _ := parseNormalizedID(directoryID)
|
||||||
|
|
||||||
replacedLeaf := replaceReservedChars(leaf)
|
replacedLeaf := replaceReservedChars(leaf)
|
||||||
copyReq := api.CopyItemRequest{
|
copyReq := api.CopyItemRequest{
|
||||||
Name: &replacedLeaf,
|
Name: &replacedLeaf,
|
||||||
ParentReference: api.ItemReference{
|
ParentReference: api.ItemReference{
|
||||||
DriveID: f.driveID,
|
DriveID: dstDriveID,
|
||||||
ID: id,
|
ID: id,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -940,15 +988,23 @@ func (f *Fs) Move(src fs.Object, remote string) (fs.Object, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
id, dstDriveID, _ := parseNormalizedID(directoryID)
|
||||||
|
_, srcObjDriveID, _ := parseNormalizedID(srcObj.id)
|
||||||
|
|
||||||
|
if dstDriveID != srcObjDriveID {
|
||||||
|
// https://docs.microsoft.com/en-us/graph/api/driveitem-move?view=graph-rest-1.0
|
||||||
|
// "Items cannot be moved between Drives using this request."
|
||||||
|
return nil, fs.ErrorCantMove
|
||||||
|
}
|
||||||
|
|
||||||
// Move the object
|
// Move the object
|
||||||
opts := newOptsCall(srcObj.id, "PATCH", "")
|
opts := newOptsCall(srcObj.id, "PATCH", "")
|
||||||
|
|
||||||
id, _, _ := parseDirID(directoryID)
|
|
||||||
|
|
||||||
move := api.MoveItemRequest{
|
move := api.MoveItemRequest{
|
||||||
Name: replaceReservedChars(leaf),
|
Name: replaceReservedChars(leaf),
|
||||||
ParentReference: &api.ItemReference{
|
ParentReference: &api.ItemReference{
|
||||||
ID: id,
|
DriveID: dstDriveID,
|
||||||
|
ID: id,
|
||||||
},
|
},
|
||||||
// We set the mod time too as it gets reset otherwise
|
// We set the mod time too as it gets reset otherwise
|
||||||
FileSystemInfo: &api.FileSystemInfoFacet{
|
FileSystemInfo: &api.FileSystemInfoFacet{
|
||||||
@@ -1024,7 +1080,20 @@ func (f *Fs) DirMove(src fs.Fs, srcRemote, dstRemote string) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
parsedDstDirID, _, _ := parseDirID(dstDirectoryID)
|
parsedDstDirID, dstDriveID, _ := parseNormalizedID(dstDirectoryID)
|
||||||
|
|
||||||
|
// Find ID of src
|
||||||
|
srcID, err := srcFs.dirCache.FindDir(srcRemote, false)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, srcDriveID, _ := parseNormalizedID(srcID)
|
||||||
|
|
||||||
|
if dstDriveID != srcDriveID {
|
||||||
|
// https://docs.microsoft.com/en-us/graph/api/driveitem-move?view=graph-rest-1.0
|
||||||
|
// "Items cannot be moved between Drives using this request."
|
||||||
|
return fs.ErrorCantDirMove
|
||||||
|
}
|
||||||
|
|
||||||
// Check destination does not exist
|
// Check destination does not exist
|
||||||
if dstRemote != "" {
|
if dstRemote != "" {
|
||||||
@@ -1038,14 +1107,8 @@ func (f *Fs) DirMove(src fs.Fs, srcRemote, dstRemote string) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find ID of src
|
|
||||||
srcID, err := srcFs.dirCache.FindDir(srcRemote, false)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get timestamps of src so they can be preserved
|
// Get timestamps of src so they can be preserved
|
||||||
srcInfo, _, err := srcFs.readMetaDataForPath(srcPath)
|
srcInfo, _, err := srcFs.readMetaDataForPathRelativeToID(srcID, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -1055,7 +1118,8 @@ func (f *Fs) DirMove(src fs.Fs, srcRemote, dstRemote string) error {
|
|||||||
move := api.MoveItemRequest{
|
move := api.MoveItemRequest{
|
||||||
Name: replaceReservedChars(leaf),
|
Name: replaceReservedChars(leaf),
|
||||||
ParentReference: &api.ItemReference{
|
ParentReference: &api.ItemReference{
|
||||||
ID: parsedDstDirID,
|
DriveID: dstDriveID,
|
||||||
|
ID: parsedDstDirID,
|
||||||
},
|
},
|
||||||
// We set the mod time too as it gets reset otherwise
|
// We set the mod time too as it gets reset otherwise
|
||||||
FileSystemInfo: &api.FileSystemInfoFacet{
|
FileSystemInfo: &api.FileSystemInfoFacet{
|
||||||
@@ -1122,7 +1186,7 @@ func (f *Fs) PublicLink(remote string) (link string, err error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
opts := newOptsCall(info.ID, "POST", "/createLink")
|
opts := newOptsCall(info.GetID(), "POST", "/createLink")
|
||||||
|
|
||||||
share := api.CreateShareLinkRequest{
|
share := api.CreateShareLinkRequest{
|
||||||
Type: "view",
|
Type: "view",
|
||||||
@@ -1270,13 +1334,13 @@ func (o *Object) ModTime() time.Time {
|
|||||||
// setModTime sets the modification time of the local fs object
|
// setModTime sets the modification time of the local fs object
|
||||||
func (o *Object) setModTime(modTime time.Time) (*api.Item, error) {
|
func (o *Object) setModTime(modTime time.Time) (*api.Item, error) {
|
||||||
var opts rest.Opts
|
var opts rest.Opts
|
||||||
_, directoryID, _ := o.fs.dirCache.FindPath(o.remote, false)
|
leaf, directoryID, _ := o.fs.dirCache.FindPath(o.remote, false)
|
||||||
_, drive, rootURL := parseDirID(directoryID)
|
trueDirID, drive, rootURL := parseNormalizedID(directoryID)
|
||||||
if drive != "" {
|
if drive != "" {
|
||||||
opts = rest.Opts{
|
opts = rest.Opts{
|
||||||
Method: "PATCH",
|
Method: "PATCH",
|
||||||
RootURL: rootURL,
|
RootURL: rootURL,
|
||||||
Path: "/" + drive + "/root:/" + rest.URLPathEscape(o.srvPath()),
|
Path: "/" + drive + "/items/" + trueDirID + ":/" + rest.URLPathEscape(leaf),
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
opts = rest.Opts{
|
opts = rest.Opts{
|
||||||
@@ -1344,7 +1408,7 @@ func (o *Object) Open(options ...fs.OpenOption) (in io.ReadCloser, err error) {
|
|||||||
// createUploadSession creates an upload session for the object
|
// createUploadSession creates an upload session for the object
|
||||||
func (o *Object) createUploadSession(modTime time.Time) (response *api.CreateUploadResponse, err error) {
|
func (o *Object) createUploadSession(modTime time.Time) (response *api.CreateUploadResponse, err error) {
|
||||||
leaf, directoryID, _ := o.fs.dirCache.FindPath(o.remote, false)
|
leaf, directoryID, _ := o.fs.dirCache.FindPath(o.remote, false)
|
||||||
id, drive, rootURL := parseDirID(directoryID)
|
id, drive, rootURL := parseNormalizedID(directoryID)
|
||||||
var opts rest.Opts
|
var opts rest.Opts
|
||||||
if drive != "" {
|
if drive != "" {
|
||||||
opts = rest.Opts{
|
opts = rest.Opts{
|
||||||
@@ -1477,13 +1541,13 @@ func (o *Object) uploadSinglepart(in io.Reader, size int64, modTime time.Time) (
|
|||||||
fs.Debugf(o, "Starting singlepart upload")
|
fs.Debugf(o, "Starting singlepart upload")
|
||||||
var resp *http.Response
|
var resp *http.Response
|
||||||
var opts rest.Opts
|
var opts rest.Opts
|
||||||
_, directoryID, _ := o.fs.dirCache.FindPath(o.remote, false)
|
leaf, directoryID, _ := o.fs.dirCache.FindPath(o.remote, false)
|
||||||
_, drive, rootURL := parseDirID(directoryID)
|
trueDirID, drive, rootURL := parseNormalizedID(directoryID)
|
||||||
if drive != "" {
|
if drive != "" {
|
||||||
opts = rest.Opts{
|
opts = rest.Opts{
|
||||||
Method: "PUT",
|
Method: "PUT",
|
||||||
RootURL: rootURL,
|
RootURL: rootURL,
|
||||||
Path: "/" + drive + "/root:/" + rest.URLPathEscape(o.srvPath()) + ":/content",
|
Path: "/" + drive + "/items/" + trueDirID + ":/" + rest.URLPathEscape(leaf) + ":/content",
|
||||||
ContentLength: &size,
|
ContentLength: &size,
|
||||||
Body: in,
|
Body: in,
|
||||||
}
|
}
|
||||||
@@ -1496,10 +1560,6 @@ func (o *Object) uploadSinglepart(in io.Reader, size int64, modTime time.Time) (
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if size == 0 {
|
|
||||||
opts.Body = nil
|
|
||||||
}
|
|
||||||
|
|
||||||
err = o.fs.pacer.Call(func() (bool, error) {
|
err = o.fs.pacer.Call(func() (bool, error) {
|
||||||
resp, err = o.fs.srv.CallJSON(&opts, nil, &info)
|
resp, err = o.fs.srv.CallJSON(&opts, nil, &info)
|
||||||
if apiErr, ok := err.(*api.Error); ok {
|
if apiErr, ok := err.(*api.Error); ok {
|
||||||
@@ -1566,8 +1626,8 @@ func (o *Object) ID() string {
|
|||||||
return o.id
|
return o.id
|
||||||
}
|
}
|
||||||
|
|
||||||
func newOptsCall(id string, method string, route string) (opts rest.Opts) {
|
func newOptsCall(normalizedID string, method string, route string) (opts rest.Opts) {
|
||||||
id, drive, rootURL := parseDirID(id)
|
id, drive, rootURL := parseNormalizedID(normalizedID)
|
||||||
|
|
||||||
if drive != "" {
|
if drive != "" {
|
||||||
return rest.Opts{
|
return rest.Opts{
|
||||||
@@ -1582,7 +1642,10 @@ func newOptsCall(id string, method string, route string) (opts rest.Opts) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseDirID(ID string) (string, string, string) {
|
// parseNormalizedID parses a normalized ID (may be in the form `driveID#itemID` or just `itemID`)
|
||||||
|
// and returns itemID, driveID, rootURL.
|
||||||
|
// Such a normalized ID can come from (*Item).GetID()
|
||||||
|
func parseNormalizedID(ID string) (string, string, string) {
|
||||||
if strings.Index(ID, "#") >= 0 {
|
if strings.Index(ID, "#") >= 0 {
|
||||||
s := strings.Split(ID, "#")
|
s := strings.Split(ID, "#")
|
||||||
return s[1], s[0], graphURL + "/drives"
|
return s[1], s[0], graphURL + "/drives"
|
||||||
@@ -1590,6 +1653,21 @@ func parseDirID(ID string) (string, string, string) {
|
|||||||
return ID, "", ""
|
return ID, "", ""
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// getRelativePathInsideBase checks if `target` is inside `base`. If so, it
|
||||||
|
// returns a relative path for `target` based on `base` and a boolean `true`.
|
||||||
|
// Otherwise returns "", false.
|
||||||
|
func getRelativePathInsideBase(base, target string) (string, bool) {
|
||||||
|
if base == "" {
|
||||||
|
return target, true
|
||||||
|
}
|
||||||
|
|
||||||
|
baseSlash := base + "/"
|
||||||
|
if strings.HasPrefix(target+"/", baseSlash) {
|
||||||
|
return target[len(baseSlash):], true
|
||||||
|
}
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
|
||||||
// Check the interfaces are satisfied
|
// Check the interfaces are satisfied
|
||||||
var (
|
var (
|
||||||
_ fs.Fs = (*Fs)(nil)
|
_ fs.Fs = (*Fs)(nil)
|
||||||
|
|||||||
@@ -246,7 +246,7 @@ 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)
|
oAuthClient, ts, err := oauthutil.NewClient(name, m, oauthConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Failed to configure Pcloud: %v", err)
|
return nil, errors.Wrap(err, "failed to configure Pcloud")
|
||||||
}
|
}
|
||||||
|
|
||||||
f := &Fs{
|
f := &Fs{
|
||||||
|
|||||||
+105
-16
@@ -69,17 +69,57 @@ func init() {
|
|||||||
}},
|
}},
|
||||||
}, {
|
}, {
|
||||||
Name: "connection_retries",
|
Name: "connection_retries",
|
||||||
Help: "Number of connnection retries.",
|
Help: "Number of connection retries.",
|
||||||
Default: 3,
|
Default: 3,
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: "upload_cutoff",
|
||||||
|
Help: `Cutoff for switching to chunked upload
|
||||||
|
|
||||||
|
Any files larger than this will be uploaded in chunks of chunk_size.
|
||||||
|
The minimum is 0 and the maximum is 5GB.`,
|
||||||
|
Default: defaultUploadCutoff,
|
||||||
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: "chunk_size",
|
||||||
|
Help: `Chunk size to use for uploading.
|
||||||
|
|
||||||
|
When uploading files larger than upload_cutoff they will be uploaded
|
||||||
|
as multipart uploads using this chunk size.
|
||||||
|
|
||||||
|
Note that "--qingstor-upload-concurrency" chunks of this size are buffered
|
||||||
|
in memory per transfer.
|
||||||
|
|
||||||
|
If you are transferring large files over high speed links and you have
|
||||||
|
enough memory, then increasing this will speed up the transfers.`,
|
||||||
|
Default: minChunkSize,
|
||||||
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: "upload_concurrency",
|
||||||
|
Help: `Concurrency for multipart uploads.
|
||||||
|
|
||||||
|
This is the number of chunks of the same file that are uploaded
|
||||||
|
concurrently.
|
||||||
|
|
||||||
|
NB if you set this to > 1 then the checksums of multpart uploads
|
||||||
|
become corrupted (the uploads themselves are not corrupted though).
|
||||||
|
|
||||||
|
If you are uploading small numbers of large file over high speed link
|
||||||
|
and these uploads do not fully utilize your bandwidth, then increasing
|
||||||
|
this may help to speed up the transfers.`,
|
||||||
|
Default: 1,
|
||||||
|
Advanced: true,
|
||||||
}},
|
}},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Constants
|
// Constants
|
||||||
const (
|
const (
|
||||||
listLimitSize = 1000 // Number of items to read at once
|
listLimitSize = 1000 // Number of items to read at once
|
||||||
maxSizeForCopy = 1024 * 1024 * 1024 * 5 // The maximum size of object we can COPY
|
maxSizeForCopy = 1024 * 1024 * 1024 * 5 // The maximum size of object we can COPY
|
||||||
|
minChunkSize = fs.SizeSuffix(minMultiPartSize)
|
||||||
|
defaultUploadCutoff = fs.SizeSuffix(200 * 1024 * 1024)
|
||||||
|
maxUploadCutoff = fs.SizeSuffix(5 * 1024 * 1024 * 1024)
|
||||||
)
|
)
|
||||||
|
|
||||||
// Globals
|
// Globals
|
||||||
@@ -92,12 +132,15 @@ func timestampToTime(tp int64) time.Time {
|
|||||||
|
|
||||||
// Options defines the configuration for this backend
|
// Options defines the configuration for this backend
|
||||||
type Options struct {
|
type Options struct {
|
||||||
EnvAuth bool `config:"env_auth"`
|
EnvAuth bool `config:"env_auth"`
|
||||||
AccessKeyID string `config:"access_key_id"`
|
AccessKeyID string `config:"access_key_id"`
|
||||||
SecretAccessKey string `config:"secret_access_key"`
|
SecretAccessKey string `config:"secret_access_key"`
|
||||||
Endpoint string `config:"endpoint"`
|
Endpoint string `config:"endpoint"`
|
||||||
Zone string `config:"zone"`
|
Zone string `config:"zone"`
|
||||||
ConnectionRetries int `config:"connection_retries"`
|
ConnectionRetries int `config:"connection_retries"`
|
||||||
|
UploadCutoff fs.SizeSuffix `config:"upload_cutoff"`
|
||||||
|
ChunkSize fs.SizeSuffix `config:"chunk_size"`
|
||||||
|
UploadConcurrency int `config:"upload_concurrency"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fs represents a remote qingstor server
|
// Fs represents a remote qingstor server
|
||||||
@@ -227,6 +270,36 @@ func qsServiceConnection(opt *Options) (*qs.Service, error) {
|
|||||||
return qs.Init(cf)
|
return qs.Init(cf)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func checkUploadChunkSize(cs fs.SizeSuffix) error {
|
||||||
|
if cs < minChunkSize {
|
||||||
|
return errors.Errorf("%s is less than %s", cs, minChunkSize)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fs) setUploadChunkSize(cs fs.SizeSuffix) (old fs.SizeSuffix, err error) {
|
||||||
|
err = checkUploadChunkSize(cs)
|
||||||
|
if err == nil {
|
||||||
|
old, f.opt.ChunkSize = f.opt.ChunkSize, cs
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkUploadCutoff(cs fs.SizeSuffix) error {
|
||||||
|
if cs > maxUploadCutoff {
|
||||||
|
return errors.Errorf("%s is greater than %s", cs, maxUploadCutoff)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fs) setUploadCutoff(cs fs.SizeSuffix) (old fs.SizeSuffix, err error) {
|
||||||
|
err = checkUploadCutoff(cs)
|
||||||
|
if err == nil {
|
||||||
|
old, f.opt.UploadCutoff = f.opt.UploadCutoff, cs
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// NewFs constructs an Fs from the path, bucket:path
|
// NewFs constructs an Fs from the path, bucket:path
|
||||||
func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
||||||
// Parse config into Options struct
|
// Parse config into Options struct
|
||||||
@@ -235,6 +308,14 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
err = checkUploadChunkSize(opt.ChunkSize)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "qingstor: chunk size")
|
||||||
|
}
|
||||||
|
err = checkUploadCutoff(opt.UploadCutoff)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "qingstor: upload cutoff")
|
||||||
|
}
|
||||||
bucket, key, err := qsParsePath(root)
|
bucket, key, err := qsParsePath(root)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -913,16 +994,24 @@ func (o *Object) Update(in io.Reader, src fs.ObjectInfo, options ...fs.OpenOptio
|
|||||||
mimeType := fs.MimeType(src)
|
mimeType := fs.MimeType(src)
|
||||||
|
|
||||||
req := uploadInput{
|
req := uploadInput{
|
||||||
body: in,
|
body: in,
|
||||||
qsSvc: o.fs.svc,
|
qsSvc: o.fs.svc,
|
||||||
bucket: o.fs.bucket,
|
bucket: o.fs.bucket,
|
||||||
zone: o.fs.zone,
|
zone: o.fs.zone,
|
||||||
key: key,
|
key: key,
|
||||||
mimeType: mimeType,
|
mimeType: mimeType,
|
||||||
|
partSize: int64(o.fs.opt.ChunkSize),
|
||||||
|
concurrency: o.fs.opt.UploadConcurrency,
|
||||||
}
|
}
|
||||||
uploader := newUploader(&req)
|
uploader := newUploader(&req)
|
||||||
|
|
||||||
err = uploader.upload()
|
size := src.Size()
|
||||||
|
multipart := size < 0 || size >= int64(o.fs.opt.UploadCutoff)
|
||||||
|
if multipart {
|
||||||
|
err = uploader.upload()
|
||||||
|
} else {
|
||||||
|
err = uploader.singlePartUpload(in, size)
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,12 +2,12 @@
|
|||||||
|
|
||||||
// +build !plan9
|
// +build !plan9
|
||||||
|
|
||||||
package qingstor_test
|
package qingstor
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/ncw/rclone/backend/qingstor"
|
"github.com/ncw/rclone/fs"
|
||||||
"github.com/ncw/rclone/fstest/fstests"
|
"github.com/ncw/rclone/fstest/fstests"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -15,6 +15,19 @@ import (
|
|||||||
func TestIntegration(t *testing.T) {
|
func TestIntegration(t *testing.T) {
|
||||||
fstests.Run(t, &fstests.Opt{
|
fstests.Run(t, &fstests.Opt{
|
||||||
RemoteName: "TestQingStor:",
|
RemoteName: "TestQingStor:",
|
||||||
NilObject: (*qingstor.Object)(nil),
|
NilObject: (*Object)(nil),
|
||||||
|
ChunkedUpload: fstests.ChunkedUploadConfig{
|
||||||
|
MinChunkSize: minChunkSize,
|
||||||
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (f *Fs) SetUploadChunkSize(cs fs.SizeSuffix) (fs.SizeSuffix, error) {
|
||||||
|
return f.setUploadChunkSize(cs)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fs) SetUploadCutoff(cs fs.SizeSuffix) (fs.SizeSuffix, error) {
|
||||||
|
return f.setUploadCutoff(cs)
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ fstests.SetUploadChunkSizer = (*Fs)(nil)
|
||||||
+19
-11
@@ -152,11 +152,11 @@ func (u *uploader) init() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// singlePartUpload upload a single object that contentLength less than "defaultUploadPartSize"
|
// singlePartUpload upload a single object that contentLength less than "defaultUploadPartSize"
|
||||||
func (u *uploader) singlePartUpload(buf io.ReadSeeker) error {
|
func (u *uploader) singlePartUpload(buf io.Reader, size int64) error {
|
||||||
bucketInit, _ := u.bucketInit()
|
bucketInit, _ := u.bucketInit()
|
||||||
|
|
||||||
req := qs.PutObjectInput{
|
req := qs.PutObjectInput{
|
||||||
ContentLength: &u.readerPos,
|
ContentLength: &size,
|
||||||
ContentType: &u.cfg.mimeType,
|
ContentType: &u.cfg.mimeType,
|
||||||
Body: buf,
|
Body: buf,
|
||||||
}
|
}
|
||||||
@@ -179,13 +179,13 @@ func (u *uploader) upload() error {
|
|||||||
// Do one read to determine if we have more than one part
|
// Do one read to determine if we have more than one part
|
||||||
reader, _, err := u.nextReader()
|
reader, _, err := u.nextReader()
|
||||||
if err == io.EOF { // single part
|
if err == io.EOF { // single part
|
||||||
fs.Debugf(u, "Tried to upload a singile object to QingStor")
|
fs.Debugf(u, "Uploading as single part object to QingStor")
|
||||||
return u.singlePartUpload(reader)
|
return u.singlePartUpload(reader, u.readerPos)
|
||||||
} else if err != nil {
|
} else if err != nil {
|
||||||
return errors.Errorf("read upload data failed: %s", err)
|
return errors.Errorf("read upload data failed: %s", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
fs.Debugf(u, "Treied to upload a multi-part object to QingStor")
|
fs.Debugf(u, "Uploading as multi-part object to QingStor")
|
||||||
mu := multiUploader{uploader: u}
|
mu := multiUploader{uploader: u}
|
||||||
return mu.multiPartUpload(reader)
|
return mu.multiPartUpload(reader)
|
||||||
}
|
}
|
||||||
@@ -261,7 +261,7 @@ func (mu *multiUploader) initiate() error {
|
|||||||
req := qs.InitiateMultipartUploadInput{
|
req := qs.InitiateMultipartUploadInput{
|
||||||
ContentType: &mu.cfg.mimeType,
|
ContentType: &mu.cfg.mimeType,
|
||||||
}
|
}
|
||||||
fs.Debugf(mu, "Tried to initiate a multi-part upload")
|
fs.Debugf(mu, "Initiating a multi-part upload")
|
||||||
rsp, err := bucketInit.InitiateMultipartUpload(mu.cfg.key, &req)
|
rsp, err := bucketInit.InitiateMultipartUpload(mu.cfg.key, &req)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
mu.uploadID = rsp.UploadID
|
mu.uploadID = rsp.UploadID
|
||||||
@@ -279,12 +279,12 @@ func (mu *multiUploader) send(c chunk) error {
|
|||||||
ContentLength: &c.size,
|
ContentLength: &c.size,
|
||||||
Body: c.buffer,
|
Body: c.buffer,
|
||||||
}
|
}
|
||||||
fs.Debugf(mu, "Tried to upload a part to QingStor that partNumber %d and partSize %d", c.partNumber, c.size)
|
fs.Debugf(mu, "Uploading a part to QingStor with partNumber %d and partSize %d", c.partNumber, c.size)
|
||||||
_, err := bucketInit.UploadMultipart(mu.cfg.key, &req)
|
_, err := bucketInit.UploadMultipart(mu.cfg.key, &req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
fs.Debugf(mu, "Upload part finished that partNumber %d and partSize %d", c.partNumber, c.size)
|
fs.Debugf(mu, "Done uploading part partNumber %d and partSize %d", c.partNumber, c.size)
|
||||||
|
|
||||||
mu.mtx.Lock()
|
mu.mtx.Lock()
|
||||||
defer mu.mtx.Unlock()
|
defer mu.mtx.Unlock()
|
||||||
@@ -304,7 +304,7 @@ func (mu *multiUploader) list() error {
|
|||||||
req := qs.ListMultipartInput{
|
req := qs.ListMultipartInput{
|
||||||
UploadID: mu.uploadID,
|
UploadID: mu.uploadID,
|
||||||
}
|
}
|
||||||
fs.Debugf(mu, "Tried to list a multi-part")
|
fs.Debugf(mu, "Reading multi-part details")
|
||||||
rsp, err := bucketInit.ListMultipart(mu.cfg.key, &req)
|
rsp, err := bucketInit.ListMultipart(mu.cfg.key, &req)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
mu.objectParts = rsp.ObjectParts
|
mu.objectParts = rsp.ObjectParts
|
||||||
@@ -331,7 +331,7 @@ func (mu *multiUploader) complete() error {
|
|||||||
ObjectParts: mu.objectParts,
|
ObjectParts: mu.objectParts,
|
||||||
ETag: &md5String,
|
ETag: &md5String,
|
||||||
}
|
}
|
||||||
fs.Debugf(mu, "Tried to complete a multi-part")
|
fs.Debugf(mu, "Completing multi-part object")
|
||||||
_, err = bucketInit.CompleteMultipartUpload(mu.cfg.key, &req)
|
_, err = bucketInit.CompleteMultipartUpload(mu.cfg.key, &req)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
fs.Debugf(mu, "Complete multi-part finished")
|
fs.Debugf(mu, "Complete multi-part finished")
|
||||||
@@ -348,7 +348,7 @@ func (mu *multiUploader) abort() error {
|
|||||||
req := qs.AbortMultipartUploadInput{
|
req := qs.AbortMultipartUploadInput{
|
||||||
UploadID: uploadID,
|
UploadID: uploadID,
|
||||||
}
|
}
|
||||||
fs.Debugf(mu, "Tried to abort a multi-part")
|
fs.Debugf(mu, "Aborting multi-part object %q", *uploadID)
|
||||||
_, err = bucketInit.AbortMultipartUpload(mu.cfg.key, &req)
|
_, err = bucketInit.AbortMultipartUpload(mu.cfg.key, &req)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -392,6 +392,14 @@ func (mu *multiUploader) multiPartUpload(firstBuf io.ReadSeeker) error {
|
|||||||
var nextChunkLen int
|
var nextChunkLen int
|
||||||
reader, nextChunkLen, err = mu.nextReader()
|
reader, nextChunkLen, err = mu.nextReader()
|
||||||
if err != nil && err != io.EOF {
|
if err != nil && err != io.EOF {
|
||||||
|
// empty ch
|
||||||
|
go func() {
|
||||||
|
for range ch {
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
// Wait for all goroutines finish
|
||||||
|
close(ch)
|
||||||
|
mu.wg.Wait()
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if nextChunkLen == 0 && partNumber > 0 {
|
if nextChunkLen == 0 && partNumber > 0 {
|
||||||
|
|||||||
+391
-82
@@ -53,7 +53,7 @@ import (
|
|||||||
func init() {
|
func init() {
|
||||||
fs.Register(&fs.RegInfo{
|
fs.Register(&fs.RegInfo{
|
||||||
Name: "s3",
|
Name: "s3",
|
||||||
Description: "Amazon S3 Compliant Storage Providers (AWS, Ceph, Dreamhost, IBM COS, Minio)",
|
Description: "Amazon S3 Compliant Storage Provider (AWS, Alibaba, Ceph, Digital Ocean, Dreamhost, IBM COS, Minio, etc)",
|
||||||
NewFs: NewFs,
|
NewFs: NewFs,
|
||||||
Options: []fs.Option{{
|
Options: []fs.Option{{
|
||||||
Name: fs.ConfigProvider,
|
Name: fs.ConfigProvider,
|
||||||
@@ -61,6 +61,9 @@ func init() {
|
|||||||
Examples: []fs.OptionExample{{
|
Examples: []fs.OptionExample{{
|
||||||
Value: "AWS",
|
Value: "AWS",
|
||||||
Help: "Amazon Web Services (AWS) S3",
|
Help: "Amazon Web Services (AWS) S3",
|
||||||
|
}, {
|
||||||
|
Value: "Alibaba",
|
||||||
|
Help: "Alibaba Cloud Object Storage System (OSS) formerly Aliyun",
|
||||||
}, {
|
}, {
|
||||||
Value: "Ceph",
|
Value: "Ceph",
|
||||||
Help: "Ceph Object Storage",
|
Help: "Ceph Object Storage",
|
||||||
@@ -76,6 +79,9 @@ func init() {
|
|||||||
}, {
|
}, {
|
||||||
Value: "Minio",
|
Value: "Minio",
|
||||||
Help: "Minio Object Storage",
|
Help: "Minio Object Storage",
|
||||||
|
}, {
|
||||||
|
Value: "Netease",
|
||||||
|
Help: "Netease Object Storage (NOS)",
|
||||||
}, {
|
}, {
|
||||||
Value: "Wasabi",
|
Value: "Wasabi",
|
||||||
Help: "Wasabi Object Storage",
|
Help: "Wasabi Object Storage",
|
||||||
@@ -150,7 +156,7 @@ func init() {
|
|||||||
}, {
|
}, {
|
||||||
Name: "region",
|
Name: "region",
|
||||||
Help: "Region to connect to.\nLeave blank if you are using an S3 clone and you don't have a region.",
|
Help: "Region to connect to.\nLeave blank if you are using an S3 clone and you don't have a region.",
|
||||||
Provider: "!AWS",
|
Provider: "!AWS,Alibaba",
|
||||||
Examples: []fs.OptionExample{{
|
Examples: []fs.OptionExample{{
|
||||||
Value: "",
|
Value: "",
|
||||||
Help: "Use this if unsure. Will use v4 signatures and an empty region.",
|
Help: "Use this if unsure. Will use v4 signatures and an empty region.",
|
||||||
@@ -269,10 +275,73 @@ func init() {
|
|||||||
Value: "s3.tor01.objectstorage.service.networklayer.com",
|
Value: "s3.tor01.objectstorage.service.networklayer.com",
|
||||||
Help: "Toronto Single Site Private Endpoint",
|
Help: "Toronto Single Site Private Endpoint",
|
||||||
}},
|
}},
|
||||||
|
}, {
|
||||||
|
// oss endpoints: https://help.aliyun.com/document_detail/31837.html
|
||||||
|
Name: "endpoint",
|
||||||
|
Help: "Endpoint for OSS API.",
|
||||||
|
Provider: "Alibaba",
|
||||||
|
Examples: []fs.OptionExample{{
|
||||||
|
Value: "oss-cn-hangzhou.aliyuncs.com",
|
||||||
|
Help: "East China 1 (Hangzhou)",
|
||||||
|
}, {
|
||||||
|
Value: "oss-cn-shanghai.aliyuncs.com",
|
||||||
|
Help: "East China 2 (Shanghai)",
|
||||||
|
}, {
|
||||||
|
Value: "oss-cn-qingdao.aliyuncs.com",
|
||||||
|
Help: "North China 1 (Qingdao)",
|
||||||
|
}, {
|
||||||
|
Value: "oss-cn-beijing.aliyuncs.com",
|
||||||
|
Help: "North China 2 (Beijing)",
|
||||||
|
}, {
|
||||||
|
Value: "oss-cn-zhangjiakou.aliyuncs.com",
|
||||||
|
Help: "North China 3 (Zhangjiakou)",
|
||||||
|
}, {
|
||||||
|
Value: "oss-cn-huhehaote.aliyuncs.com",
|
||||||
|
Help: "North China 5 (Huhehaote)",
|
||||||
|
}, {
|
||||||
|
Value: "oss-cn-shenzhen.aliyuncs.com",
|
||||||
|
Help: "South China 1 (Shenzhen)",
|
||||||
|
}, {
|
||||||
|
Value: "oss-cn-hongkong.aliyuncs.com",
|
||||||
|
Help: "Hong Kong (Hong Kong)",
|
||||||
|
}, {
|
||||||
|
Value: "oss-us-west-1.aliyuncs.com",
|
||||||
|
Help: "US West 1 (Silicon Valley)",
|
||||||
|
}, {
|
||||||
|
Value: "oss-us-east-1.aliyuncs.com",
|
||||||
|
Help: "US East 1 (Virginia)",
|
||||||
|
}, {
|
||||||
|
Value: "oss-ap-southeast-1.aliyuncs.com",
|
||||||
|
Help: "Southeast Asia Southeast 1 (Singapore)",
|
||||||
|
}, {
|
||||||
|
Value: "oss-ap-southeast-2.aliyuncs.com",
|
||||||
|
Help: "Asia Pacific Southeast 2 (Sydney)",
|
||||||
|
}, {
|
||||||
|
Value: "oss-ap-southeast-3.aliyuncs.com",
|
||||||
|
Help: "Southeast Asia Southeast 3 (Kuala Lumpur)",
|
||||||
|
}, {
|
||||||
|
Value: "oss-ap-southeast-5.aliyuncs.com",
|
||||||
|
Help: "Asia Pacific Southeast 5 (Jakarta)",
|
||||||
|
}, {
|
||||||
|
Value: "oss-ap-northeast-1.aliyuncs.com",
|
||||||
|
Help: "Asia Pacific Northeast 1 (Japan)",
|
||||||
|
}, {
|
||||||
|
Value: "oss-ap-south-1.aliyuncs.com",
|
||||||
|
Help: "Asia Pacific South 1 (Mumbai)",
|
||||||
|
}, {
|
||||||
|
Value: "oss-eu-central-1.aliyuncs.com",
|
||||||
|
Help: "Central Europe 1 (Frankfurt)",
|
||||||
|
}, {
|
||||||
|
Value: "oss-eu-west-1.aliyuncs.com",
|
||||||
|
Help: "West Europe (London)",
|
||||||
|
}, {
|
||||||
|
Value: "oss-me-east-1.aliyuncs.com",
|
||||||
|
Help: "Middle East 1 (Dubai)",
|
||||||
|
}},
|
||||||
}, {
|
}, {
|
||||||
Name: "endpoint",
|
Name: "endpoint",
|
||||||
Help: "Endpoint for S3 API.\nRequired when using an S3 clone.",
|
Help: "Endpoint for S3 API.\nRequired when using an S3 clone.",
|
||||||
Provider: "!AWS,IBMCOS",
|
Provider: "!AWS,IBMCOS,Alibaba",
|
||||||
Examples: []fs.OptionExample{{
|
Examples: []fs.OptionExample{{
|
||||||
Value: "objects-us-west-1.dream.io",
|
Value: "objects-us-west-1.dream.io",
|
||||||
Help: "Dream Objects endpoint",
|
Help: "Dream Objects endpoint",
|
||||||
@@ -291,7 +360,11 @@ func init() {
|
|||||||
Provider: "DigitalOcean",
|
Provider: "DigitalOcean",
|
||||||
}, {
|
}, {
|
||||||
Value: "s3.wasabisys.com",
|
Value: "s3.wasabisys.com",
|
||||||
Help: "Wasabi Object Storage",
|
Help: "Wasabi US East endpoint",
|
||||||
|
Provider: "Wasabi",
|
||||||
|
}, {
|
||||||
|
Value: "s3.us-west-1.wasabisys.com",
|
||||||
|
Help: "Wasabi US West endpoint",
|
||||||
Provider: "Wasabi",
|
Provider: "Wasabi",
|
||||||
}},
|
}},
|
||||||
}, {
|
}, {
|
||||||
@@ -445,11 +518,13 @@ func init() {
|
|||||||
}, {
|
}, {
|
||||||
Name: "location_constraint",
|
Name: "location_constraint",
|
||||||
Help: "Location constraint - must be set to match the Region.\nLeave blank if not sure. Used when creating buckets only.",
|
Help: "Location constraint - must be set to match the Region.\nLeave blank if not sure. Used when creating buckets only.",
|
||||||
Provider: "!AWS,IBMCOS",
|
Provider: "!AWS,IBMCOS,Alibaba",
|
||||||
}, {
|
}, {
|
||||||
Name: "acl",
|
Name: "acl",
|
||||||
Help: `Canned ACL used when creating buckets and storing or copying objects.
|
Help: `Canned ACL used when creating buckets and storing or copying objects.
|
||||||
|
|
||||||
|
This ACL is used for creating objects and if bucket_acl isn't set, for creating buckets too.
|
||||||
|
|
||||||
For more info visit https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#canned-acl
|
For more info visit https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#canned-acl
|
||||||
|
|
||||||
Note that this ACL is applied when server side copying objects as S3
|
Note that this ACL is applied when server side copying objects as S3
|
||||||
@@ -495,6 +570,28 @@ doesn't copy the ACL from the source but rather writes a fresh one.`,
|
|||||||
Help: "Owner gets FULL_CONTROL. The AuthenticatedUsers group gets READ access. Not supported on Buckets. This acl is available on IBM Cloud (Infra) and On-Premise IBM COS",
|
Help: "Owner gets FULL_CONTROL. The AuthenticatedUsers group gets READ access. Not supported on Buckets. This acl is available on IBM Cloud (Infra) and On-Premise IBM COS",
|
||||||
Provider: "IBMCOS",
|
Provider: "IBMCOS",
|
||||||
}},
|
}},
|
||||||
|
}, {
|
||||||
|
Name: "bucket_acl",
|
||||||
|
Help: `Canned ACL used when creating buckets.
|
||||||
|
|
||||||
|
For more info visit https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#canned-acl
|
||||||
|
|
||||||
|
Note that this ACL is applied when only when creating buckets. If it
|
||||||
|
isn't set then "acl" is used instead.`,
|
||||||
|
Advanced: true,
|
||||||
|
Examples: []fs.OptionExample{{
|
||||||
|
Value: "private",
|
||||||
|
Help: "Owner gets FULL_CONTROL. No one else has access rights (default).",
|
||||||
|
}, {
|
||||||
|
Value: "public-read",
|
||||||
|
Help: "Owner gets FULL_CONTROL. The AllUsers group gets READ access.",
|
||||||
|
}, {
|
||||||
|
Value: "public-read-write",
|
||||||
|
Help: "Owner gets FULL_CONTROL. The AllUsers group gets READ and WRITE access.\nGranting this on a bucket is generally not recommended.",
|
||||||
|
}, {
|
||||||
|
Value: "authenticated-read",
|
||||||
|
Help: "Owner gets FULL_CONTROL. The AuthenticatedUsers group gets READ access.",
|
||||||
|
}},
|
||||||
}, {
|
}, {
|
||||||
Name: "server_side_encryption",
|
Name: "server_side_encryption",
|
||||||
Help: "The server-side encryption algorithm used when storing this object in S3.",
|
Help: "The server-side encryption algorithm used when storing this object in S3.",
|
||||||
@@ -539,13 +636,42 @@ doesn't copy the ACL from the source but rather writes a fresh one.`,
|
|||||||
}, {
|
}, {
|
||||||
Value: "ONEZONE_IA",
|
Value: "ONEZONE_IA",
|
||||||
Help: "One Zone Infrequent Access storage class",
|
Help: "One Zone Infrequent Access storage class",
|
||||||
|
}, {
|
||||||
|
Value: "GLACIER",
|
||||||
|
Help: "Glacier storage class",
|
||||||
}},
|
}},
|
||||||
|
}, {
|
||||||
|
// Mapping from here: https://www.alibabacloud.com/help/doc-detail/64919.htm
|
||||||
|
Name: "storage_class",
|
||||||
|
Help: "The storage class to use when storing new objects in OSS.",
|
||||||
|
Provider: "Alibaba",
|
||||||
|
Examples: []fs.OptionExample{{
|
||||||
|
Value: "",
|
||||||
|
Help: "Default",
|
||||||
|
}, {
|
||||||
|
Value: "STANDARD",
|
||||||
|
Help: "Standard storage class",
|
||||||
|
}, {
|
||||||
|
Value: "GLACIER",
|
||||||
|
Help: "Archive storage mode.",
|
||||||
|
}, {
|
||||||
|
Value: "STANDARD_IA",
|
||||||
|
Help: "Infrequent access storage mode.",
|
||||||
|
}},
|
||||||
|
}, {
|
||||||
|
Name: "upload_cutoff",
|
||||||
|
Help: `Cutoff for switching to chunked upload
|
||||||
|
|
||||||
|
Any files larger than this will be uploaded in chunks of chunk_size.
|
||||||
|
The minimum is 0 and the maximum is 5GB.`,
|
||||||
|
Default: defaultUploadCutoff,
|
||||||
|
Advanced: true,
|
||||||
}, {
|
}, {
|
||||||
Name: "chunk_size",
|
Name: "chunk_size",
|
||||||
Help: `Chunk size to use for uploading.
|
Help: `Chunk size to use for uploading.
|
||||||
|
|
||||||
Any files larger than this will be uploaded in chunks of this
|
When uploading files larger than upload_cutoff they will be uploaded
|
||||||
size. The default is 5MB. The minimum is 5MB.
|
as multipart uploads using this chunk size.
|
||||||
|
|
||||||
Note that "--s3-upload-concurrency" chunks of this size are buffered
|
Note that "--s3-upload-concurrency" chunks of this size are buffered
|
||||||
in memory per transfer.
|
in memory per transfer.
|
||||||
@@ -573,7 +699,7 @@ concurrently.
|
|||||||
If you are uploading small numbers of large file over high speed link
|
If you are uploading small numbers of large file over high speed link
|
||||||
and these uploads do not fully utilize your bandwidth, then increasing
|
and these uploads do not fully utilize your bandwidth, then increasing
|
||||||
this may help to speed up the transfers.`,
|
this may help to speed up the transfers.`,
|
||||||
Default: 2,
|
Default: 4,
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
}, {
|
}, {
|
||||||
Name: "force_path_style",
|
Name: "force_path_style",
|
||||||
@@ -603,14 +729,16 @@ Use this only if v4 signatures don't work, eg pre Jewel/v10 CEPH.`,
|
|||||||
|
|
||||||
// Constants
|
// Constants
|
||||||
const (
|
const (
|
||||||
metaMtime = "Mtime" // the meta key to store mtime in - eg X-Amz-Meta-Mtime
|
metaMtime = "Mtime" // the meta key to store mtime in - eg X-Amz-Meta-Mtime
|
||||||
metaMD5Hash = "Md5chksum" // the meta key to store md5hash in
|
metaMD5Hash = "Md5chksum" // the meta key to store md5hash in
|
||||||
listChunkSize = 1000 // number of items to read at once
|
listChunkSize = 1000 // number of items to read at once
|
||||||
maxRetries = 10 // number of retries to make of operations
|
maxRetries = 10 // number of retries to make of operations
|
||||||
maxSizeForCopy = 5 * 1024 * 1024 * 1024 // The maximum size of object we can COPY
|
maxSizeForCopy = 5 * 1024 * 1024 * 1024 // The maximum size of object we can COPY
|
||||||
maxFileSize = 5 * 1024 * 1024 * 1024 * 1024 // largest possible upload file size
|
maxFileSize = 5 * 1024 * 1024 * 1024 * 1024 // largest possible upload file size
|
||||||
minChunkSize = fs.SizeSuffix(s3manager.MinUploadPartSize)
|
minChunkSize = fs.SizeSuffix(s3manager.MinUploadPartSize)
|
||||||
minSleep = 10 * time.Millisecond // In case of error, start at 10ms sleep.
|
defaultUploadCutoff = fs.SizeSuffix(200 * 1024 * 1024)
|
||||||
|
maxUploadCutoff = fs.SizeSuffix(5 * 1024 * 1024 * 1024)
|
||||||
|
minSleep = 10 * time.Millisecond // In case of error, start at 10ms sleep.
|
||||||
)
|
)
|
||||||
|
|
||||||
// Options defines the configuration for this backend
|
// Options defines the configuration for this backend
|
||||||
@@ -623,9 +751,11 @@ type Options struct {
|
|||||||
Endpoint string `config:"endpoint"`
|
Endpoint string `config:"endpoint"`
|
||||||
LocationConstraint string `config:"location_constraint"`
|
LocationConstraint string `config:"location_constraint"`
|
||||||
ACL string `config:"acl"`
|
ACL string `config:"acl"`
|
||||||
|
BucketACL string `config:"bucket_acl"`
|
||||||
ServerSideEncryption string `config:"server_side_encryption"`
|
ServerSideEncryption string `config:"server_side_encryption"`
|
||||||
SSEKMSKeyID string `config:"sse_kms_key_id"`
|
SSEKMSKeyID string `config:"sse_kms_key_id"`
|
||||||
StorageClass string `config:"storage_class"`
|
StorageClass string `config:"storage_class"`
|
||||||
|
UploadCutoff fs.SizeSuffix `config:"upload_cutoff"`
|
||||||
ChunkSize fs.SizeSuffix `config:"chunk_size"`
|
ChunkSize fs.SizeSuffix `config:"chunk_size"`
|
||||||
DisableChecksum bool `config:"disable_checksum"`
|
DisableChecksum bool `config:"disable_checksum"`
|
||||||
SessionToken string `config:"session_token"`
|
SessionToken string `config:"session_token"`
|
||||||
@@ -647,6 +777,7 @@ type Fs struct {
|
|||||||
bucketOK bool // true if we have created the bucket
|
bucketOK bool // true if we have created the bucket
|
||||||
bucketDeleted bool // true if we have deleted the bucket
|
bucketDeleted bool // true if we have deleted the bucket
|
||||||
pacer *pacer.Pacer // To pace the API calls
|
pacer *pacer.Pacer // To pace the API calls
|
||||||
|
srv *http.Client // a plain http client
|
||||||
}
|
}
|
||||||
|
|
||||||
// Object describes a s3 object
|
// Object describes a s3 object
|
||||||
@@ -695,23 +826,31 @@ func (f *Fs) Features() *fs.Features {
|
|||||||
// retryErrorCodes is a slice of error codes that we will retry
|
// retryErrorCodes is a slice of error codes that we will retry
|
||||||
// See: https://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html
|
// See: https://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html
|
||||||
var retryErrorCodes = []int{
|
var retryErrorCodes = []int{
|
||||||
409, // Conflict - various states that could be resolved on a retry
|
// 409, // Conflict - various states that could be resolved on a retry
|
||||||
503, // Service Unavailable/Slow Down - "Reduce your request rate"
|
503, // Service Unavailable/Slow Down - "Reduce your request rate"
|
||||||
}
|
}
|
||||||
|
|
||||||
//S3 is pretty resilient, and the built in retry handling is probably sufficient
|
//S3 is pretty resilient, and the built in retry handling is probably sufficient
|
||||||
// as it should notice closed connections and timeouts which are the most likely
|
// as it should notice closed connections and timeouts which are the most likely
|
||||||
// sort of failure modes
|
// sort of failure modes
|
||||||
func shouldRetry(err error) (bool, error) {
|
func (f *Fs) shouldRetry(err error) (bool, error) {
|
||||||
|
|
||||||
// If this is an awserr object, try and extract more useful information to determine if we should retry
|
// If this is an awserr object, try and extract more useful information to determine if we should retry
|
||||||
if awsError, ok := err.(awserr.Error); ok {
|
if awsError, ok := err.(awserr.Error); ok {
|
||||||
// Simple case, check the original embedded error in case it's generically retriable
|
// Simple case, check the original embedded error in case it's generically retriable
|
||||||
if fserrors.ShouldRetry(awsError.OrigErr()) {
|
if fserrors.ShouldRetry(awsError.OrigErr()) {
|
||||||
return true, err
|
return true, err
|
||||||
}
|
}
|
||||||
//Failing that, if it's a RequestFailure it's probably got an http status code we can check
|
// Failing that, if it's a RequestFailure it's probably got an http status code we can check
|
||||||
if reqErr, ok := err.(awserr.RequestFailure); ok {
|
if reqErr, ok := err.(awserr.RequestFailure); ok {
|
||||||
|
// 301 if wrong region for bucket
|
||||||
|
if reqErr.StatusCode() == http.StatusMovedPermanently {
|
||||||
|
urfbErr := f.updateRegionForBucket()
|
||||||
|
if urfbErr != nil {
|
||||||
|
fs.Errorf(f, "Failed to update region for bucket: %v", urfbErr)
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return true, err
|
||||||
|
}
|
||||||
for _, e := range retryErrorCodes {
|
for _, e := range retryErrorCodes {
|
||||||
if reqErr.StatusCode() == e {
|
if reqErr.StatusCode() == e {
|
||||||
return true, err
|
return true, err
|
||||||
@@ -719,7 +858,7 @@ func shouldRetry(err error) (bool, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//Ok, not an awserr, check for generic failure conditions
|
// Ok, not an awserr, check for generic failure conditions
|
||||||
return fserrors.ShouldRetry(err), err
|
return fserrors.ShouldRetry(err), err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -796,16 +935,37 @@ func s3Connection(opt *Options) (*s3.S3, *session.Session, error) {
|
|||||||
if opt.Region == "" {
|
if opt.Region == "" {
|
||||||
opt.Region = "us-east-1"
|
opt.Region = "us-east-1"
|
||||||
}
|
}
|
||||||
|
if opt.Provider == "Alibaba" || opt.Provider == "Netease" {
|
||||||
|
opt.ForcePathStyle = false
|
||||||
|
}
|
||||||
awsConfig := aws.NewConfig().
|
awsConfig := aws.NewConfig().
|
||||||
WithRegion(opt.Region).
|
|
||||||
WithMaxRetries(maxRetries).
|
WithMaxRetries(maxRetries).
|
||||||
WithCredentials(cred).
|
WithCredentials(cred).
|
||||||
WithEndpoint(opt.Endpoint).
|
|
||||||
WithHTTPClient(fshttp.NewClient(fs.Config)).
|
WithHTTPClient(fshttp.NewClient(fs.Config)).
|
||||||
WithS3ForcePathStyle(opt.ForcePathStyle)
|
WithS3ForcePathStyle(opt.ForcePathStyle)
|
||||||
|
if opt.Region != "" {
|
||||||
|
awsConfig.WithRegion(opt.Region)
|
||||||
|
}
|
||||||
|
if opt.Endpoint != "" {
|
||||||
|
awsConfig.WithEndpoint(opt.Endpoint)
|
||||||
|
}
|
||||||
|
|
||||||
// awsConfig.WithLogLevel(aws.LogDebugWithSigning)
|
// awsConfig.WithLogLevel(aws.LogDebugWithSigning)
|
||||||
ses := session.New()
|
awsSessionOpts := session.Options{
|
||||||
c := s3.New(ses, awsConfig)
|
Config: *awsConfig,
|
||||||
|
}
|
||||||
|
if opt.EnvAuth && opt.AccessKeyID == "" && opt.SecretAccessKey == "" {
|
||||||
|
// Enable loading config options from ~/.aws/config (selected by AWS_PROFILE env)
|
||||||
|
awsSessionOpts.SharedConfigState = session.SharedConfigEnable
|
||||||
|
// The session constructor (aws/session/mergeConfigSrcs) will only use the user's preferred credential source
|
||||||
|
// (from the shared config file) if the passed-in Options.Config.Credentials is nil.
|
||||||
|
awsSessionOpts.Config.Credentials = nil
|
||||||
|
}
|
||||||
|
ses, err := session.NewSessionWithOptions(awsSessionOpts)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
c := s3.New(ses)
|
||||||
if opt.V2Auth || opt.Region == "other-v2-signature" {
|
if opt.V2Auth || opt.Region == "other-v2-signature" {
|
||||||
fs.Debugf(nil, "Using v2 auth")
|
fs.Debugf(nil, "Using v2 auth")
|
||||||
signer := func(req *request.Request) {
|
signer := func(req *request.Request) {
|
||||||
@@ -837,6 +997,21 @@ func (f *Fs) setUploadChunkSize(cs fs.SizeSuffix) (old fs.SizeSuffix, err error)
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func checkUploadCutoff(cs fs.SizeSuffix) error {
|
||||||
|
if cs > maxUploadCutoff {
|
||||||
|
return errors.Errorf("%s is greater than %s", cs, maxUploadCutoff)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fs) setUploadCutoff(cs fs.SizeSuffix) (old fs.SizeSuffix, err error) {
|
||||||
|
err = checkUploadCutoff(cs)
|
||||||
|
if err == nil {
|
||||||
|
old, f.opt.UploadCutoff = f.opt.UploadCutoff, cs
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// NewFs constructs an Fs from the path, bucket:path
|
// NewFs constructs an Fs from the path, bucket:path
|
||||||
func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
||||||
// Parse config into Options struct
|
// Parse config into Options struct
|
||||||
@@ -849,10 +1024,20 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "s3: chunk size")
|
return nil, errors.Wrap(err, "s3: chunk size")
|
||||||
}
|
}
|
||||||
|
err = checkUploadCutoff(opt.UploadCutoff)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "s3: upload cutoff")
|
||||||
|
}
|
||||||
bucket, directory, err := s3ParsePath(root)
|
bucket, directory, err := s3ParsePath(root)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if opt.ACL == "" {
|
||||||
|
opt.ACL = "private"
|
||||||
|
}
|
||||||
|
if opt.BucketACL == "" {
|
||||||
|
opt.BucketACL = opt.ACL
|
||||||
|
}
|
||||||
c, ses, err := s3Connection(opt)
|
c, ses, err := s3Connection(opt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -865,6 +1050,7 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
bucket: bucket,
|
bucket: bucket,
|
||||||
ses: ses,
|
ses: ses,
|
||||||
pacer: pacer.New().SetMinSleep(minSleep).SetPacer(pacer.S3Pacer),
|
pacer: pacer.New().SetMinSleep(minSleep).SetPacer(pacer.S3Pacer),
|
||||||
|
srv: fshttp.NewClient(fs.Config),
|
||||||
}
|
}
|
||||||
f.features = (&fs.Features{
|
f.features = (&fs.Features{
|
||||||
ReadMimeType: true,
|
ReadMimeType: true,
|
||||||
@@ -880,7 +1066,7 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
}
|
}
|
||||||
err = f.pacer.Call(func() (bool, error) {
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
_, err = f.c.HeadObject(&req)
|
_, err = f.c.HeadObject(&req)
|
||||||
return shouldRetry(err)
|
return f.shouldRetry(err)
|
||||||
})
|
})
|
||||||
if err == nil {
|
if err == nil {
|
||||||
f.root = path.Dir(directory)
|
f.root = path.Dir(directory)
|
||||||
@@ -930,6 +1116,51 @@ func (f *Fs) NewObject(remote string) (fs.Object, error) {
|
|||||||
return f.newObjectWithInfo(remote, nil)
|
return f.newObjectWithInfo(remote, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Gets the bucket location
|
||||||
|
func (f *Fs) getBucketLocation() (string, error) {
|
||||||
|
req := s3.GetBucketLocationInput{
|
||||||
|
Bucket: &f.bucket,
|
||||||
|
}
|
||||||
|
var resp *s3.GetBucketLocationOutput
|
||||||
|
var err error
|
||||||
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
|
resp, err = f.c.GetBucketLocation(&req)
|
||||||
|
return f.shouldRetry(err)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return s3.NormalizeBucketLocation(aws.StringValue(resp.LocationConstraint)), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Updates the region for the bucket by reading the region from the
|
||||||
|
// bucket then updating the session.
|
||||||
|
func (f *Fs) updateRegionForBucket() error {
|
||||||
|
region, err := f.getBucketLocation()
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "reading bucket location failed")
|
||||||
|
}
|
||||||
|
if aws.StringValue(f.c.Config.Endpoint) != "" {
|
||||||
|
return errors.Errorf("can't set region to %q as endpoint is set", region)
|
||||||
|
}
|
||||||
|
if aws.StringValue(f.c.Config.Region) == region {
|
||||||
|
return errors.Errorf("region is already %q - not updating", region)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make a new session with the new region
|
||||||
|
oldRegion := f.opt.Region
|
||||||
|
f.opt.Region = region
|
||||||
|
c, ses, err := s3Connection(&f.opt)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "creating new session failed")
|
||||||
|
}
|
||||||
|
f.c = c
|
||||||
|
f.ses = ses
|
||||||
|
|
||||||
|
fs.Logf(f, "Switched region to %q from %q", region, oldRegion)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// listFn is called from list to handle an object.
|
// listFn is called from list to handle an object.
|
||||||
type listFn func(remote string, object *s3.Object, isDirectory bool) error
|
type listFn func(remote string, object *s3.Object, isDirectory bool) error
|
||||||
|
|
||||||
@@ -962,7 +1193,7 @@ func (f *Fs) list(dir string, recurse bool, fn listFn) error {
|
|||||||
var err error
|
var err error
|
||||||
err = f.pacer.Call(func() (bool, error) {
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
resp, err = f.c.ListObjects(&req)
|
resp, err = f.c.ListObjects(&req)
|
||||||
return shouldRetry(err)
|
return f.shouldRetry(err)
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if awsErr, ok := err.(awserr.RequestFailure); ok {
|
if awsErr, ok := err.(awserr.RequestFailure); ok {
|
||||||
@@ -1091,7 +1322,7 @@ func (f *Fs) listBuckets(dir string) (entries fs.DirEntries, err error) {
|
|||||||
var resp *s3.ListBucketsOutput
|
var resp *s3.ListBucketsOutput
|
||||||
err = f.pacer.Call(func() (bool, error) {
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
resp, err = f.c.ListBuckets(&req)
|
resp, err = f.c.ListBuckets(&req)
|
||||||
return shouldRetry(err)
|
return f.shouldRetry(err)
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -1179,7 +1410,7 @@ func (f *Fs) dirExists() (bool, error) {
|
|||||||
}
|
}
|
||||||
err := f.pacer.Call(func() (bool, error) {
|
err := f.pacer.Call(func() (bool, error) {
|
||||||
_, err := f.c.HeadBucket(&req)
|
_, err := f.c.HeadBucket(&req)
|
||||||
return shouldRetry(err)
|
return f.shouldRetry(err)
|
||||||
})
|
})
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return true, nil
|
return true, nil
|
||||||
@@ -1210,7 +1441,7 @@ func (f *Fs) Mkdir(dir string) error {
|
|||||||
}
|
}
|
||||||
req := s3.CreateBucketInput{
|
req := s3.CreateBucketInput{
|
||||||
Bucket: &f.bucket,
|
Bucket: &f.bucket,
|
||||||
ACL: &f.opt.ACL,
|
ACL: &f.opt.BucketACL,
|
||||||
}
|
}
|
||||||
if f.opt.LocationConstraint != "" {
|
if f.opt.LocationConstraint != "" {
|
||||||
req.CreateBucketConfiguration = &s3.CreateBucketConfiguration{
|
req.CreateBucketConfiguration = &s3.CreateBucketConfiguration{
|
||||||
@@ -1219,7 +1450,7 @@ func (f *Fs) Mkdir(dir string) error {
|
|||||||
}
|
}
|
||||||
err := f.pacer.Call(func() (bool, error) {
|
err := f.pacer.Call(func() (bool, error) {
|
||||||
_, err := f.c.CreateBucket(&req)
|
_, err := f.c.CreateBucket(&req)
|
||||||
return shouldRetry(err)
|
return f.shouldRetry(err)
|
||||||
})
|
})
|
||||||
if err, ok := err.(awserr.Error); ok {
|
if err, ok := err.(awserr.Error); ok {
|
||||||
if err.Code() == "BucketAlreadyOwnedByYou" {
|
if err.Code() == "BucketAlreadyOwnedByYou" {
|
||||||
@@ -1229,6 +1460,7 @@ func (f *Fs) Mkdir(dir string) error {
|
|||||||
if err == nil {
|
if err == nil {
|
||||||
f.bucketOK = true
|
f.bucketOK = true
|
||||||
f.bucketDeleted = false
|
f.bucketDeleted = false
|
||||||
|
fs.Infof(f, "Bucket created with ACL %q", *req.ACL)
|
||||||
}
|
}
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -1247,11 +1479,12 @@ func (f *Fs) Rmdir(dir string) error {
|
|||||||
}
|
}
|
||||||
err := f.pacer.Call(func() (bool, error) {
|
err := f.pacer.Call(func() (bool, error) {
|
||||||
_, err := f.c.DeleteBucket(&req)
|
_, err := f.c.DeleteBucket(&req)
|
||||||
return shouldRetry(err)
|
return f.shouldRetry(err)
|
||||||
})
|
})
|
||||||
if err == nil {
|
if err == nil {
|
||||||
f.bucketOK = false
|
f.bucketOK = false
|
||||||
f.bucketDeleted = true
|
f.bucketDeleted = true
|
||||||
|
fs.Infof(f, "Bucket deleted")
|
||||||
}
|
}
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -1307,7 +1540,7 @@ func (f *Fs) Copy(src fs.Object, remote string) (fs.Object, error) {
|
|||||||
}
|
}
|
||||||
err = f.pacer.Call(func() (bool, error) {
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
_, err = f.c.CopyObject(&req)
|
_, err = f.c.CopyObject(&req)
|
||||||
return shouldRetry(err)
|
return f.shouldRetry(err)
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -1389,7 +1622,7 @@ func (o *Object) readMetaData() (err error) {
|
|||||||
err = o.fs.pacer.Call(func() (bool, error) {
|
err = o.fs.pacer.Call(func() (bool, error) {
|
||||||
var err error
|
var err error
|
||||||
resp, err = o.fs.c.HeadObject(&req)
|
resp, err = o.fs.c.HeadObject(&req)
|
||||||
return shouldRetry(err)
|
return o.fs.shouldRetry(err)
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if awsErr, ok := err.(awserr.RequestFailure); ok {
|
if awsErr, ok := err.(awserr.RequestFailure); ok {
|
||||||
@@ -1485,7 +1718,7 @@ func (o *Object) SetModTime(modTime time.Time) error {
|
|||||||
}
|
}
|
||||||
err = o.fs.pacer.Call(func() (bool, error) {
|
err = o.fs.pacer.Call(func() (bool, error) {
|
||||||
_, err := o.fs.c.CopyObject(&req)
|
_, err := o.fs.c.CopyObject(&req)
|
||||||
return shouldRetry(err)
|
return o.fs.shouldRetry(err)
|
||||||
})
|
})
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -1517,7 +1750,7 @@ func (o *Object) Open(options ...fs.OpenOption) (in io.ReadCloser, err error) {
|
|||||||
err = o.fs.pacer.Call(func() (bool, error) {
|
err = o.fs.pacer.Call(func() (bool, error) {
|
||||||
var err error
|
var err error
|
||||||
resp, err = o.fs.c.GetObject(&req)
|
resp, err = o.fs.c.GetObject(&req)
|
||||||
return shouldRetry(err)
|
return o.fs.shouldRetry(err)
|
||||||
})
|
})
|
||||||
if err, ok := err.(awserr.RequestFailure); ok {
|
if err, ok := err.(awserr.RequestFailure); ok {
|
||||||
if err.Code() == "InvalidObjectState" {
|
if err.Code() == "InvalidObjectState" {
|
||||||
@@ -1539,38 +1772,46 @@ func (o *Object) Update(in io.Reader, src fs.ObjectInfo, options ...fs.OpenOptio
|
|||||||
modTime := src.ModTime()
|
modTime := src.ModTime()
|
||||||
size := src.Size()
|
size := src.Size()
|
||||||
|
|
||||||
uploader := s3manager.NewUploader(o.fs.ses, func(u *s3manager.Uploader) {
|
multipart := size < 0 || size >= int64(o.fs.opt.UploadCutoff)
|
||||||
u.Concurrency = o.fs.opt.UploadConcurrency
|
var uploader *s3manager.Uploader
|
||||||
u.LeavePartsOnError = false
|
if multipart {
|
||||||
u.S3 = o.fs.c
|
uploader = s3manager.NewUploader(o.fs.ses, func(u *s3manager.Uploader) {
|
||||||
u.PartSize = int64(o.fs.opt.ChunkSize)
|
u.Concurrency = o.fs.opt.UploadConcurrency
|
||||||
|
u.LeavePartsOnError = false
|
||||||
|
u.S3 = o.fs.c
|
||||||
|
u.PartSize = int64(o.fs.opt.ChunkSize)
|
||||||
|
|
||||||
if size == -1 {
|
if size == -1 {
|
||||||
// Make parts as small as possible while still being able to upload to the
|
// Make parts as small as possible while still being able to upload to the
|
||||||
// S3 file size limit. Rounded up to nearest MB.
|
// S3 file size limit. Rounded up to nearest MB.
|
||||||
u.PartSize = (((maxFileSize / s3manager.MaxUploadParts) >> 20) + 1) << 20
|
u.PartSize = (((maxFileSize / s3manager.MaxUploadParts) >> 20) + 1) << 20
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// Adjust PartSize until the number of parts is small enough.
|
// Adjust PartSize until the number of parts is small enough.
|
||||||
if size/u.PartSize >= s3manager.MaxUploadParts {
|
if size/u.PartSize >= s3manager.MaxUploadParts {
|
||||||
// Calculate partition size rounded up to the nearest MB
|
// Calculate partition size rounded up to the nearest MB
|
||||||
u.PartSize = (((size / s3manager.MaxUploadParts) >> 20) + 1) << 20
|
u.PartSize = (((size / s3manager.MaxUploadParts) >> 20) + 1) << 20
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
}
|
||||||
|
|
||||||
// Set the mtime in the meta data
|
// Set the mtime in the meta data
|
||||||
metadata := map[string]*string{
|
metadata := map[string]*string{
|
||||||
metaMtime: aws.String(swift.TimeToFloatString(modTime)),
|
metaMtime: aws.String(swift.TimeToFloatString(modTime)),
|
||||||
}
|
}
|
||||||
|
|
||||||
if !o.fs.opt.DisableChecksum && size > uploader.PartSize {
|
// read the md5sum if available for non multpart and if
|
||||||
|
// disable checksum isn't present.
|
||||||
|
var md5sum string
|
||||||
|
if !multipart || !o.fs.opt.DisableChecksum {
|
||||||
hash, err := src.Hash(hash.MD5)
|
hash, err := src.Hash(hash.MD5)
|
||||||
|
|
||||||
if err == nil && matchMd5.MatchString(hash) {
|
if err == nil && matchMd5.MatchString(hash) {
|
||||||
hashBytes, err := hex.DecodeString(hash)
|
hashBytes, err := hex.DecodeString(hash)
|
||||||
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
metadata[metaMD5Hash] = aws.String(base64.StdEncoding.EncodeToString(hashBytes))
|
md5sum = base64.StdEncoding.EncodeToString(hashBytes)
|
||||||
|
if multipart {
|
||||||
|
metadata[metaMD5Hash] = &md5sum
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1579,30 +1820,98 @@ func (o *Object) Update(in io.Reader, src fs.ObjectInfo, options ...fs.OpenOptio
|
|||||||
mimeType := fs.MimeType(src)
|
mimeType := fs.MimeType(src)
|
||||||
|
|
||||||
key := o.fs.root + o.remote
|
key := o.fs.root + o.remote
|
||||||
req := s3manager.UploadInput{
|
if multipart {
|
||||||
Bucket: &o.fs.bucket,
|
req := s3manager.UploadInput{
|
||||||
ACL: &o.fs.opt.ACL,
|
Bucket: &o.fs.bucket,
|
||||||
Key: &key,
|
ACL: &o.fs.opt.ACL,
|
||||||
Body: in,
|
Key: &key,
|
||||||
ContentType: &mimeType,
|
Body: in,
|
||||||
Metadata: metadata,
|
ContentType: &mimeType,
|
||||||
//ContentLength: &size,
|
Metadata: metadata,
|
||||||
}
|
//ContentLength: &size,
|
||||||
if o.fs.opt.ServerSideEncryption != "" {
|
}
|
||||||
req.ServerSideEncryption = &o.fs.opt.ServerSideEncryption
|
if o.fs.opt.ServerSideEncryption != "" {
|
||||||
}
|
req.ServerSideEncryption = &o.fs.opt.ServerSideEncryption
|
||||||
if o.fs.opt.SSEKMSKeyID != "" {
|
}
|
||||||
req.SSEKMSKeyId = &o.fs.opt.SSEKMSKeyID
|
if o.fs.opt.SSEKMSKeyID != "" {
|
||||||
}
|
req.SSEKMSKeyId = &o.fs.opt.SSEKMSKeyID
|
||||||
if o.fs.opt.StorageClass != "" {
|
}
|
||||||
req.StorageClass = &o.fs.opt.StorageClass
|
if o.fs.opt.StorageClass != "" {
|
||||||
}
|
req.StorageClass = &o.fs.opt.StorageClass
|
||||||
err = o.fs.pacer.CallNoRetry(func() (bool, error) {
|
}
|
||||||
_, err = uploader.Upload(&req)
|
err = o.fs.pacer.CallNoRetry(func() (bool, error) {
|
||||||
return shouldRetry(err)
|
_, err = uploader.Upload(&req)
|
||||||
})
|
return o.fs.shouldRetry(err)
|
||||||
if err != nil {
|
})
|
||||||
return err
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
req := s3.PutObjectInput{
|
||||||
|
Bucket: &o.fs.bucket,
|
||||||
|
ACL: &o.fs.opt.ACL,
|
||||||
|
Key: &key,
|
||||||
|
ContentType: &mimeType,
|
||||||
|
Metadata: metadata,
|
||||||
|
}
|
||||||
|
if md5sum != "" {
|
||||||
|
req.ContentMD5 = &md5sum
|
||||||
|
}
|
||||||
|
if o.fs.opt.ServerSideEncryption != "" {
|
||||||
|
req.ServerSideEncryption = &o.fs.opt.ServerSideEncryption
|
||||||
|
}
|
||||||
|
if o.fs.opt.SSEKMSKeyID != "" {
|
||||||
|
req.SSEKMSKeyId = &o.fs.opt.SSEKMSKeyID
|
||||||
|
}
|
||||||
|
if o.fs.opt.StorageClass != "" {
|
||||||
|
req.StorageClass = &o.fs.opt.StorageClass
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create the request
|
||||||
|
putObj, _ := o.fs.c.PutObjectRequest(&req)
|
||||||
|
|
||||||
|
// Sign it so we can upload using a presigned request.
|
||||||
|
//
|
||||||
|
// Note the SDK doesn't currently support streaming to
|
||||||
|
// PutObject so we'll use this work-around.
|
||||||
|
url, headers, err := putObj.PresignRequest(15 * time.Minute)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "s3 upload: sign request")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set request to nil if empty so as not to make chunked encoding
|
||||||
|
if size == 0 {
|
||||||
|
in = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// create the vanilla http request
|
||||||
|
httpReq, err := http.NewRequest("PUT", url, in)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "s3 upload: new request")
|
||||||
|
}
|
||||||
|
|
||||||
|
// set the headers we signed and the length
|
||||||
|
httpReq.Header = headers
|
||||||
|
httpReq.ContentLength = size
|
||||||
|
|
||||||
|
err = o.fs.pacer.CallNoRetry(func() (bool, error) {
|
||||||
|
resp, err := o.fs.srv.Do(httpReq)
|
||||||
|
if err != nil {
|
||||||
|
return o.fs.shouldRetry(err)
|
||||||
|
}
|
||||||
|
body, err := rest.ReadBody(resp)
|
||||||
|
if err != nil {
|
||||||
|
return o.fs.shouldRetry(err)
|
||||||
|
}
|
||||||
|
if resp.StatusCode >= 200 && resp.StatusCode < 299 {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
err = errors.Errorf("s3 upload: %s: %s", resp.Status, body)
|
||||||
|
return fserrors.ShouldRetryHTTP(resp, retryErrorCodes), err
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read the metadata from the newly created object
|
// Read the metadata from the newly created object
|
||||||
@@ -1620,7 +1929,7 @@ func (o *Object) Remove() error {
|
|||||||
}
|
}
|
||||||
err := o.fs.pacer.Call(func() (bool, error) {
|
err := o.fs.pacer.Call(func() (bool, error) {
|
||||||
_, err := o.fs.c.DeleteObject(&req)
|
_, err := o.fs.c.DeleteObject(&req)
|
||||||
return shouldRetry(err)
|
return o.fs.shouldRetry(err)
|
||||||
})
|
})
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,4 +23,8 @@ func (f *Fs) SetUploadChunkSize(cs fs.SizeSuffix) (fs.SizeSuffix, error) {
|
|||||||
return f.setUploadChunkSize(cs)
|
return f.setUploadChunkSize(cs)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (f *Fs) SetUploadCutoff(cs fs.SizeSuffix) (fs.SizeSuffix, error) {
|
||||||
|
return f.setUploadCutoff(cs)
|
||||||
|
}
|
||||||
|
|
||||||
var _ fstests.SetUploadChunkSizer = (*Fs)(nil)
|
var _ fstests.SetUploadChunkSizer = (*Fs)(nil)
|
||||||
+83
-9
@@ -28,7 +28,7 @@ import (
|
|||||||
"github.com/ncw/rclone/lib/readers"
|
"github.com/ncw/rclone/lib/readers"
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"github.com/pkg/sftp"
|
"github.com/pkg/sftp"
|
||||||
"github.com/xanzy/ssh-agent"
|
sshagent "github.com/xanzy/ssh-agent"
|
||||||
"golang.org/x/crypto/ssh"
|
"golang.org/x/crypto/ssh"
|
||||||
"golang.org/x/time/rate"
|
"golang.org/x/time/rate"
|
||||||
)
|
)
|
||||||
@@ -66,7 +66,22 @@ func init() {
|
|||||||
IsPassword: true,
|
IsPassword: true,
|
||||||
}, {
|
}, {
|
||||||
Name: "key_file",
|
Name: "key_file",
|
||||||
Help: "Path to unencrypted PEM-encoded private key file, leave blank to use ssh-agent.",
|
Help: "Path to PEM-encoded private key file, leave blank or set key-use-agent to use ssh-agent.",
|
||||||
|
}, {
|
||||||
|
Name: "key_file_pass",
|
||||||
|
Help: `The passphrase to decrypt the PEM-encoded private key file.
|
||||||
|
|
||||||
|
Only PEM encrypted key files (old OpenSSH format) are supported. Encrypted keys
|
||||||
|
in the new OpenSSH format can't be used.`,
|
||||||
|
IsPassword: true,
|
||||||
|
}, {
|
||||||
|
Name: "key_use_agent",
|
||||||
|
Help: `When set forces the usage of the ssh-agent.
|
||||||
|
|
||||||
|
When key-file is also set, the ".pub" file of the specified key-file is read and only the associated key is
|
||||||
|
requested from the ssh-agent. This allows to avoid ` + "`Too many authentication failures for *username*`" + ` errors
|
||||||
|
when the ssh-agent contains many keys.`,
|
||||||
|
Default: false,
|
||||||
}, {
|
}, {
|
||||||
Name: "use_insecure_cipher",
|
Name: "use_insecure_cipher",
|
||||||
Help: "Enable the use of the aes128-cbc cipher. This cipher is insecure and may allow plaintext data to be recovered by an attacker.",
|
Help: "Enable the use of the aes128-cbc cipher. This cipher is insecure and may allow plaintext data to be recovered by an attacker.",
|
||||||
@@ -122,6 +137,8 @@ type Options struct {
|
|||||||
Port string `config:"port"`
|
Port string `config:"port"`
|
||||||
Pass string `config:"pass"`
|
Pass string `config:"pass"`
|
||||||
KeyFile string `config:"key_file"`
|
KeyFile string `config:"key_file"`
|
||||||
|
KeyFilePass string `config:"key_file_pass"`
|
||||||
|
KeyUseAgent bool `config:"key_use_agent"`
|
||||||
UseInsecureCipher bool `config:"use_insecure_cipher"`
|
UseInsecureCipher bool `config:"use_insecure_cipher"`
|
||||||
DisableHashCheck bool `config:"disable_hashcheck"`
|
DisableHashCheck bool `config:"disable_hashcheck"`
|
||||||
AskPassword bool `config:"ask_password"`
|
AskPassword bool `config:"ask_password"`
|
||||||
@@ -298,6 +315,18 @@ func (f *Fs) putSftpConnection(pc **conn, err error) {
|
|||||||
f.poolMu.Unlock()
|
f.poolMu.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// shellExpand replaces a leading "~" with "${HOME}" and expands all environment
|
||||||
|
// variables afterwards.
|
||||||
|
func shellExpand(s string) string {
|
||||||
|
if s != "" {
|
||||||
|
if s[0] == '~' {
|
||||||
|
s = "${HOME}" + s[1:]
|
||||||
|
}
|
||||||
|
s = os.ExpandEnv(s)
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
// NewFs creates a new Fs object from the name and root. It connects to
|
// NewFs creates a new Fs object from the name and root. It connects to
|
||||||
// the host specified in the config file.
|
// the host specified in the config file.
|
||||||
func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
||||||
@@ -325,8 +354,9 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
sshConfig.Config.Ciphers = append(sshConfig.Config.Ciphers, "aes128-cbc")
|
sshConfig.Config.Ciphers = append(sshConfig.Config.Ciphers, "aes128-cbc")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
keyFile := shellExpand(opt.KeyFile)
|
||||||
// Add ssh agent-auth if no password or file specified
|
// Add ssh agent-auth if no password or file specified
|
||||||
if opt.Pass == "" && opt.KeyFile == "" {
|
if (opt.Pass == "" && keyFile == "") || 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")
|
||||||
@@ -335,16 +365,46 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "couldn't read ssh agent signers")
|
return nil, errors.Wrap(err, "couldn't read ssh agent signers")
|
||||||
}
|
}
|
||||||
sshConfig.Auth = append(sshConfig.Auth, ssh.PublicKeys(signers...))
|
if keyFile != "" {
|
||||||
|
pubBytes, err := ioutil.ReadFile(keyFile + ".pub")
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "failed to read public key file")
|
||||||
|
}
|
||||||
|
pub, _, _, _, err := ssh.ParseAuthorizedKey(pubBytes)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "failed to parse public key file")
|
||||||
|
}
|
||||||
|
pubM := pub.Marshal()
|
||||||
|
found := false
|
||||||
|
for _, s := range signers {
|
||||||
|
if bytes.Equal(pubM, s.PublicKey().Marshal()) {
|
||||||
|
sshConfig.Auth = append(sshConfig.Auth, ssh.PublicKeys(s))
|
||||||
|
found = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
return nil, errors.New("private key not found in the ssh-agent")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
sshConfig.Auth = append(sshConfig.Auth, ssh.PublicKeys(signers...))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load key file if specified
|
// Load key file if specified
|
||||||
if opt.KeyFile != "" {
|
if keyFile != "" {
|
||||||
key, err := ioutil.ReadFile(opt.KeyFile)
|
key, err := ioutil.ReadFile(keyFile)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "failed to read private key file")
|
return nil, errors.Wrap(err, "failed to read private key file")
|
||||||
}
|
}
|
||||||
signer, err := ssh.ParsePrivateKey(key)
|
clearpass := ""
|
||||||
|
if opt.KeyFilePass != "" {
|
||||||
|
clearpass, err = obscure.Reveal(opt.KeyFilePass)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
signer, err := ssh.ParsePrivateKeyWithPassphrase(key, []byte(clearpass))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "failed to parse private key file")
|
return nil, errors.Wrap(err, "failed to parse private key file")
|
||||||
}
|
}
|
||||||
@@ -505,9 +565,13 @@ func (f *Fs) List(dir string) (entries fs.DirEntries, err error) {
|
|||||||
// If file is a symlink (not a regular file is the best cross platform test we can do), do a stat to
|
// If file is a symlink (not a regular file is the best cross platform test we can do), do a stat to
|
||||||
// pick up the size and type of the destination, instead of the size and type of the symlink.
|
// pick up the size and type of the destination, instead of the size and type of the symlink.
|
||||||
if !info.Mode().IsRegular() {
|
if !info.Mode().IsRegular() {
|
||||||
|
oldInfo := info
|
||||||
info, err = f.stat(remote)
|
info, err = f.stat(remote)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "stat of non-regular file/dir failed")
|
if !os.IsNotExist(err) {
|
||||||
|
fs.Errorf(remote, "stat of non-regular file/dir failed: %v", err)
|
||||||
|
}
|
||||||
|
info = oldInfo
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if info.IsDir() {
|
if info.IsDir() {
|
||||||
@@ -594,12 +658,22 @@ func (f *Fs) Mkdir(dir string) error {
|
|||||||
|
|
||||||
// Rmdir removes the root directory of the Fs object
|
// Rmdir removes the root directory of the Fs object
|
||||||
func (f *Fs) Rmdir(dir string) error {
|
func (f *Fs) Rmdir(dir string) error {
|
||||||
|
// Check to see if directory is empty as some servers will
|
||||||
|
// delete recursively with RemoveDirectory
|
||||||
|
entries, err := f.List(dir)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "Rmdir")
|
||||||
|
}
|
||||||
|
if len(entries) != 0 {
|
||||||
|
return fs.ErrorDirectoryNotEmpty
|
||||||
|
}
|
||||||
|
// Remove the directory
|
||||||
root := path.Join(f.root, dir)
|
root := path.Join(f.root, 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")
|
||||||
}
|
}
|
||||||
err = c.sftpClient.Remove(root)
|
err = c.sftpClient.RemoveDirectory(root)
|
||||||
f.putSftpConnection(&c, err)
|
f.putSftpConnection(&c, err)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
+236
-73
@@ -21,6 +21,7 @@ import (
|
|||||||
"github.com/ncw/rclone/fs/hash"
|
"github.com/ncw/rclone/fs/hash"
|
||||||
"github.com/ncw/rclone/fs/operations"
|
"github.com/ncw/rclone/fs/operations"
|
||||||
"github.com/ncw/rclone/fs/walk"
|
"github.com/ncw/rclone/fs/walk"
|
||||||
|
"github.com/ncw/rclone/lib/pacer"
|
||||||
"github.com/ncw/swift"
|
"github.com/ncw/swift"
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
)
|
)
|
||||||
@@ -30,6 +31,7 @@ const (
|
|||||||
directoryMarkerContentType = "application/directory" // content type of directory marker objects
|
directoryMarkerContentType = "application/directory" // content type of directory marker objects
|
||||||
listChunks = 1000 // chunk size to read directory listings
|
listChunks = 1000 // chunk size to read directory listings
|
||||||
defaultChunkSize = 5 * fs.GibiByte
|
defaultChunkSize = 5 * fs.GibiByte
|
||||||
|
minSleep = 10 * time.Millisecond // In case of error, start at 10ms sleep.
|
||||||
)
|
)
|
||||||
|
|
||||||
// SharedOptions are shared between swift and hubic
|
// SharedOptions are shared between swift and hubic
|
||||||
@@ -41,6 +43,20 @@ Above this size files will be chunked into a _segments container. The
|
|||||||
default for this is 5GB which is its maximum value.`,
|
default for this is 5GB which is its maximum value.`,
|
||||||
Default: defaultChunkSize,
|
Default: defaultChunkSize,
|
||||||
Advanced: true,
|
Advanced: true,
|
||||||
|
}, {
|
||||||
|
Name: "no_chunk",
|
||||||
|
Help: `Don't chunk files during streaming upload.
|
||||||
|
|
||||||
|
When doing streaming uploads (eg using rcat or mount) setting this
|
||||||
|
flag will cause the swift backend to not upload chunked files.
|
||||||
|
|
||||||
|
This will limit the maximum upload size to 5GB. However non chunked
|
||||||
|
files are easier to deal with and have an MD5SUM.
|
||||||
|
|
||||||
|
Rclone will still chunk files bigger than chunk_size when doing normal
|
||||||
|
copy operations.`,
|
||||||
|
Default: false,
|
||||||
|
Advanced: true,
|
||||||
}}
|
}}
|
||||||
|
|
||||||
// Register with Fs
|
// Register with Fs
|
||||||
@@ -114,6 +130,15 @@ func init() {
|
|||||||
}, {
|
}, {
|
||||||
Name: "auth_token",
|
Name: "auth_token",
|
||||||
Help: "Auth Token from alternate authentication - optional (OS_AUTH_TOKEN)",
|
Help: "Auth Token from alternate authentication - optional (OS_AUTH_TOKEN)",
|
||||||
|
}, {
|
||||||
|
Name: "application_credential_id",
|
||||||
|
Help: "Application Credential ID (OS_APPLICATION_CREDENTIAL_ID)",
|
||||||
|
}, {
|
||||||
|
Name: "application_credential_name",
|
||||||
|
Help: "Application Credential Name (OS_APPLICATION_CREDENTIAL_NAME)",
|
||||||
|
}, {
|
||||||
|
Name: "application_credential_secret",
|
||||||
|
Help: "Application Credential Secret (OS_APPLICATION_CREDENTIAL_SECRET)",
|
||||||
}, {
|
}, {
|
||||||
Name: "auth_version",
|
Name: "auth_version",
|
||||||
Help: "AuthVersion - optional - set to (1,2,3) if your auth URL has no version (ST_AUTH_VERSION)",
|
Help: "AuthVersion - optional - set to (1,2,3) if your auth URL has no version (ST_AUTH_VERSION)",
|
||||||
@@ -157,22 +182,26 @@ provider.`,
|
|||||||
|
|
||||||
// Options defines the configuration for this backend
|
// Options defines the configuration for this backend
|
||||||
type Options struct {
|
type Options struct {
|
||||||
EnvAuth bool `config:"env_auth"`
|
EnvAuth bool `config:"env_auth"`
|
||||||
User string `config:"user"`
|
User string `config:"user"`
|
||||||
Key string `config:"key"`
|
Key string `config:"key"`
|
||||||
Auth string `config:"auth"`
|
Auth string `config:"auth"`
|
||||||
UserID string `config:"user_id"`
|
UserID string `config:"user_id"`
|
||||||
Domain string `config:"domain"`
|
Domain string `config:"domain"`
|
||||||
Tenant string `config:"tenant"`
|
Tenant string `config:"tenant"`
|
||||||
TenantID string `config:"tenant_id"`
|
TenantID string `config:"tenant_id"`
|
||||||
TenantDomain string `config:"tenant_domain"`
|
TenantDomain string `config:"tenant_domain"`
|
||||||
Region string `config:"region"`
|
Region string `config:"region"`
|
||||||
StorageURL string `config:"storage_url"`
|
StorageURL string `config:"storage_url"`
|
||||||
AuthToken string `config:"auth_token"`
|
AuthToken string `config:"auth_token"`
|
||||||
AuthVersion int `config:"auth_version"`
|
AuthVersion int `config:"auth_version"`
|
||||||
StoragePolicy string `config:"storage_policy"`
|
ApplicationCredentialId string `config:"application_credential_id"`
|
||||||
EndpointType string `config:"endpoint_type"`
|
ApplicationCredentialName string `config:"application_credential_name"`
|
||||||
ChunkSize fs.SizeSuffix `config:"chunk_size"`
|
ApplicationCredentialSecret string `config:"application_credential_secret"`
|
||||||
|
StoragePolicy string `config:"storage_policy"`
|
||||||
|
EndpointType string `config:"endpoint_type"`
|
||||||
|
ChunkSize fs.SizeSuffix `config:"chunk_size"`
|
||||||
|
NoChunk bool `config:"no_chunk"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fs represents a remote swift server
|
// Fs represents a remote swift server
|
||||||
@@ -187,16 +216,20 @@ type Fs struct {
|
|||||||
containerOK bool // true if we have created the container
|
containerOK bool // true if we have created the container
|
||||||
segmentsContainer string // container to store the segments (if any) in
|
segmentsContainer string // container to store the segments (if any) in
|
||||||
noCheckContainer bool // don't check the container before creating it
|
noCheckContainer bool // don't check the container before creating it
|
||||||
|
pacer *pacer.Pacer // To pace the API calls
|
||||||
}
|
}
|
||||||
|
|
||||||
// Object describes a swift object
|
// Object describes a swift object
|
||||||
//
|
//
|
||||||
// Will definitely have info but maybe not meta
|
// Will definitely have info but maybe not meta
|
||||||
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
|
||||||
info swift.Object // Info from the swift object if known
|
size int64
|
||||||
headers swift.Headers // The object headers if known
|
lastModified time.Time
|
||||||
|
contentType string
|
||||||
|
md5 string
|
||||||
|
headers swift.Headers // The object headers if known
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------
|
// ------------------------------------------------------------
|
||||||
@@ -227,6 +260,32 @@ func (f *Fs) Features() *fs.Features {
|
|||||||
return f.features
|
return f.features
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// retryErrorCodes is a slice of error codes that we will retry
|
||||||
|
var retryErrorCodes = []int{
|
||||||
|
401, // Unauthorized (eg "Token has expired")
|
||||||
|
408, // Request Timeout
|
||||||
|
409, // Conflict - various states that could be resolved on a retry
|
||||||
|
429, // Rate exceeded.
|
||||||
|
500, // Get occasional 500 Internal Server Error
|
||||||
|
503, // Service Unavailable/Slow Down - "Reduce your request rate"
|
||||||
|
504, // Gateway Time-out
|
||||||
|
}
|
||||||
|
|
||||||
|
// shouldRetry returns a boolean as to whether this err deserves to be
|
||||||
|
// retried. It returns the err as a convenience
|
||||||
|
func shouldRetry(err error) (bool, error) {
|
||||||
|
// If this is an swift.Error object extract the HTTP error code
|
||||||
|
if swiftError, ok := err.(*swift.Error); ok {
|
||||||
|
for _, e := range retryErrorCodes {
|
||||||
|
if swiftError.StatusCode == e {
|
||||||
|
return true, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Check for generic failure conditions
|
||||||
|
return fserrors.ShouldRetry(err), err
|
||||||
|
}
|
||||||
|
|
||||||
// Pattern to match a swift path
|
// Pattern to match a swift path
|
||||||
var matcher = regexp.MustCompile(`^/*([^/]*)(.*)$`)
|
var matcher = regexp.MustCompile(`^/*([^/]*)(.*)$`)
|
||||||
|
|
||||||
@@ -246,22 +305,25 @@ func parsePath(path string) (container, directory string, err error) {
|
|||||||
func swiftConnection(opt *Options, name string) (*swift.Connection, error) {
|
func swiftConnection(opt *Options, name string) (*swift.Connection, error) {
|
||||||
c := &swift.Connection{
|
c := &swift.Connection{
|
||||||
// Keep these in the same order as the Config for ease of checking
|
// Keep these in the same order as the Config for ease of checking
|
||||||
UserName: opt.User,
|
UserName: opt.User,
|
||||||
ApiKey: opt.Key,
|
ApiKey: opt.Key,
|
||||||
AuthUrl: opt.Auth,
|
AuthUrl: opt.Auth,
|
||||||
UserId: opt.UserID,
|
UserId: opt.UserID,
|
||||||
Domain: opt.Domain,
|
Domain: opt.Domain,
|
||||||
Tenant: opt.Tenant,
|
Tenant: opt.Tenant,
|
||||||
TenantId: opt.TenantID,
|
TenantId: opt.TenantID,
|
||||||
TenantDomain: opt.TenantDomain,
|
TenantDomain: opt.TenantDomain,
|
||||||
Region: opt.Region,
|
Region: opt.Region,
|
||||||
StorageUrl: opt.StorageURL,
|
StorageUrl: opt.StorageURL,
|
||||||
AuthToken: opt.AuthToken,
|
AuthToken: opt.AuthToken,
|
||||||
AuthVersion: opt.AuthVersion,
|
AuthVersion: opt.AuthVersion,
|
||||||
EndpointType: swift.EndpointType(opt.EndpointType),
|
ApplicationCredentialId: opt.ApplicationCredentialId,
|
||||||
ConnectTimeout: 10 * fs.Config.ConnectTimeout, // Use the timeouts in the transport
|
ApplicationCredentialName: opt.ApplicationCredentialName,
|
||||||
Timeout: 10 * fs.Config.Timeout, // Use the timeouts in the transport
|
ApplicationCredentialSecret: opt.ApplicationCredentialSecret,
|
||||||
Transport: fshttp.NewTransport(fs.Config),
|
EndpointType: swift.EndpointType(opt.EndpointType),
|
||||||
|
ConnectTimeout: 10 * fs.Config.ConnectTimeout, // Use the timeouts in the transport
|
||||||
|
Timeout: 10 * fs.Config.Timeout, // Use the timeouts in the transport
|
||||||
|
Transport: fshttp.NewTransport(fs.Config),
|
||||||
}
|
}
|
||||||
if opt.EnvAuth {
|
if opt.EnvAuth {
|
||||||
err := c.ApplyEnvironment()
|
err := c.ApplyEnvironment()
|
||||||
@@ -271,11 +333,13 @@ func swiftConnection(opt *Options, name string) (*swift.Connection, error) {
|
|||||||
}
|
}
|
||||||
StorageUrl, AuthToken := c.StorageUrl, c.AuthToken // nolint
|
StorageUrl, AuthToken := c.StorageUrl, c.AuthToken // nolint
|
||||||
if !c.Authenticated() {
|
if !c.Authenticated() {
|
||||||
if c.UserName == "" && c.UserId == "" {
|
if (c.ApplicationCredentialId != "" || c.ApplicationCredentialName != "") && c.ApplicationCredentialSecret == "" {
|
||||||
return nil, errors.New("user name or user id not found for authentication (and no storage_url+auth_token is provided)")
|
if c.UserName == "" && c.UserId == "" {
|
||||||
}
|
return nil, errors.New("user name or user id not found for authentication (and no storage_url+auth_token is provided)")
|
||||||
if c.ApiKey == "" {
|
}
|
||||||
return nil, errors.New("key not found")
|
if c.ApiKey == "" {
|
||||||
|
return nil, errors.New("key not found")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if c.AuthUrl == "" {
|
if c.AuthUrl == "" {
|
||||||
return nil, errors.New("auth not found")
|
return nil, errors.New("auth not found")
|
||||||
@@ -337,6 +401,7 @@ func NewFsWithConnection(opt *Options, name, root string, c *swift.Connection, n
|
|||||||
segmentsContainer: container + "_segments",
|
segmentsContainer: container + "_segments",
|
||||||
root: directory,
|
root: directory,
|
||||||
noCheckContainer: noCheckContainer,
|
noCheckContainer: noCheckContainer,
|
||||||
|
pacer: pacer.New().SetMinSleep(minSleep).SetPacer(pacer.S3Pacer),
|
||||||
}
|
}
|
||||||
f.features = (&fs.Features{
|
f.features = (&fs.Features{
|
||||||
ReadMimeType: true,
|
ReadMimeType: true,
|
||||||
@@ -346,7 +411,11 @@ func NewFsWithConnection(opt *Options, name, root string, c *swift.Connection, n
|
|||||||
if f.root != "" {
|
if f.root != "" {
|
||||||
f.root += "/"
|
f.root += "/"
|
||||||
// Check to see if the object exists - ignoring directory markers
|
// Check to see if the object exists - ignoring directory markers
|
||||||
info, _, err := f.c.Object(container, directory)
|
var info swift.Object
|
||||||
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
|
info, _, err = f.c.Object(container, directory)
|
||||||
|
return shouldRetry(err)
|
||||||
|
})
|
||||||
if err == nil && info.ContentType != directoryMarkerContentType {
|
if err == nil && info.ContentType != directoryMarkerContentType {
|
||||||
f.root = path.Dir(directory)
|
f.root = path.Dir(directory)
|
||||||
if f.root == "." {
|
if f.root == "." {
|
||||||
@@ -398,7 +467,10 @@ func (f *Fs) newObjectWithInfo(remote string, info *swift.Object) (fs.Object, er
|
|||||||
}
|
}
|
||||||
if info != nil {
|
if info != nil {
|
||||||
// Set info but not headers
|
// Set info but not headers
|
||||||
o.info = *info
|
err := o.decodeMetaData(info)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
err := o.readMetaData() // reads info and headers, returning an error
|
err := o.readMetaData() // reads info and headers, returning an error
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -436,7 +508,12 @@ func (f *Fs) listContainerRoot(container, root string, dir string, recurse bool,
|
|||||||
}
|
}
|
||||||
rootLength := len(root)
|
rootLength := len(root)
|
||||||
return f.c.ObjectsWalk(container, &opts, func(opts *swift.ObjectsOpts) (interface{}, error) {
|
return f.c.ObjectsWalk(container, &opts, func(opts *swift.ObjectsOpts) (interface{}, error) {
|
||||||
objects, err := f.c.Objects(container, opts)
|
var objects []swift.Object
|
||||||
|
var err error
|
||||||
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
|
objects, err = f.c.Objects(container, opts)
|
||||||
|
return shouldRetry(err)
|
||||||
|
})
|
||||||
if err == nil {
|
if err == nil {
|
||||||
for i := range objects {
|
for i := range objects {
|
||||||
object := &objects[i]
|
object := &objects[i]
|
||||||
@@ -525,7 +602,11 @@ func (f *Fs) listContainers(dir string) (entries fs.DirEntries, err error) {
|
|||||||
if dir != "" {
|
if dir != "" {
|
||||||
return nil, fs.ErrorListBucketRequired
|
return nil, fs.ErrorListBucketRequired
|
||||||
}
|
}
|
||||||
containers, err := f.c.ContainersAll(nil)
|
var containers []swift.Container
|
||||||
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
|
containers, err = f.c.ContainersAll(nil)
|
||||||
|
return shouldRetry(err)
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "container listing failed")
|
return nil, errors.Wrap(err, "container listing failed")
|
||||||
}
|
}
|
||||||
@@ -586,7 +667,12 @@ func (f *Fs) ListR(dir string, callback fs.ListRCallback) (err error) {
|
|||||||
|
|
||||||
// About gets quota information
|
// About gets quota information
|
||||||
func (f *Fs) About() (*fs.Usage, error) {
|
func (f *Fs) About() (*fs.Usage, error) {
|
||||||
containers, err := f.c.ContainersAll(nil)
|
var containers []swift.Container
|
||||||
|
var err error
|
||||||
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
|
containers, err = f.c.ContainersAll(nil)
|
||||||
|
return shouldRetry(err)
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "container listing failed")
|
return nil, errors.Wrap(err, "container listing failed")
|
||||||
}
|
}
|
||||||
@@ -636,14 +722,20 @@ func (f *Fs) Mkdir(dir string) error {
|
|||||||
// Check to see if container exists first
|
// Check to see if container exists first
|
||||||
var err error = swift.ContainerNotFound
|
var err error = swift.ContainerNotFound
|
||||||
if !f.noCheckContainer {
|
if !f.noCheckContainer {
|
||||||
_, _, err = f.c.Container(f.container)
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
|
_, _, err = f.c.Container(f.container)
|
||||||
|
return shouldRetry(err)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
if err == swift.ContainerNotFound {
|
if err == swift.ContainerNotFound {
|
||||||
headers := swift.Headers{}
|
headers := swift.Headers{}
|
||||||
if f.opt.StoragePolicy != "" {
|
if f.opt.StoragePolicy != "" {
|
||||||
headers["X-Storage-Policy"] = f.opt.StoragePolicy
|
headers["X-Storage-Policy"] = f.opt.StoragePolicy
|
||||||
}
|
}
|
||||||
err = f.c.ContainerCreate(f.container, headers)
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
|
err = f.c.ContainerCreate(f.container, headers)
|
||||||
|
return shouldRetry(err)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
if err == nil {
|
if err == nil {
|
||||||
f.containerOK = true
|
f.containerOK = true
|
||||||
@@ -660,7 +752,11 @@ func (f *Fs) Rmdir(dir string) error {
|
|||||||
if f.root != "" || dir != "" {
|
if f.root != "" || dir != "" {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
err := f.c.ContainerDelete(f.container)
|
var err error
|
||||||
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
|
err = f.c.ContainerDelete(f.container)
|
||||||
|
return shouldRetry(err)
|
||||||
|
})
|
||||||
if err == nil {
|
if err == nil {
|
||||||
f.containerOK = false
|
f.containerOK = false
|
||||||
}
|
}
|
||||||
@@ -719,7 +815,10 @@ func (f *Fs) Copy(src fs.Object, remote string) (fs.Object, error) {
|
|||||||
return nil, fs.ErrorCantCopy
|
return nil, fs.ErrorCantCopy
|
||||||
}
|
}
|
||||||
srcFs := srcObj.fs
|
srcFs := srcObj.fs
|
||||||
_, err = f.c.ObjectCopy(srcFs.container, srcFs.root+srcObj.remote, f.container, f.root+remote, nil)
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
|
_, err = f.c.ObjectCopy(srcFs.container, srcFs.root+srcObj.remote, f.container, f.root+remote, nil)
|
||||||
|
return shouldRetry(err)
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -768,7 +867,7 @@ func (o *Object) Hash(t hash.Type) (string, error) {
|
|||||||
fs.Debugf(o, "Returning empty Md5sum for swift large object")
|
fs.Debugf(o, "Returning empty Md5sum for swift large object")
|
||||||
return "", nil
|
return "", nil
|
||||||
}
|
}
|
||||||
return strings.ToLower(o.info.Hash), nil
|
return strings.ToLower(o.md5), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// hasHeader checks for the header passed in returning false if the
|
// hasHeader checks for the header passed in returning false if the
|
||||||
@@ -797,7 +896,22 @@ func (o *Object) isStaticLargeObject() (bool, error) {
|
|||||||
|
|
||||||
// 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 {
|
||||||
return o.info.Bytes
|
return o.size
|
||||||
|
}
|
||||||
|
|
||||||
|
// decodeMetaData sets the metadata in the object from a swift.Object
|
||||||
|
//
|
||||||
|
// Sets
|
||||||
|
// o.lastModified
|
||||||
|
// o.size
|
||||||
|
// o.md5
|
||||||
|
// o.contentType
|
||||||
|
func (o *Object) decodeMetaData(info *swift.Object) (err error) {
|
||||||
|
o.lastModified = info.LastModified
|
||||||
|
o.size = info.Bytes
|
||||||
|
o.md5 = info.Hash
|
||||||
|
o.contentType = info.ContentType
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// readMetaData gets the metadata if it hasn't already been fetched
|
// readMetaData gets the metadata if it hasn't already been fetched
|
||||||
@@ -809,15 +923,23 @@ func (o *Object) readMetaData() (err error) {
|
|||||||
if o.headers != nil {
|
if o.headers != nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
info, h, err := o.fs.c.Object(o.fs.container, o.fs.root+o.remote)
|
var info swift.Object
|
||||||
|
var h swift.Headers
|
||||||
|
err = o.fs.pacer.Call(func() (bool, error) {
|
||||||
|
info, h, err = o.fs.c.Object(o.fs.container, o.fs.root+o.remote)
|
||||||
|
return shouldRetry(err)
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err == swift.ObjectNotFound {
|
if err == swift.ObjectNotFound {
|
||||||
return fs.ErrorObjectNotFound
|
return fs.ErrorObjectNotFound
|
||||||
}
|
}
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
o.info = info
|
|
||||||
o.headers = h
|
o.headers = h
|
||||||
|
err = o.decodeMetaData(&info)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -828,17 +950,17 @@ func (o *Object) readMetaData() (err error) {
|
|||||||
// LastModified returned in the http headers
|
// LastModified returned in the http headers
|
||||||
func (o *Object) ModTime() time.Time {
|
func (o *Object) ModTime() time.Time {
|
||||||
if fs.Config.UseServerModTime {
|
if fs.Config.UseServerModTime {
|
||||||
return o.info.LastModified
|
return o.lastModified
|
||||||
}
|
}
|
||||||
err := o.readMetaData()
|
err := o.readMetaData()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fs.Debugf(o, "Failed to read metadata: %s", err)
|
fs.Debugf(o, "Failed to read metadata: %s", err)
|
||||||
return o.info.LastModified
|
return o.lastModified
|
||||||
}
|
}
|
||||||
modTime, err := o.headers.ObjectMetadata().GetModTime()
|
modTime, err := o.headers.ObjectMetadata().GetModTime()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// fs.Logf(o, "Failed to read mtime from object: %v", err)
|
// fs.Logf(o, "Failed to read mtime from object: %v", err)
|
||||||
return o.info.LastModified
|
return o.lastModified
|
||||||
}
|
}
|
||||||
return modTime
|
return modTime
|
||||||
}
|
}
|
||||||
@@ -861,7 +983,10 @@ func (o *Object) SetModTime(modTime time.Time) error {
|
|||||||
newHeaders[k] = v
|
newHeaders[k] = v
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return o.fs.c.ObjectUpdate(o.fs.container, o.fs.root+o.remote, newHeaders)
|
return o.fs.pacer.Call(func() (bool, error) {
|
||||||
|
err = o.fs.c.ObjectUpdate(o.fs.container, o.fs.root+o.remote, newHeaders)
|
||||||
|
return shouldRetry(err)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Storable returns if this object is storable
|
// Storable returns if this object is storable
|
||||||
@@ -869,14 +994,17 @@ func (o *Object) SetModTime(modTime time.Time) error {
|
|||||||
// It compares the Content-Type to directoryMarkerContentType - that
|
// It compares the Content-Type to directoryMarkerContentType - that
|
||||||
// makes it a directory marker which is not storable.
|
// makes it a directory marker which is not storable.
|
||||||
func (o *Object) Storable() bool {
|
func (o *Object) Storable() bool {
|
||||||
return o.info.ContentType != directoryMarkerContentType
|
return o.contentType != directoryMarkerContentType
|
||||||
}
|
}
|
||||||
|
|
||||||
// Open an object for read
|
// Open an object for read
|
||||||
func (o *Object) Open(options ...fs.OpenOption) (in io.ReadCloser, err error) {
|
func (o *Object) Open(options ...fs.OpenOption) (in io.ReadCloser, err error) {
|
||||||
headers := fs.OpenOptionHeaders(options)
|
headers := fs.OpenOptionHeaders(options)
|
||||||
_, isRanging := headers["Range"]
|
_, isRanging := headers["Range"]
|
||||||
in, _, err = o.fs.c.ObjectOpen(o.fs.container, o.fs.root+o.remote, !isRanging, headers)
|
err = o.fs.pacer.Call(func() (bool, error) {
|
||||||
|
in, _, err = o.fs.c.ObjectOpen(o.fs.container, o.fs.root+o.remote, !isRanging, headers)
|
||||||
|
return shouldRetry(err)
|
||||||
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -903,13 +1031,20 @@ func (o *Object) removeSegments(except string) error {
|
|||||||
}
|
}
|
||||||
segmentPath := segmentsRoot + remote
|
segmentPath := segmentsRoot + remote
|
||||||
fs.Debugf(o, "Removing segment file %q in container %q", segmentPath, o.fs.segmentsContainer)
|
fs.Debugf(o, "Removing segment file %q in container %q", segmentPath, o.fs.segmentsContainer)
|
||||||
return o.fs.c.ObjectDelete(o.fs.segmentsContainer, segmentPath)
|
var err error
|
||||||
|
return o.fs.pacer.Call(func() (bool, error) {
|
||||||
|
err = o.fs.c.ObjectDelete(o.fs.segmentsContainer, segmentPath)
|
||||||
|
return shouldRetry(err)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
// remove the segments container if empty, ignore errors
|
// remove the segments container if empty, ignore errors
|
||||||
err = o.fs.c.ContainerDelete(o.fs.segmentsContainer)
|
err = o.fs.pacer.Call(func() (bool, error) {
|
||||||
|
err = o.fs.c.ContainerDelete(o.fs.segmentsContainer)
|
||||||
|
return shouldRetry(err)
|
||||||
|
})
|
||||||
if err == nil {
|
if err == nil {
|
||||||
fs.Debugf(o, "Removed empty container %q", o.fs.segmentsContainer)
|
fs.Debugf(o, "Removed empty container %q", o.fs.segmentsContainer)
|
||||||
}
|
}
|
||||||
@@ -938,13 +1073,19 @@ func urlEncode(str string) string {
|
|||||||
func (o *Object) updateChunks(in0 io.Reader, headers swift.Headers, size int64, contentType string) (string, error) {
|
func (o *Object) updateChunks(in0 io.Reader, headers swift.Headers, size int64, contentType string) (string, error) {
|
||||||
// Create the segmentsContainer if it doesn't exist
|
// Create the segmentsContainer if it doesn't exist
|
||||||
var err error
|
var err error
|
||||||
_, _, err = o.fs.c.Container(o.fs.segmentsContainer)
|
err = o.fs.pacer.Call(func() (bool, error) {
|
||||||
|
_, _, err = o.fs.c.Container(o.fs.segmentsContainer)
|
||||||
|
return shouldRetry(err)
|
||||||
|
})
|
||||||
if err == swift.ContainerNotFound {
|
if err == swift.ContainerNotFound {
|
||||||
headers := swift.Headers{}
|
headers := swift.Headers{}
|
||||||
if o.fs.opt.StoragePolicy != "" {
|
if o.fs.opt.StoragePolicy != "" {
|
||||||
headers["X-Storage-Policy"] = o.fs.opt.StoragePolicy
|
headers["X-Storage-Policy"] = o.fs.opt.StoragePolicy
|
||||||
}
|
}
|
||||||
err = o.fs.c.ContainerCreate(o.fs.segmentsContainer, headers)
|
err = o.fs.pacer.Call(func() (bool, error) {
|
||||||
|
err = o.fs.c.ContainerCreate(o.fs.segmentsContainer, headers)
|
||||||
|
return shouldRetry(err)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
@@ -973,7 +1114,10 @@ func (o *Object) updateChunks(in0 io.Reader, headers swift.Headers, size int64,
|
|||||||
segmentReader := io.LimitReader(in, n)
|
segmentReader := io.LimitReader(in, n)
|
||||||
segmentPath := fmt.Sprintf("%s/%08d", segmentsPath, i)
|
segmentPath := fmt.Sprintf("%s/%08d", segmentsPath, i)
|
||||||
fs.Debugf(o, "Uploading segment file %q into %q", segmentPath, o.fs.segmentsContainer)
|
fs.Debugf(o, "Uploading segment file %q into %q", segmentPath, o.fs.segmentsContainer)
|
||||||
_, err := o.fs.c.ObjectPut(o.fs.segmentsContainer, segmentPath, segmentReader, true, "", "", headers)
|
err = o.fs.pacer.CallNoRetry(func() (bool, error) {
|
||||||
|
_, err = o.fs.c.ObjectPut(o.fs.segmentsContainer, segmentPath, segmentReader, true, "", "", headers)
|
||||||
|
return shouldRetry(err)
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
@@ -984,7 +1128,10 @@ func (o *Object) updateChunks(in0 io.Reader, headers swift.Headers, size int64,
|
|||||||
headers["Content-Length"] = "0" // set Content-Length as we know it
|
headers["Content-Length"] = "0" // set Content-Length as we know it
|
||||||
emptyReader := bytes.NewReader(nil)
|
emptyReader := bytes.NewReader(nil)
|
||||||
manifestName := o.fs.root + o.remote
|
manifestName := o.fs.root + o.remote
|
||||||
_, err = o.fs.c.ObjectPut(o.fs.container, manifestName, emptyReader, true, "", contentType, headers)
|
err = o.fs.pacer.Call(func() (bool, error) {
|
||||||
|
_, err = o.fs.c.ObjectPut(o.fs.container, manifestName, emptyReader, true, "", contentType, headers)
|
||||||
|
return shouldRetry(err)
|
||||||
|
})
|
||||||
return uniquePrefix + "/", err
|
return uniquePrefix + "/", err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1014,17 +1161,31 @@ func (o *Object) Update(in io.Reader, src fs.ObjectInfo, options ...fs.OpenOptio
|
|||||||
contentType := fs.MimeType(src)
|
contentType := fs.MimeType(src)
|
||||||
headers := m.ObjectHeaders()
|
headers := m.ObjectHeaders()
|
||||||
uniquePrefix := ""
|
uniquePrefix := ""
|
||||||
if size > int64(o.fs.opt.ChunkSize) || size == -1 {
|
if size > int64(o.fs.opt.ChunkSize) || (size == -1 && !o.fs.opt.NoChunk) {
|
||||||
uniquePrefix, err = o.updateChunks(in, headers, size, contentType)
|
uniquePrefix, err = o.updateChunks(in, headers, size, contentType)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
o.headers = nil // wipe old metadata
|
||||||
} else {
|
} else {
|
||||||
headers["Content-Length"] = strconv.FormatInt(size, 10) // set Content-Length as we know it
|
if size >= 0 {
|
||||||
_, err := o.fs.c.ObjectPut(o.fs.container, o.fs.root+o.remote, in, true, "", contentType, headers)
|
headers["Content-Length"] = strconv.FormatInt(size, 10) // set Content-Length if we know it
|
||||||
|
}
|
||||||
|
var rxHeaders swift.Headers
|
||||||
|
err = o.fs.pacer.CallNoRetry(func() (bool, error) {
|
||||||
|
rxHeaders, err = o.fs.c.ObjectPut(o.fs.container, o.fs.root+o.remote, in, true, "", contentType, headers)
|
||||||
|
return shouldRetry(err)
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
// set Metadata since ObjectPut checked the hash and length so we know the
|
||||||
|
// object has been safely uploaded
|
||||||
|
o.lastModified = modTime
|
||||||
|
o.size = size
|
||||||
|
o.md5 = rxHeaders["ETag"]
|
||||||
|
o.contentType = contentType
|
||||||
|
o.headers = headers
|
||||||
}
|
}
|
||||||
|
|
||||||
// If file was a dynamic large object then remove old/all segments
|
// If file was a dynamic large object then remove old/all segments
|
||||||
@@ -1035,8 +1196,7 @@ func (o *Object) Update(in io.Reader, src fs.ObjectInfo, options ...fs.OpenOptio
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read the metadata from the newly created object
|
// Read the metadata from the newly created object if necessary
|
||||||
o.headers = nil // wipe old metadata
|
|
||||||
return o.readMetaData()
|
return o.readMetaData()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1047,7 +1207,10 @@ func (o *Object) Remove() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
// Remove file/manifest first
|
// Remove file/manifest first
|
||||||
err = o.fs.c.ObjectDelete(o.fs.container, o.fs.root+o.remote)
|
err = o.fs.pacer.Call(func() (bool, error) {
|
||||||
|
err = o.fs.c.ObjectDelete(o.fs.container, o.fs.root+o.remote)
|
||||||
|
return shouldRetry(err)
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -1063,7 +1226,7 @@ func (o *Object) Remove() error {
|
|||||||
|
|
||||||
// MimeType of an Object if known, "" otherwise
|
// MimeType of an Object if known, "" otherwise
|
||||||
func (o *Object) MimeType() string {
|
func (o *Object) MimeType() string {
|
||||||
return o.info.ContentType
|
return o.contentType
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check the interfaces are satisfied
|
// Check the interfaces are satisfied
|
||||||
|
|||||||
@@ -376,6 +376,11 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
}).Fill(f)
|
}).Fill(f)
|
||||||
features = features.Mask(f.wr) // mask the features just on the writable fs
|
features = features.Mask(f.wr) // mask the features just on the writable fs
|
||||||
|
|
||||||
|
// Really need the union of all remotes for these, so
|
||||||
|
// re-instate and calculate separately.
|
||||||
|
features.ChangeNotify = f.ChangeNotify
|
||||||
|
features.DirCacheFlush = f.DirCacheFlush
|
||||||
|
|
||||||
// FIXME maybe should be masking the bools here?
|
// FIXME maybe should be masking the bools here?
|
||||||
|
|
||||||
// Clear ChangeNotify and DirCacheFlush if all are nil
|
// Clear ChangeNotify and DirCacheFlush if all are nil
|
||||||
|
|||||||
@@ -6,7 +6,11 @@ import (
|
|||||||
"regexp"
|
"regexp"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/ncw/rclone/fs"
|
||||||
|
"github.com/ncw/rclone/fs/hash"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -62,11 +66,12 @@ type Response struct {
|
|||||||
// Note that status collects all the status values for which we just
|
// Note that status collects all the status values for which we just
|
||||||
// check the first is OK.
|
// check the first is OK.
|
||||||
type Prop struct {
|
type Prop struct {
|
||||||
Status []string `xml:"DAV: status"`
|
Status []string `xml:"DAV: status"`
|
||||||
Name string `xml:"DAV: prop>displayname,omitempty"`
|
Name string `xml:"DAV: prop>displayname,omitempty"`
|
||||||
Type *xml.Name `xml:"DAV: prop>resourcetype>collection,omitempty"`
|
Type *xml.Name `xml:"DAV: prop>resourcetype>collection,omitempty"`
|
||||||
Size int64 `xml:"DAV: prop>getcontentlength,omitempty"`
|
Size int64 `xml:"DAV: prop>getcontentlength,omitempty"`
|
||||||
Modified Time `xml:"DAV: prop>getlastmodified,omitempty"`
|
Modified Time `xml:"DAV: prop>getlastmodified,omitempty"`
|
||||||
|
Checksums []string `xml:"prop>checksums>checksum,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse a status of the form "HTTP/1.1 200 OK" or "HTTP/1.1 200"
|
// Parse a status of the form "HTTP/1.1 200 OK" or "HTTP/1.1 200"
|
||||||
@@ -92,6 +97,26 @@ func (p *Prop) StatusOK() bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Hashes returns a map of all checksums - may be nil
|
||||||
|
func (p *Prop) Hashes() (hashes map[hash.Type]string) {
|
||||||
|
if len(p.Checksums) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
hashes = make(map[hash.Type]string)
|
||||||
|
for _, checksums := range p.Checksums {
|
||||||
|
checksums = strings.ToLower(checksums)
|
||||||
|
for _, checksum := range strings.Split(checksums, " ") {
|
||||||
|
switch {
|
||||||
|
case strings.HasPrefix(checksum, "sha1:"):
|
||||||
|
hashes[hash.SHA1] = checksum[5:]
|
||||||
|
case strings.HasPrefix(checksum, "md5:"):
|
||||||
|
hashes[hash.MD5] = checksum[4:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return hashes
|
||||||
|
}
|
||||||
|
|
||||||
// PropValue is a tagged name and value
|
// PropValue is a tagged name and value
|
||||||
type PropValue struct {
|
type PropValue struct {
|
||||||
XMLName xml.Name `xml:""`
|
XMLName xml.Name `xml:""`
|
||||||
@@ -148,6 +173,8 @@ var timeFormats = []string{
|
|||||||
time.RFC3339, // Wed, 31 Oct 2018 13:57:11 CET (as used by komfortcloud.de)
|
time.RFC3339, // Wed, 31 Oct 2018 13:57:11 CET (as used by komfortcloud.de)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var oneTimeError sync.Once
|
||||||
|
|
||||||
// UnmarshalXML turns XML into a Time
|
// UnmarshalXML turns XML into a Time
|
||||||
func (t *Time) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
|
func (t *Time) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
|
||||||
var v string
|
var v string
|
||||||
@@ -171,5 +198,33 @@ func (t *Time) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if err != nil {
|
||||||
|
oneTimeError.Do(func() {
|
||||||
|
fs.Errorf(nil, "Failed to parse time %q - using the epoch", v)
|
||||||
|
})
|
||||||
|
// Return the epoch instead
|
||||||
|
*t = Time(time.Unix(0, 0))
|
||||||
|
// ignore error
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Quota is used to read the bytes used and available
|
||||||
|
//
|
||||||
|
// <d:multistatus xmlns:d="DAV:" xmlns:s="http://sabredav.org/ns" xmlns:oc="http://owncloud.org/ns" xmlns:nc="http://nextcloud.org/ns">
|
||||||
|
// <d:response>
|
||||||
|
// <d:href>/remote.php/webdav/</d:href>
|
||||||
|
// <d:propstat>
|
||||||
|
// <d:prop>
|
||||||
|
// <d:quota-available-bytes>-3</d:quota-available-bytes>
|
||||||
|
// <d:quota-used-bytes>376461895</d:quota-used-bytes>
|
||||||
|
// </d:prop>
|
||||||
|
// <d:status>HTTP/1.1 200 OK</d:status>
|
||||||
|
// </d:propstat>
|
||||||
|
// </d:response>
|
||||||
|
// </d:multistatus>
|
||||||
|
type Quota struct {
|
||||||
|
Available int64 `xml:"DAV: response>propstat>prop>quota-available-bytes"`
|
||||||
|
Used int64 `xml:"DAV: response>propstat>prop>quota-used-bytes"`
|
||||||
|
}
|
||||||
+121
-37
@@ -2,23 +2,13 @@
|
|||||||
// object storage system.
|
// object storage system.
|
||||||
package webdav
|
package webdav
|
||||||
|
|
||||||
// Owncloud: Getting Oc-Checksum:
|
|
||||||
// SHA1:f572d396fae9206628714fb2ce00f72e94f2258f on HEAD but not on
|
|
||||||
// nextcloud?
|
|
||||||
|
|
||||||
// docs for file webdav
|
|
||||||
// https://docs.nextcloud.com/server/12/developer_manual/client_apis/WebDAV/index.html
|
|
||||||
|
|
||||||
// indicates checksums can be set as metadata here
|
|
||||||
// https://github.com/nextcloud/server/issues/6129
|
|
||||||
// owncloud seems to have checksums as metadata though - can read them
|
|
||||||
|
|
||||||
// SetModTime might be possible
|
// SetModTime might be possible
|
||||||
// https://stackoverflow.com/questions/3579608/webdav-can-a-client-modify-the-mtime-of-a-file
|
// https://stackoverflow.com/questions/3579608/webdav-can-a-client-modify-the-mtime-of-a-file
|
||||||
// ...support for a PROPSET to lastmodified (mind the missing get) which does the utime() call might be an option.
|
// ...support for a PROPSET to lastmodified (mind the missing get) which does the utime() call might be an option.
|
||||||
// For example the ownCloud WebDAV server does it that way.
|
// For example the ownCloud WebDAV server does it that way.
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"encoding/xml"
|
"encoding/xml"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
@@ -31,7 +21,6 @@ import (
|
|||||||
"github.com/ncw/rclone/backend/webdav/api"
|
"github.com/ncw/rclone/backend/webdav/api"
|
||||||
"github.com/ncw/rclone/backend/webdav/odrvcookie"
|
"github.com/ncw/rclone/backend/webdav/odrvcookie"
|
||||||
"github.com/ncw/rclone/fs"
|
"github.com/ncw/rclone/fs"
|
||||||
"github.com/ncw/rclone/fs/config"
|
|
||||||
"github.com/ncw/rclone/fs/config/configmap"
|
"github.com/ncw/rclone/fs/config/configmap"
|
||||||
"github.com/ncw/rclone/fs/config/configstruct"
|
"github.com/ncw/rclone/fs/config/configstruct"
|
||||||
"github.com/ncw/rclone/fs/config/obscure"
|
"github.com/ncw/rclone/fs/config/obscure"
|
||||||
@@ -96,10 +85,11 @@ func init() {
|
|||||||
|
|
||||||
// Options defines the configuration for this backend
|
// Options defines the configuration for this backend
|
||||||
type Options struct {
|
type Options struct {
|
||||||
URL string `config:"url"`
|
URL string `config:"url"`
|
||||||
Vendor string `config:"vendor"`
|
Vendor string `config:"vendor"`
|
||||||
User string `config:"user"`
|
User string `config:"user"`
|
||||||
Pass string `config:"pass"`
|
Pass string `config:"pass"`
|
||||||
|
BearerToken string `config:"bearer_token"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fs represents a remote webdav
|
// Fs represents a remote webdav
|
||||||
@@ -116,6 +106,7 @@ type Fs struct {
|
|||||||
canStream bool // set if can stream
|
canStream bool // set if can stream
|
||||||
useOCMtime bool // set if can use X-OC-Mtime
|
useOCMtime bool // set if can use X-OC-Mtime
|
||||||
retryWithZeroDepth bool // some vendors (sharepoint) won't list files when Depth is 1 (our default)
|
retryWithZeroDepth bool // some vendors (sharepoint) won't list files when Depth is 1 (our default)
|
||||||
|
hasChecksums bool // set if can use owncloud style checksums
|
||||||
}
|
}
|
||||||
|
|
||||||
// Object describes a webdav object
|
// Object describes a webdav object
|
||||||
@@ -127,7 +118,8 @@ type Object struct {
|
|||||||
hasMetaData bool // whether info below has been set
|
hasMetaData bool // whether info below has been set
|
||||||
size int64 // size of the object
|
size int64 // size of the object
|
||||||
modTime time.Time // modification time of the object
|
modTime time.Time // modification time of the object
|
||||||
sha1 string // SHA-1 of the object content
|
sha1 string // SHA-1 of the object content if known
|
||||||
|
md5 string // MD5 of the object content if known
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------
|
// ------------------------------------------------------------
|
||||||
@@ -194,6 +186,9 @@ func (f *Fs) readMetaDataForPath(path string, depth string) (info *api.Prop, err
|
|||||||
},
|
},
|
||||||
NoRedirect: true,
|
NoRedirect: true,
|
||||||
}
|
}
|
||||||
|
if f.hasChecksums {
|
||||||
|
opts.Body = bytes.NewBuffer(owncloudProps)
|
||||||
|
}
|
||||||
var result api.Multistatus
|
var result api.Multistatus
|
||||||
var resp *http.Response
|
var resp *http.Response
|
||||||
err = f.pacer.Call(func() (bool, error) {
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
@@ -283,9 +278,6 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
rootIsDir := strings.HasSuffix(root, "/")
|
rootIsDir := strings.HasSuffix(root, "/")
|
||||||
root = strings.Trim(root, "/")
|
root = strings.Trim(root, "/")
|
||||||
|
|
||||||
user := config.FileGet(name, "user")
|
|
||||||
pass := config.FileGet(name, "pass")
|
|
||||||
bearerToken := config.FileGet(name, "bearer_token")
|
|
||||||
if !strings.HasSuffix(opt.URL, "/") {
|
if !strings.HasSuffix(opt.URL, "/") {
|
||||||
opt.URL += "/"
|
opt.URL += "/"
|
||||||
}
|
}
|
||||||
@@ -320,10 +312,10 @@ func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|||||||
f.features = (&fs.Features{
|
f.features = (&fs.Features{
|
||||||
CanHaveEmptyDirectories: true,
|
CanHaveEmptyDirectories: true,
|
||||||
}).Fill(f)
|
}).Fill(f)
|
||||||
if user != "" || pass != "" {
|
if opt.User != "" || opt.Pass != "" {
|
||||||
f.srv.SetUserPass(opt.User, opt.Pass)
|
f.srv.SetUserPass(opt.User, opt.Pass)
|
||||||
} else if bearerToken != "" {
|
} else if opt.BearerToken != "" {
|
||||||
f.srv.SetHeader("Authorization", "BEARER "+bearerToken)
|
f.srv.SetHeader("Authorization", "BEARER "+opt.BearerToken)
|
||||||
}
|
}
|
||||||
f.srv.SetErrorHandler(errorHandler)
|
f.srv.SetErrorHandler(errorHandler)
|
||||||
err = f.setQuirks(opt.Vendor)
|
err = f.setQuirks(opt.Vendor)
|
||||||
@@ -360,9 +352,11 @@ func (f *Fs) setQuirks(vendor string) error {
|
|||||||
f.canStream = true
|
f.canStream = true
|
||||||
f.precision = time.Second
|
f.precision = time.Second
|
||||||
f.useOCMtime = true
|
f.useOCMtime = true
|
||||||
|
f.hasChecksums = true
|
||||||
case "nextcloud":
|
case "nextcloud":
|
||||||
f.precision = time.Second
|
f.precision = time.Second
|
||||||
f.useOCMtime = true
|
f.useOCMtime = true
|
||||||
|
f.hasChecksums = true
|
||||||
case "sharepoint":
|
case "sharepoint":
|
||||||
// To mount sharepoint, two Cookies are required
|
// To mount sharepoint, two Cookies are required
|
||||||
// They have to be set instead of BasicAuth
|
// They have to be set instead of BasicAuth
|
||||||
@@ -429,6 +423,22 @@ func (f *Fs) NewObject(remote string) (fs.Object, error) {
|
|||||||
return f.newObjectWithInfo(remote, nil)
|
return f.newObjectWithInfo(remote, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Read the normal props, plus the checksums
|
||||||
|
//
|
||||||
|
// <oc:checksums><oc:checksum>SHA1:f572d396fae9206628714fb2ce00f72e94f2258f MD5:b1946ac92492d2347c6235b4d2611184 ADLER32:084b021f</oc:checksum></oc:checksums>
|
||||||
|
var owncloudProps = []byte(`<?xml version="1.0"?>
|
||||||
|
<d:propfind xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns" xmlns:nc="http://nextcloud.org/ns">
|
||||||
|
<d:prop>
|
||||||
|
<d:displayname />
|
||||||
|
<d:getlastmodified />
|
||||||
|
<d:getcontentlength />
|
||||||
|
<d:resourcetype />
|
||||||
|
<d:getcontenttype />
|
||||||
|
<oc:checksums />
|
||||||
|
</d:prop>
|
||||||
|
</d:propfind>
|
||||||
|
`)
|
||||||
|
|
||||||
// list the objects into the function supplied
|
// list the objects into the function supplied
|
||||||
//
|
//
|
||||||
// If directories is set it only sends directories
|
// If directories is set it only sends directories
|
||||||
@@ -448,6 +458,9 @@ func (f *Fs) listAll(dir string, directoriesOnly bool, filesOnly bool, depth str
|
|||||||
"Depth": depth,
|
"Depth": depth,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
if f.hasChecksums {
|
||||||
|
opts.Body = bytes.NewBuffer(owncloudProps)
|
||||||
|
}
|
||||||
var result api.Multistatus
|
var result api.Multistatus
|
||||||
var resp *http.Response
|
var resp *http.Response
|
||||||
err = f.pacer.Call(func() (bool, error) {
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
@@ -604,10 +617,9 @@ func (f *Fs) mkParentDir(dirPath string) error {
|
|||||||
return f.mkdir(parent)
|
return f.mkdir(parent)
|
||||||
}
|
}
|
||||||
|
|
||||||
// mkdir makes the directory and parents using native paths
|
// low level mkdir, only makes the directory, doesn't attempt to create parents
|
||||||
func (f *Fs) mkdir(dirPath string) error {
|
func (f *Fs) _mkdir(dirPath string) error {
|
||||||
// defer log.Trace(dirPath, "")("")
|
// We assume the root is already created
|
||||||
// We assume the root is already ceated
|
|
||||||
if dirPath == "" {
|
if dirPath == "" {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -620,20 +632,26 @@ func (f *Fs) mkdir(dirPath string) error {
|
|||||||
Path: dirPath,
|
Path: dirPath,
|
||||||
NoResponse: true,
|
NoResponse: true,
|
||||||
}
|
}
|
||||||
err := f.pacer.Call(func() (bool, error) {
|
return f.pacer.Call(func() (bool, error) {
|
||||||
resp, err := f.srv.Call(&opts)
|
resp, err := f.srv.Call(&opts)
|
||||||
return shouldRetry(resp, err)
|
return shouldRetry(resp, err)
|
||||||
})
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// mkdir makes the directory and parents using native paths
|
||||||
|
func (f *Fs) mkdir(dirPath string) error {
|
||||||
|
// defer log.Trace(dirPath, "")("")
|
||||||
|
err := f._mkdir(dirPath)
|
||||||
if apiErr, ok := err.(*api.Error); ok {
|
if apiErr, ok := err.(*api.Error); ok {
|
||||||
// already exists
|
// already exists
|
||||||
if apiErr.StatusCode == http.StatusMethodNotAllowed || apiErr.StatusCode == http.StatusNotAcceptable {
|
if apiErr.StatusCode == http.StatusMethodNotAllowed || apiErr.StatusCode == http.StatusNotAcceptable {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
// parent does not exists
|
// parent does not exist
|
||||||
if apiErr.StatusCode == http.StatusConflict {
|
if apiErr.StatusCode == http.StatusConflict {
|
||||||
err = f.mkParentDir(dirPath)
|
err = f.mkParentDir(dirPath)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
err = f.mkdir(dirPath)
|
err = f._mkdir(dirPath)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -845,9 +863,52 @@ func (f *Fs) DirMove(src fs.Fs, srcRemote, dstRemote string) error {
|
|||||||
|
|
||||||
// Hashes returns the supported hash sets.
|
// Hashes returns the supported hash sets.
|
||||||
func (f *Fs) Hashes() hash.Set {
|
func (f *Fs) Hashes() hash.Set {
|
||||||
|
if f.hasChecksums {
|
||||||
|
return hash.NewHashSet(hash.MD5, hash.SHA1)
|
||||||
|
}
|
||||||
return hash.Set(hash.None)
|
return hash.Set(hash.None)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// About gets quota information
|
||||||
|
func (f *Fs) About() (*fs.Usage, error) {
|
||||||
|
opts := rest.Opts{
|
||||||
|
Method: "PROPFIND",
|
||||||
|
Path: "",
|
||||||
|
ExtraHeaders: map[string]string{
|
||||||
|
"Depth": "0",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
opts.Body = bytes.NewBuffer([]byte(`<?xml version="1.0" ?>
|
||||||
|
<D:propfind xmlns:D="DAV:">
|
||||||
|
<D:prop>
|
||||||
|
<D:quota-available-bytes/>
|
||||||
|
<D:quota-used-bytes/>
|
||||||
|
</D:prop>
|
||||||
|
</D:propfind>
|
||||||
|
`))
|
||||||
|
var q = api.Quota{
|
||||||
|
Available: -1,
|
||||||
|
Used: -1,
|
||||||
|
}
|
||||||
|
var resp *http.Response
|
||||||
|
var err error
|
||||||
|
err = f.pacer.Call(func() (bool, error) {
|
||||||
|
resp, err = f.srv.CallXML(&opts, nil, &q)
|
||||||
|
return shouldRetry(resp, err)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "about call failed")
|
||||||
|
}
|
||||||
|
usage := &fs.Usage{}
|
||||||
|
if q.Available >= 0 && q.Used >= 0 {
|
||||||
|
usage.Total = fs.NewUsageValue(q.Available + q.Used)
|
||||||
|
}
|
||||||
|
if q.Used >= 0 {
|
||||||
|
usage.Used = fs.NewUsageValue(q.Used)
|
||||||
|
}
|
||||||
|
return usage, nil
|
||||||
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------
|
// ------------------------------------------------------------
|
||||||
|
|
||||||
// Fs returns the parent Fs
|
// Fs returns the parent Fs
|
||||||
@@ -868,12 +929,17 @@ func (o *Object) Remote() string {
|
|||||||
return o.remote
|
return o.remote
|
||||||
}
|
}
|
||||||
|
|
||||||
// Hash returns the SHA-1 of an object returning a lowercase hex string
|
// Hash returns the SHA1 or MD5 of an object returning a lowercase hex string
|
||||||
func (o *Object) Hash(t hash.Type) (string, error) {
|
func (o *Object) Hash(t hash.Type) (string, error) {
|
||||||
if t != hash.SHA1 {
|
if o.fs.hasChecksums {
|
||||||
return "", hash.ErrUnsupported
|
switch t {
|
||||||
|
case hash.SHA1:
|
||||||
|
return o.sha1, nil
|
||||||
|
case hash.MD5:
|
||||||
|
return o.md5, nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return o.sha1, nil
|
return "", hash.ErrUnsupported
|
||||||
}
|
}
|
||||||
|
|
||||||
// Size returns the size of an object in bytes
|
// Size returns the size of an object in bytes
|
||||||
@@ -891,6 +957,11 @@ func (o *Object) setMetaData(info *api.Prop) (err error) {
|
|||||||
o.hasMetaData = true
|
o.hasMetaData = true
|
||||||
o.size = info.Size
|
o.size = info.Size
|
||||||
o.modTime = time.Time(info.Modified)
|
o.modTime = time.Time(info.Modified)
|
||||||
|
if o.fs.hasChecksums {
|
||||||
|
hashes := info.Hashes()
|
||||||
|
o.sha1 = hashes[hash.SHA1]
|
||||||
|
o.md5 = hashes[hash.MD5]
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -970,9 +1041,21 @@ func (o *Object) Update(in io.Reader, src fs.ObjectInfo, options ...fs.OpenOptio
|
|||||||
ContentLength: &size, // FIXME this isn't necessary with owncloud - See https://github.com/nextcloud/nextcloud-snap/issues/365
|
ContentLength: &size, // FIXME this isn't necessary with owncloud - See https://github.com/nextcloud/nextcloud-snap/issues/365
|
||||||
ContentType: fs.MimeType(src),
|
ContentType: fs.MimeType(src),
|
||||||
}
|
}
|
||||||
if o.fs.useOCMtime {
|
if o.fs.useOCMtime || o.fs.hasChecksums {
|
||||||
opts.ExtraHeaders = map[string]string{
|
opts.ExtraHeaders = map[string]string{}
|
||||||
"X-OC-Mtime": fmt.Sprintf("%f", float64(src.ModTime().UnixNano())/1E9),
|
if o.fs.useOCMtime {
|
||||||
|
opts.ExtraHeaders["X-OC-Mtime"] = fmt.Sprintf("%f", float64(src.ModTime().UnixNano())/1E9)
|
||||||
|
}
|
||||||
|
if o.fs.hasChecksums {
|
||||||
|
// Set an upload checksum - prefer SHA1
|
||||||
|
//
|
||||||
|
// This is used as an upload integrity test. If we set
|
||||||
|
// only SHA1 here, owncloud will calculate the MD5 too.
|
||||||
|
if sha1, _ := src.Hash(hash.SHA1); sha1 != "" {
|
||||||
|
opts.ExtraHeaders["OC-Checksum"] = "SHA1:" + sha1
|
||||||
|
} else if md5, _ := src.Hash(hash.MD5); md5 != "" {
|
||||||
|
opts.ExtraHeaders["OC-Checksum"] = "MD5:" + md5
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
err = o.fs.pacer.CallNoRetry(func() (bool, error) {
|
err = o.fs.pacer.CallNoRetry(func() (bool, error) {
|
||||||
@@ -1016,5 +1099,6 @@ 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.Abouter = (*Fs)(nil)
|
||||||
_ fs.Object = (*Object)(nil)
|
_ fs.Object = (*Object)(nil)
|
||||||
)
|
)
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
//from yadisk
|
|
||||||
|
|
||||||
import (
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
//RootAddr is the base URL for Yandex Disk API.
|
|
||||||
const RootAddr = "https://cloud-api.yandex.com" //also https://cloud-api.yandex.net and https://cloud-api.yandex.ru
|
|
||||||
|
|
||||||
func (c *Client) setRequestScope(req *http.Request) {
|
|
||||||
req.Header.Add("Accept", "application/json")
|
|
||||||
req.Header.Add("Content-Type", "application/json")
|
|
||||||
req.Header.Add("Authorization", "OAuth "+c.token)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Client) scopedRequest(method, urlPath string, body io.Reader) (*http.Request, error) {
|
|
||||||
fullURL := RootAddr
|
|
||||||
if urlPath[:1] != "/" {
|
|
||||||
fullURL += "/" + urlPath
|
|
||||||
} else {
|
|
||||||
fullURL += urlPath
|
|
||||||
}
|
|
||||||
|
|
||||||
req, err := http.NewRequest(method, fullURL, body)
|
|
||||||
if err != nil {
|
|
||||||
return req, err
|
|
||||||
}
|
|
||||||
|
|
||||||
c.setRequestScope(req)
|
|
||||||
return req, nil
|
|
||||||
}
|
|
||||||
@@ -1,133 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"io/ioutil"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
//Client struct
|
|
||||||
type Client struct {
|
|
||||||
token string
|
|
||||||
basePath string
|
|
||||||
HTTPClient *http.Client
|
|
||||||
}
|
|
||||||
|
|
||||||
//NewClient creates new client
|
|
||||||
func NewClient(token string, client ...*http.Client) *Client {
|
|
||||||
return newClientInternal(
|
|
||||||
token,
|
|
||||||
"https://cloud-api.yandex.com/v1/disk", //also "https://cloud-api.yandex.net/v1/disk" "https://cloud-api.yandex.ru/v1/disk"
|
|
||||||
client...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func newClientInternal(token string, basePath string, client ...*http.Client) *Client {
|
|
||||||
c := &Client{
|
|
||||||
token: token,
|
|
||||||
basePath: basePath,
|
|
||||||
}
|
|
||||||
if len(client) != 0 {
|
|
||||||
c.HTTPClient = client[0]
|
|
||||||
} else {
|
|
||||||
c.HTTPClient = http.DefaultClient
|
|
||||||
}
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
//ErrorHandler type
|
|
||||||
type ErrorHandler func(*http.Response) error
|
|
||||||
|
|
||||||
var defaultErrorHandler ErrorHandler = func(resp *http.Response) error {
|
|
||||||
if resp.StatusCode/100 == 5 {
|
|
||||||
return errors.New("server error")
|
|
||||||
}
|
|
||||||
|
|
||||||
if resp.StatusCode/100 == 4 {
|
|
||||||
var response DiskClientError
|
|
||||||
contents, _ := ioutil.ReadAll(resp.Body)
|
|
||||||
err := json.Unmarshal(contents, &response)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return response
|
|
||||||
}
|
|
||||||
|
|
||||||
if resp.StatusCode/100 == 3 {
|
|
||||||
return errors.New("redirect error")
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (HTTPRequest *HTTPRequest) run(client *Client) ([]byte, error) {
|
|
||||||
var err error
|
|
||||||
values := make(url.Values)
|
|
||||||
for k, v := range HTTPRequest.Parameters {
|
|
||||||
values.Set(k, fmt.Sprintf("%v", v))
|
|
||||||
}
|
|
||||||
|
|
||||||
var req *http.Request
|
|
||||||
if HTTPRequest.Method == "POST" {
|
|
||||||
// TODO json serialize
|
|
||||||
req, err = http.NewRequest(
|
|
||||||
"POST",
|
|
||||||
client.basePath+HTTPRequest.Path,
|
|
||||||
strings.NewReader(values.Encode()))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
// TODO
|
|
||||||
// req.Header.Set("Content-Type", "application/json")
|
|
||||||
} else {
|
|
||||||
req, err = http.NewRequest(
|
|
||||||
HTTPRequest.Method,
|
|
||||||
client.basePath+HTTPRequest.Path+"?"+values.Encode(),
|
|
||||||
nil)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for headerName := range HTTPRequest.Headers {
|
|
||||||
var headerValues = HTTPRequest.Headers[headerName]
|
|
||||||
for _, headerValue := range headerValues {
|
|
||||||
req.Header.Set(headerName, headerValue)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return runRequest(client, req)
|
|
||||||
}
|
|
||||||
|
|
||||||
func runRequest(client *Client, req *http.Request) ([]byte, error) {
|
|
||||||
return runRequestWithErrorHandler(client, req, defaultErrorHandler)
|
|
||||||
}
|
|
||||||
|
|
||||||
func runRequestWithErrorHandler(client *Client, req *http.Request, errorHandler ErrorHandler) (out []byte, err error) {
|
|
||||||
resp, err := client.HTTPClient.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer CheckClose(resp.Body, &err)
|
|
||||||
|
|
||||||
return checkResponseForErrorsWithErrorHandler(resp, errorHandler)
|
|
||||||
}
|
|
||||||
|
|
||||||
func checkResponseForErrorsWithErrorHandler(resp *http.Response, errorHandler ErrorHandler) ([]byte, error) {
|
|
||||||
if resp.StatusCode/100 > 2 {
|
|
||||||
return nil, errorHandler(resp)
|
|
||||||
}
|
|
||||||
return ioutil.ReadAll(resp.Body)
|
|
||||||
}
|
|
||||||
|
|
||||||
// CheckClose is a utility function used to check the return from
|
|
||||||
// Close in a defer statement.
|
|
||||||
func CheckClose(c io.Closer, err *error) {
|
|
||||||
cerr := c.Close()
|
|
||||||
if *err == nil {
|
|
||||||
*err = cerr
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"encoding/json"
|
|
||||||
"io"
|
|
||||||
"net/url"
|
|
||||||
)
|
|
||||||
|
|
||||||
//CustomPropertyResponse struct we send and is returned by the API for CustomProperty request.
|
|
||||||
type CustomPropertyResponse struct {
|
|
||||||
CustomProperties map[string]interface{} `json:"custom_properties"`
|
|
||||||
}
|
|
||||||
|
|
||||||
//SetCustomProperty will set specified data from Yandex Disk
|
|
||||||
func (c *Client) SetCustomProperty(remotePath string, property string, value string) error {
|
|
||||||
rcm := map[string]interface{}{
|
|
||||||
property: value,
|
|
||||||
}
|
|
||||||
cpr := CustomPropertyResponse{rcm}
|
|
||||||
data, _ := json.Marshal(cpr)
|
|
||||||
body := bytes.NewReader(data)
|
|
||||||
err := c.SetCustomPropertyRequest(remotePath, body)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
//SetCustomPropertyRequest will make an CustomProperty request and return a URL to CustomProperty data to.
|
|
||||||
func (c *Client) SetCustomPropertyRequest(remotePath string, body io.Reader) (err error) {
|
|
||||||
values := url.Values{}
|
|
||||||
values.Add("path", remotePath)
|
|
||||||
req, err := c.scopedRequest("PATCH", "/v1/disk/resources?"+values.Encode(), body)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
resp, err := c.HTTPClient.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if err := CheckAPIError(resp); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer CheckClose(resp.Body, &err)
|
|
||||||
|
|
||||||
//If needed we can read response and check if custom_property is set.
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/url"
|
|
||||||
"strconv"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Delete will remove specified file/folder from Yandex Disk
|
|
||||||
func (c *Client) Delete(remotePath string, permanently bool) error {
|
|
||||||
|
|
||||||
values := url.Values{}
|
|
||||||
values.Add("permanently", strconv.FormatBool(permanently))
|
|
||||||
values.Add("path", remotePath)
|
|
||||||
urlPath := "/v1/disk/resources?" + values.Encode()
|
|
||||||
fullURL := RootAddr
|
|
||||||
if urlPath[:1] != "/" {
|
|
||||||
fullURL += "/" + urlPath
|
|
||||||
} else {
|
|
||||||
fullURL += urlPath
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.PerformDelete(fullURL)
|
|
||||||
}
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
import "encoding/json"
|
|
||||||
|
|
||||||
//DiskInfoRequest type
|
|
||||||
type DiskInfoRequest struct {
|
|
||||||
client *Client
|
|
||||||
HTTPRequest *HTTPRequest
|
|
||||||
}
|
|
||||||
|
|
||||||
func (req *DiskInfoRequest) request() *HTTPRequest {
|
|
||||||
return req.HTTPRequest
|
|
||||||
}
|
|
||||||
|
|
||||||
//DiskInfoResponse struct is returned by the API for DiskInfo request.
|
|
||||||
type DiskInfoResponse struct {
|
|
||||||
TrashSize uint64 `json:"TrashSize"`
|
|
||||||
TotalSpace uint64 `json:"TotalSpace"`
|
|
||||||
UsedSpace uint64 `json:"UsedSpace"`
|
|
||||||
SystemFolders map[string]string `json:"SystemFolders"`
|
|
||||||
}
|
|
||||||
|
|
||||||
//NewDiskInfoRequest create new DiskInfo Request
|
|
||||||
func (c *Client) NewDiskInfoRequest() *DiskInfoRequest {
|
|
||||||
return &DiskInfoRequest{
|
|
||||||
client: c,
|
|
||||||
HTTPRequest: createGetRequest(c, "/", nil),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//Exec run DiskInfo Request
|
|
||||||
func (req *DiskInfoRequest) Exec() (*DiskInfoResponse, error) {
|
|
||||||
data, err := req.request().run(req.client)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var info DiskInfoResponse
|
|
||||||
err = json.Unmarshal(data, &info)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if info.SystemFolders == nil {
|
|
||||||
info.SystemFolders = make(map[string]string)
|
|
||||||
}
|
|
||||||
|
|
||||||
return &info, nil
|
|
||||||
}
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"io"
|
|
||||||
"net/url"
|
|
||||||
)
|
|
||||||
|
|
||||||
// DownloadResponse struct is returned by the API for Download request.
|
|
||||||
type DownloadResponse struct {
|
|
||||||
HRef string `json:"href"`
|
|
||||||
Method string `json:"method"`
|
|
||||||
Templated bool `json:"templated"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Download will get specified data from Yandex.Disk supplying the extra headers
|
|
||||||
func (c *Client) Download(remotePath string, headers map[string]string) (io.ReadCloser, error) { //io.Writer
|
|
||||||
ur, err := c.DownloadRequest(remotePath)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return c.PerformDownload(ur.HRef, headers)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DownloadRequest will make an download request and return a URL to download data to.
|
|
||||||
func (c *Client) DownloadRequest(remotePath string) (ur *DownloadResponse, err error) {
|
|
||||||
values := url.Values{}
|
|
||||||
values.Add("path", remotePath)
|
|
||||||
|
|
||||||
req, err := c.scopedRequest("GET", "/v1/disk/resources/download?"+values.Encode(), nil)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
resp, err := c.HTTPClient.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if err := CheckAPIError(resp); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer CheckClose(resp.Body, &err)
|
|
||||||
|
|
||||||
ur, err = ParseDownloadResponse(resp.Body)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return ur, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ParseDownloadResponse tries to read and parse DownloadResponse struct.
|
|
||||||
func ParseDownloadResponse(data io.Reader) (*DownloadResponse, error) {
|
|
||||||
dec := json.NewDecoder(data)
|
|
||||||
var ur DownloadResponse
|
|
||||||
|
|
||||||
if err := dec.Decode(&ur); err == io.EOF {
|
|
||||||
// ok
|
|
||||||
} else if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: check if there is any trash data after JSON and crash if there is.
|
|
||||||
|
|
||||||
return &ur, nil
|
|
||||||
}
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
// EmptyTrash will permanently delete all trashed files/folders from Yandex Disk
|
|
||||||
func (c *Client) EmptyTrash() error {
|
|
||||||
fullURL := RootAddr
|
|
||||||
fullURL += "/v1/disk/trash/resources"
|
|
||||||
|
|
||||||
return c.PerformDelete(fullURL)
|
|
||||||
}
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
//from yadisk
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ErrorResponse represents erroneous API response.
|
|
||||||
// Implements go's built in `error`.
|
|
||||||
type ErrorResponse struct {
|
|
||||||
ErrorName string `json:"error"`
|
|
||||||
Description string `json:"description"`
|
|
||||||
Message string `json:"message"`
|
|
||||||
|
|
||||||
StatusCode int `json:""`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *ErrorResponse) Error() string {
|
|
||||||
return fmt.Sprintf("[%d - %s] %s (%s)", e.StatusCode, e.ErrorName, e.Description, e.Message)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ProccessErrorResponse tries to represent data passed as
|
|
||||||
// an ErrorResponse object.
|
|
||||||
func ProccessErrorResponse(data io.Reader) (*ErrorResponse, error) {
|
|
||||||
dec := json.NewDecoder(data)
|
|
||||||
var errorResponse ErrorResponse
|
|
||||||
|
|
||||||
if err := dec.Decode(&errorResponse); err == io.EOF {
|
|
||||||
// ok
|
|
||||||
} else if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: check if there is any trash data after JSON and crash if there is.
|
|
||||||
|
|
||||||
return &errorResponse, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// CheckAPIError is a convenient function to turn erroneous
|
|
||||||
// API response into go error. It closes the Body on error.
|
|
||||||
func CheckAPIError(resp *http.Response) (err error) {
|
|
||||||
if resp.StatusCode >= 200 && resp.StatusCode < 400 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
defer CheckClose(resp.Body, &err)
|
|
||||||
|
|
||||||
errorResponse, err := ProccessErrorResponse(resp.Body)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
errorResponse.StatusCode = resp.StatusCode
|
|
||||||
|
|
||||||
return errorResponse
|
|
||||||
}
|
|
||||||
|
|
||||||
// ProccessErrorString tries to represent data passed as
|
|
||||||
// an ErrorResponse object.
|
|
||||||
func ProccessErrorString(data string) (*ErrorResponse, error) {
|
|
||||||
var errorResponse ErrorResponse
|
|
||||||
if err := json.Unmarshal([]byte(data), &errorResponse); err == nil {
|
|
||||||
// ok
|
|
||||||
} else if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: check if there is any trash data after JSON and crash if there is.
|
|
||||||
|
|
||||||
return &errorResponse, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ParseAPIError Parse json error response from API
|
|
||||||
func (c *Client) ParseAPIError(jsonErr string) (string, error) { //ErrorName
|
|
||||||
errorResponse, err := ProccessErrorString(jsonErr)
|
|
||||||
if err != nil {
|
|
||||||
return err.Error(), err
|
|
||||||
}
|
|
||||||
|
|
||||||
return errorResponse.ErrorName, nil
|
|
||||||
}
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
import "encoding/json"
|
|
||||||
|
|
||||||
//DiskClientError struct
|
|
||||||
type DiskClientError struct {
|
|
||||||
Description string `json:"Description"`
|
|
||||||
Code string `json:"Error"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e DiskClientError) Error() string {
|
|
||||||
b, _ := json.Marshal(e)
|
|
||||||
return string(b)
|
|
||||||
}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
// FilesResourceListResponse struct is returned by the API for requests.
|
|
||||||
type FilesResourceListResponse struct {
|
|
||||||
Items []ResourceInfoResponse `json:"items"`
|
|
||||||
Limit *uint64 `json:"limit"`
|
|
||||||
Offset *uint64 `json:"offset"`
|
|
||||||
}
|
|
||||||
@@ -1,78 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// FlatFileListRequest struct client for FlatFileList Request
|
|
||||||
type FlatFileListRequest struct {
|
|
||||||
client *Client
|
|
||||||
HTTPRequest *HTTPRequest
|
|
||||||
}
|
|
||||||
|
|
||||||
// FlatFileListRequestOptions struct - options for request
|
|
||||||
type FlatFileListRequestOptions struct {
|
|
||||||
MediaType []MediaType
|
|
||||||
Limit *uint32
|
|
||||||
Offset *uint32
|
|
||||||
Fields []string
|
|
||||||
PreviewSize *PreviewSize
|
|
||||||
PreviewCrop *bool
|
|
||||||
}
|
|
||||||
|
|
||||||
// Request get request
|
|
||||||
func (req *FlatFileListRequest) Request() *HTTPRequest {
|
|
||||||
return req.HTTPRequest
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewFlatFileListRequest create new FlatFileList Request
|
|
||||||
func (c *Client) NewFlatFileListRequest(options ...FlatFileListRequestOptions) *FlatFileListRequest {
|
|
||||||
var parameters = make(map[string]interface{})
|
|
||||||
if len(options) > 0 {
|
|
||||||
opt := options[0]
|
|
||||||
if opt.Limit != nil {
|
|
||||||
parameters["limit"] = *opt.Limit
|
|
||||||
}
|
|
||||||
if opt.Offset != nil {
|
|
||||||
parameters["offset"] = *opt.Offset
|
|
||||||
}
|
|
||||||
if opt.Fields != nil {
|
|
||||||
parameters["fields"] = strings.Join(opt.Fields, ",")
|
|
||||||
}
|
|
||||||
if opt.PreviewSize != nil {
|
|
||||||
parameters["preview_size"] = opt.PreviewSize.String()
|
|
||||||
}
|
|
||||||
if opt.PreviewCrop != nil {
|
|
||||||
parameters["preview_crop"] = *opt.PreviewCrop
|
|
||||||
}
|
|
||||||
if opt.MediaType != nil {
|
|
||||||
var strMediaTypes = make([]string, len(opt.MediaType))
|
|
||||||
for i, t := range opt.MediaType {
|
|
||||||
strMediaTypes[i] = t.String()
|
|
||||||
}
|
|
||||||
parameters["media_type"] = strings.Join(strMediaTypes, ",")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return &FlatFileListRequest{
|
|
||||||
client: c,
|
|
||||||
HTTPRequest: createGetRequest(c, "/resources/files", parameters),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Exec run FlatFileList Request
|
|
||||||
func (req *FlatFileListRequest) Exec() (*FilesResourceListResponse, error) {
|
|
||||||
data, err := req.Request().run(req.client)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var info FilesResourceListResponse
|
|
||||||
err = json.Unmarshal(data, &info)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if cap(info.Items) == 0 {
|
|
||||||
info.Items = []ResourceInfoResponse{}
|
|
||||||
}
|
|
||||||
return &info, nil
|
|
||||||
}
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
// HTTPRequest struct
|
|
||||||
type HTTPRequest struct {
|
|
||||||
Method string
|
|
||||||
Path string
|
|
||||||
Parameters map[string]interface{}
|
|
||||||
Headers map[string][]string
|
|
||||||
}
|
|
||||||
|
|
||||||
func createGetRequest(client *Client, path string, params map[string]interface{}) *HTTPRequest {
|
|
||||||
return createRequest(client, "GET", path, params)
|
|
||||||
}
|
|
||||||
|
|
||||||
func createRequest(client *Client, method string, path string, parameters map[string]interface{}) *HTTPRequest {
|
|
||||||
var headers = make(map[string][]string)
|
|
||||||
headers["Authorization"] = []string{"OAuth " + client.token}
|
|
||||||
return &HTTPRequest{
|
|
||||||
Method: method,
|
|
||||||
Path: path,
|
|
||||||
Parameters: parameters,
|
|
||||||
Headers: headers,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
// LastUploadedResourceListResponse struct
|
|
||||||
type LastUploadedResourceListResponse struct {
|
|
||||||
Items []ResourceInfoResponse `json:"items"`
|
|
||||||
Limit *uint64 `json:"limit"`
|
|
||||||
}
|
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// LastUploadedResourceListRequest struct
|
|
||||||
type LastUploadedResourceListRequest struct {
|
|
||||||
client *Client
|
|
||||||
HTTPRequest *HTTPRequest
|
|
||||||
}
|
|
||||||
|
|
||||||
// LastUploadedResourceListRequestOptions struct
|
|
||||||
type LastUploadedResourceListRequestOptions struct {
|
|
||||||
MediaType []MediaType
|
|
||||||
Limit *uint32
|
|
||||||
Fields []string
|
|
||||||
PreviewSize *PreviewSize
|
|
||||||
PreviewCrop *bool
|
|
||||||
}
|
|
||||||
|
|
||||||
// Request return request
|
|
||||||
func (req *LastUploadedResourceListRequest) Request() *HTTPRequest {
|
|
||||||
return req.HTTPRequest
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewLastUploadedResourceListRequest create new LastUploadedResourceList Request
|
|
||||||
func (c *Client) NewLastUploadedResourceListRequest(options ...LastUploadedResourceListRequestOptions) *LastUploadedResourceListRequest {
|
|
||||||
var parameters = make(map[string]interface{})
|
|
||||||
if len(options) > 0 {
|
|
||||||
opt := options[0]
|
|
||||||
if opt.Limit != nil {
|
|
||||||
parameters["limit"] = opt.Limit
|
|
||||||
}
|
|
||||||
if opt.Fields != nil {
|
|
||||||
parameters["fields"] = strings.Join(opt.Fields, ",")
|
|
||||||
}
|
|
||||||
if opt.PreviewSize != nil {
|
|
||||||
parameters["preview_size"] = opt.PreviewSize.String()
|
|
||||||
}
|
|
||||||
if opt.PreviewCrop != nil {
|
|
||||||
parameters["preview_crop"] = opt.PreviewCrop
|
|
||||||
}
|
|
||||||
if opt.MediaType != nil {
|
|
||||||
var strMediaTypes = make([]string, len(opt.MediaType))
|
|
||||||
for i, t := range opt.MediaType {
|
|
||||||
strMediaTypes[i] = t.String()
|
|
||||||
}
|
|
||||||
parameters["media_type"] = strings.Join(strMediaTypes, ",")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return &LastUploadedResourceListRequest{
|
|
||||||
client: c,
|
|
||||||
HTTPRequest: createGetRequest(c, "/resources/last-uploaded", parameters),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Exec run LastUploadedResourceList Request
|
|
||||||
func (req *LastUploadedResourceListRequest) Exec() (*LastUploadedResourceListResponse, error) {
|
|
||||||
data, err := req.Request().run(req.client)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var info LastUploadedResourceListResponse
|
|
||||||
err = json.Unmarshal(data, &info)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if cap(info.Items) == 0 {
|
|
||||||
info.Items = []ResourceInfoResponse{}
|
|
||||||
}
|
|
||||||
return &info, nil
|
|
||||||
}
|
|
||||||
@@ -1,144 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
// MediaType struct - media types
|
|
||||||
type MediaType struct {
|
|
||||||
mediaType string
|
|
||||||
}
|
|
||||||
|
|
||||||
// Audio - media type
|
|
||||||
func (m *MediaType) Audio() *MediaType {
|
|
||||||
return &MediaType{
|
|
||||||
mediaType: "audio",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Backup - media type
|
|
||||||
func (m *MediaType) Backup() *MediaType {
|
|
||||||
return &MediaType{
|
|
||||||
mediaType: "backup",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Book - media type
|
|
||||||
func (m *MediaType) Book() *MediaType {
|
|
||||||
return &MediaType{
|
|
||||||
mediaType: "book",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Compressed - media type
|
|
||||||
func (m *MediaType) Compressed() *MediaType {
|
|
||||||
return &MediaType{
|
|
||||||
mediaType: "compressed",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Data - media type
|
|
||||||
func (m *MediaType) Data() *MediaType {
|
|
||||||
return &MediaType{
|
|
||||||
mediaType: "data",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Development - media type
|
|
||||||
func (m *MediaType) Development() *MediaType {
|
|
||||||
return &MediaType{
|
|
||||||
mediaType: "development",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Diskimage - media type
|
|
||||||
func (m *MediaType) Diskimage() *MediaType {
|
|
||||||
return &MediaType{
|
|
||||||
mediaType: "diskimage",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Document - media type
|
|
||||||
func (m *MediaType) Document() *MediaType {
|
|
||||||
return &MediaType{
|
|
||||||
mediaType: "document",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Encoded - media type
|
|
||||||
func (m *MediaType) Encoded() *MediaType {
|
|
||||||
return &MediaType{
|
|
||||||
mediaType: "encoded",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Executable - media type
|
|
||||||
func (m *MediaType) Executable() *MediaType {
|
|
||||||
return &MediaType{
|
|
||||||
mediaType: "executable",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Flash - media type
|
|
||||||
func (m *MediaType) Flash() *MediaType {
|
|
||||||
return &MediaType{
|
|
||||||
mediaType: "flash",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Font - media type
|
|
||||||
func (m *MediaType) Font() *MediaType {
|
|
||||||
return &MediaType{
|
|
||||||
mediaType: "font",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Image - media type
|
|
||||||
func (m *MediaType) Image() *MediaType {
|
|
||||||
return &MediaType{
|
|
||||||
mediaType: "image",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Settings - media type
|
|
||||||
func (m *MediaType) Settings() *MediaType {
|
|
||||||
return &MediaType{
|
|
||||||
mediaType: "settings",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Spreadsheet - media type
|
|
||||||
func (m *MediaType) Spreadsheet() *MediaType {
|
|
||||||
return &MediaType{
|
|
||||||
mediaType: "spreadsheet",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Text - media type
|
|
||||||
func (m *MediaType) Text() *MediaType {
|
|
||||||
return &MediaType{
|
|
||||||
mediaType: "text",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Unknown - media type
|
|
||||||
func (m *MediaType) Unknown() *MediaType {
|
|
||||||
return &MediaType{
|
|
||||||
mediaType: "unknown",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Video - media type
|
|
||||||
func (m *MediaType) Video() *MediaType {
|
|
||||||
return &MediaType{
|
|
||||||
mediaType: "video",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Web - media type
|
|
||||||
func (m *MediaType) Web() *MediaType {
|
|
||||||
return &MediaType{
|
|
||||||
mediaType: "web",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// String - media type
|
|
||||||
func (m *MediaType) String() string {
|
|
||||||
return m.mediaType
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/url"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Mkdir will make specified folder on Yandex Disk
|
|
||||||
func (c *Client) Mkdir(remotePath string) (int, string, error) {
|
|
||||||
|
|
||||||
values := url.Values{}
|
|
||||||
values.Add("path", remotePath) // only one current folder will be created. Not all the folders in the path.
|
|
||||||
urlPath := "/v1/disk/resources?" + values.Encode()
|
|
||||||
fullURL := RootAddr
|
|
||||||
if urlPath[:1] != "/" {
|
|
||||||
fullURL += "/" + urlPath
|
|
||||||
} else {
|
|
||||||
fullURL += urlPath
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.PerformMkdir(fullURL)
|
|
||||||
}
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
import (
|
|
||||||
"io/ioutil"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
// PerformDelete does the actual delete via DELETE request.
|
|
||||||
func (c *Client) PerformDelete(url string) error {
|
|
||||||
req, err := http.NewRequest("DELETE", url, nil)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
//set access token and headers
|
|
||||||
c.setRequestScope(req)
|
|
||||||
|
|
||||||
resp, err := c.HTTPClient.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
//204 - resource deleted.
|
|
||||||
//202 - folder not empty, content will be deleted soon (async delete).
|
|
||||||
if resp.StatusCode != 204 && resp.StatusCode != 202 {
|
|
||||||
body, err := ioutil.ReadAll(resp.Body)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return errors.Errorf("delete error [%d]: %s", resp.StatusCode, string(body))
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
import (
|
|
||||||
"io"
|
|
||||||
"io/ioutil"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
// PerformDownload does the actual download via unscoped GET request.
|
|
||||||
func (c *Client) PerformDownload(url string, headers map[string]string) (out io.ReadCloser, err error) {
|
|
||||||
req, err := http.NewRequest("GET", url, nil)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set any extra headers
|
|
||||||
for k, v := range headers {
|
|
||||||
req.Header.Set(k, v)
|
|
||||||
}
|
|
||||||
|
|
||||||
//c.setRequestScope(req)
|
|
||||||
|
|
||||||
resp, err := c.HTTPClient.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
_, isRanging := req.Header["Range"]
|
|
||||||
if !(resp.StatusCode == http.StatusOK || (isRanging && resp.StatusCode == http.StatusPartialContent)) {
|
|
||||||
defer CheckClose(resp.Body, &err)
|
|
||||||
body, err := ioutil.ReadAll(resp.Body)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return nil, errors.Errorf("download error [%d]: %s", resp.StatusCode, string(body))
|
|
||||||
}
|
|
||||||
return resp.Body, err
|
|
||||||
}
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
import (
|
|
||||||
"io/ioutil"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
// PerformMkdir does the actual mkdir via PUT request.
|
|
||||||
func (c *Client) PerformMkdir(url string) (int, string, error) {
|
|
||||||
req, err := http.NewRequest("PUT", url, nil)
|
|
||||||
if err != nil {
|
|
||||||
return 0, "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
//set access token and headers
|
|
||||||
c.setRequestScope(req)
|
|
||||||
|
|
||||||
resp, err := c.HTTPClient.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return 0, "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
if resp.StatusCode != 201 {
|
|
||||||
body, err := ioutil.ReadAll(resp.Body)
|
|
||||||
if err != nil {
|
|
||||||
return 0, "", err
|
|
||||||
}
|
|
||||||
//third parameter is the json error response body
|
|
||||||
return resp.StatusCode, string(body), errors.Errorf("create folder error [%d]: %s", resp.StatusCode, string(body))
|
|
||||||
}
|
|
||||||
return resp.StatusCode, "", nil
|
|
||||||
}
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
//from yadisk
|
|
||||||
|
|
||||||
import (
|
|
||||||
"io"
|
|
||||||
"io/ioutil"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
// PerformUpload does the actual upload via unscoped PUT request.
|
|
||||||
func (c *Client) PerformUpload(url string, data io.Reader, contentType string) (err error) {
|
|
||||||
req, err := http.NewRequest("PUT", url, data)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
req.Header.Set("Content-Type", contentType)
|
|
||||||
|
|
||||||
//c.setRequestScope(req)
|
|
||||||
|
|
||||||
resp, err := c.HTTPClient.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer CheckClose(resp.Body, &err)
|
|
||||||
|
|
||||||
if resp.StatusCode != 201 {
|
|
||||||
body, err := ioutil.ReadAll(resp.Body)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
return errors.Errorf("upload error [%d]: %s", resp.StatusCode, string(body))
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
import "fmt"
|
|
||||||
|
|
||||||
// PreviewSize struct
|
|
||||||
type PreviewSize struct {
|
|
||||||
size string
|
|
||||||
}
|
|
||||||
|
|
||||||
// PredefinedSizeS - set preview size
|
|
||||||
func (s *PreviewSize) PredefinedSizeS() *PreviewSize {
|
|
||||||
return &PreviewSize{
|
|
||||||
size: "S",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// PredefinedSizeM - set preview size
|
|
||||||
func (s *PreviewSize) PredefinedSizeM() *PreviewSize {
|
|
||||||
return &PreviewSize{
|
|
||||||
size: "M",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// PredefinedSizeL - set preview size
|
|
||||||
func (s *PreviewSize) PredefinedSizeL() *PreviewSize {
|
|
||||||
return &PreviewSize{
|
|
||||||
size: "L",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// PredefinedSizeXL - set preview size
|
|
||||||
func (s *PreviewSize) PredefinedSizeXL() *PreviewSize {
|
|
||||||
return &PreviewSize{
|
|
||||||
size: "XL",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// PredefinedSizeXXL - set preview size
|
|
||||||
func (s *PreviewSize) PredefinedSizeXXL() *PreviewSize {
|
|
||||||
return &PreviewSize{
|
|
||||||
size: "XXL",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// PredefinedSizeXXXL - set preview size
|
|
||||||
func (s *PreviewSize) PredefinedSizeXXXL() *PreviewSize {
|
|
||||||
return &PreviewSize{
|
|
||||||
size: "XXXL",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ExactWidth - set preview size
|
|
||||||
func (s *PreviewSize) ExactWidth(width uint32) *PreviewSize {
|
|
||||||
return &PreviewSize{
|
|
||||||
size: fmt.Sprintf("%dx", width),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ExactHeight - set preview size
|
|
||||||
func (s *PreviewSize) ExactHeight(height uint32) *PreviewSize {
|
|
||||||
return &PreviewSize{
|
|
||||||
size: fmt.Sprintf("x%d", height),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ExactSize - set preview size
|
|
||||||
func (s *PreviewSize) ExactSize(width uint32, height uint32) *PreviewSize {
|
|
||||||
return &PreviewSize{
|
|
||||||
size: fmt.Sprintf("%dx%d", width, height),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *PreviewSize) String() string {
|
|
||||||
return s.size
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
//ResourceInfoResponse struct is returned by the API for metedata requests.
|
|
||||||
type ResourceInfoResponse struct {
|
|
||||||
PublicKey string `json:"public_key"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
Created string `json:"created"`
|
|
||||||
CustomProperties map[string]interface{} `json:"custom_properties"`
|
|
||||||
Preview string `json:"preview"`
|
|
||||||
PublicURL string `json:"public_url"`
|
|
||||||
OriginPath string `json:"origin_path"`
|
|
||||||
Modified string `json:"modified"`
|
|
||||||
Path string `json:"path"`
|
|
||||||
Md5 string `json:"md5"`
|
|
||||||
ResourceType string `json:"type"`
|
|
||||||
MimeType string `json:"mime_type"`
|
|
||||||
Size uint64 `json:"size"`
|
|
||||||
Embedded *ResourceListResponse `json:"_embedded"`
|
|
||||||
}
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
import "encoding/json"
|
|
||||||
|
|
||||||
// ResourceInfoRequest struct
|
|
||||||
type ResourceInfoRequest struct {
|
|
||||||
client *Client
|
|
||||||
HTTPRequest *HTTPRequest
|
|
||||||
}
|
|
||||||
|
|
||||||
// Request of ResourceInfoRequest
|
|
||||||
func (req *ResourceInfoRequest) Request() *HTTPRequest {
|
|
||||||
return req.HTTPRequest
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewResourceInfoRequest create new ResourceInfo Request
|
|
||||||
func (c *Client) NewResourceInfoRequest(path string, options ...ResourceInfoRequestOptions) *ResourceInfoRequest {
|
|
||||||
return &ResourceInfoRequest{
|
|
||||||
client: c,
|
|
||||||
HTTPRequest: createResourceInfoRequest(c, "/resources", path, options...),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Exec run ResourceInfo Request
|
|
||||||
func (req *ResourceInfoRequest) Exec() (*ResourceInfoResponse, error) {
|
|
||||||
data, err := req.Request().run(req.client)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var info ResourceInfoResponse
|
|
||||||
err = json.Unmarshal(data, &info)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if info.CustomProperties == nil {
|
|
||||||
info.CustomProperties = make(map[string]interface{})
|
|
||||||
}
|
|
||||||
if info.Embedded != nil {
|
|
||||||
if cap(info.Embedded.Items) == 0 {
|
|
||||||
info.Embedded.Items = []ResourceInfoResponse{}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return &info, nil
|
|
||||||
}
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
import "strings"
|
|
||||||
|
|
||||||
func createResourceInfoRequest(c *Client,
|
|
||||||
apiPath string,
|
|
||||||
path string,
|
|
||||||
options ...ResourceInfoRequestOptions) *HTTPRequest {
|
|
||||||
var parameters = make(map[string]interface{})
|
|
||||||
parameters["path"] = path
|
|
||||||
if len(options) > 0 {
|
|
||||||
opt := options[0]
|
|
||||||
if opt.SortMode != nil {
|
|
||||||
parameters["sort"] = opt.SortMode.String()
|
|
||||||
}
|
|
||||||
if opt.Limit != nil {
|
|
||||||
parameters["limit"] = *opt.Limit
|
|
||||||
}
|
|
||||||
if opt.Offset != nil {
|
|
||||||
parameters["offset"] = *opt.Offset
|
|
||||||
}
|
|
||||||
if opt.Fields != nil {
|
|
||||||
parameters["fields"] = strings.Join(opt.Fields, ",")
|
|
||||||
}
|
|
||||||
if opt.PreviewSize != nil {
|
|
||||||
parameters["preview_size"] = opt.PreviewSize.String()
|
|
||||||
}
|
|
||||||
if opt.PreviewCrop != nil {
|
|
||||||
parameters["preview_crop"] = *opt.PreviewCrop
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return createGetRequest(c, apiPath, parameters)
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
// ResourceInfoRequestOptions struct
|
|
||||||
type ResourceInfoRequestOptions struct {
|
|
||||||
SortMode *SortMode
|
|
||||||
Limit *uint32
|
|
||||||
Offset *uint32
|
|
||||||
Fields []string
|
|
||||||
PreviewSize *PreviewSize
|
|
||||||
PreviewCrop *bool
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
// ResourceListResponse struct
|
|
||||||
type ResourceListResponse struct {
|
|
||||||
Sort *SortMode `json:"sort"`
|
|
||||||
PublicKey string `json:"public_key"`
|
|
||||||
Items []ResourceInfoResponse `json:"items"`
|
|
||||||
Path string `json:"path"`
|
|
||||||
Limit *uint64 `json:"limit"`
|
|
||||||
Offset *uint64 `json:"offset"`
|
|
||||||
Total *uint64 `json:"total"`
|
|
||||||
}
|
|
||||||
@@ -1,79 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
import "strings"
|
|
||||||
|
|
||||||
// SortMode struct - sort mode
|
|
||||||
type SortMode struct {
|
|
||||||
mode string
|
|
||||||
}
|
|
||||||
|
|
||||||
// Default - sort mode
|
|
||||||
func (m *SortMode) Default() *SortMode {
|
|
||||||
return &SortMode{
|
|
||||||
mode: "",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ByName - sort mode
|
|
||||||
func (m *SortMode) ByName() *SortMode {
|
|
||||||
return &SortMode{
|
|
||||||
mode: "name",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ByPath - sort mode
|
|
||||||
func (m *SortMode) ByPath() *SortMode {
|
|
||||||
return &SortMode{
|
|
||||||
mode: "path",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ByCreated - sort mode
|
|
||||||
func (m *SortMode) ByCreated() *SortMode {
|
|
||||||
return &SortMode{
|
|
||||||
mode: "created",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ByModified - sort mode
|
|
||||||
func (m *SortMode) ByModified() *SortMode {
|
|
||||||
return &SortMode{
|
|
||||||
mode: "modified",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// BySize - sort mode
|
|
||||||
func (m *SortMode) BySize() *SortMode {
|
|
||||||
return &SortMode{
|
|
||||||
mode: "size",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reverse - sort mode
|
|
||||||
func (m *SortMode) Reverse() *SortMode {
|
|
||||||
if strings.HasPrefix(m.mode, "-") {
|
|
||||||
return &SortMode{
|
|
||||||
mode: m.mode[1:],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return &SortMode{
|
|
||||||
mode: "-" + m.mode,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *SortMode) String() string {
|
|
||||||
return m.mode
|
|
||||||
}
|
|
||||||
|
|
||||||
// UnmarshalJSON sort mode
|
|
||||||
func (m *SortMode) UnmarshalJSON(value []byte) error {
|
|
||||||
if value == nil || len(value) == 0 {
|
|
||||||
m.mode = ""
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
m.mode = string(value)
|
|
||||||
if strings.HasPrefix(m.mode, "\"") && strings.HasSuffix(m.mode, "\"") {
|
|
||||||
m.mode = m.mode[1 : len(m.mode)-1]
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
import "encoding/json"
|
|
||||||
|
|
||||||
// TrashResourceInfoRequest struct
|
|
||||||
type TrashResourceInfoRequest struct {
|
|
||||||
client *Client
|
|
||||||
HTTPRequest *HTTPRequest
|
|
||||||
}
|
|
||||||
|
|
||||||
// Request of TrashResourceInfoRequest struct
|
|
||||||
func (req *TrashResourceInfoRequest) Request() *HTTPRequest {
|
|
||||||
return req.HTTPRequest
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewTrashResourceInfoRequest create new TrashResourceInfo Request
|
|
||||||
func (c *Client) NewTrashResourceInfoRequest(path string, options ...ResourceInfoRequestOptions) *TrashResourceInfoRequest {
|
|
||||||
return &TrashResourceInfoRequest{
|
|
||||||
client: c,
|
|
||||||
HTTPRequest: createResourceInfoRequest(c, "/trash/resources", path, options...),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Exec run TrashResourceInfo Request
|
|
||||||
func (req *TrashResourceInfoRequest) Exec() (*ResourceInfoResponse, error) {
|
|
||||||
data, err := req.Request().run(req.client)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var info ResourceInfoResponse
|
|
||||||
err = json.Unmarshal(data, &info)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if info.CustomProperties == nil {
|
|
||||||
info.CustomProperties = make(map[string]interface{})
|
|
||||||
}
|
|
||||||
if info.Embedded != nil {
|
|
||||||
if cap(info.Embedded.Items) == 0 {
|
|
||||||
info.Embedded.Items = []ResourceInfoResponse{}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return &info, nil
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DiskInfo contains disk metadata
|
||||||
|
type DiskInfo struct {
|
||||||
|
TotalSpace int64 `json:"total_space"`
|
||||||
|
UsedSpace int64 `json:"used_space"`
|
||||||
|
TrashSize int64 `json:"trash_size"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResourceInfoRequestOptions struct
|
||||||
|
type ResourceInfoRequestOptions struct {
|
||||||
|
SortMode *SortMode
|
||||||
|
Limit uint64
|
||||||
|
Offset uint64
|
||||||
|
Fields []string
|
||||||
|
}
|
||||||
|
|
||||||
|
//ResourceInfoResponse struct is returned by the API for metedata requests.
|
||||||
|
type ResourceInfoResponse struct {
|
||||||
|
PublicKey string `json:"public_key"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Created string `json:"created"`
|
||||||
|
CustomProperties map[string]interface{} `json:"custom_properties"`
|
||||||
|
Preview string `json:"preview"`
|
||||||
|
PublicURL string `json:"public_url"`
|
||||||
|
OriginPath string `json:"origin_path"`
|
||||||
|
Modified string `json:"modified"`
|
||||||
|
Path string `json:"path"`
|
||||||
|
Md5 string `json:"md5"`
|
||||||
|
ResourceType string `json:"type"`
|
||||||
|
MimeType string `json:"mime_type"`
|
||||||
|
Size int64 `json:"size"`
|
||||||
|
Embedded *ResourceListResponse `json:"_embedded"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResourceListResponse struct
|
||||||
|
type ResourceListResponse struct {
|
||||||
|
Sort *SortMode `json:"sort"`
|
||||||
|
PublicKey string `json:"public_key"`
|
||||||
|
Items []ResourceInfoResponse `json:"items"`
|
||||||
|
Path string `json:"path"`
|
||||||
|
Limit *uint64 `json:"limit"`
|
||||||
|
Offset *uint64 `json:"offset"`
|
||||||
|
Total *uint64 `json:"total"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// AsyncInfo struct is returned by the API for various async operations.
|
||||||
|
type AsyncInfo struct {
|
||||||
|
HRef string `json:"href"`
|
||||||
|
Method string `json:"method"`
|
||||||
|
Templated bool `json:"templated"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// AsyncStatus is returned when requesting the status of an async operations. Possble values in-progress, success, failure
|
||||||
|
type AsyncStatus struct {
|
||||||
|
Status string `json:"status"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//CustomPropertyResponse struct we send and is returned by the API for CustomProperty request.
|
||||||
|
type CustomPropertyResponse struct {
|
||||||
|
CustomProperties map[string]interface{} `json:"custom_properties"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// SortMode struct - sort mode
|
||||||
|
type SortMode struct {
|
||||||
|
mode string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Default - sort mode
|
||||||
|
func (m *SortMode) Default() *SortMode {
|
||||||
|
return &SortMode{
|
||||||
|
mode: "",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ByName - sort mode
|
||||||
|
func (m *SortMode) ByName() *SortMode {
|
||||||
|
return &SortMode{
|
||||||
|
mode: "name",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ByPath - sort mode
|
||||||
|
func (m *SortMode) ByPath() *SortMode {
|
||||||
|
return &SortMode{
|
||||||
|
mode: "path",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ByCreated - sort mode
|
||||||
|
func (m *SortMode) ByCreated() *SortMode {
|
||||||
|
return &SortMode{
|
||||||
|
mode: "created",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ByModified - sort mode
|
||||||
|
func (m *SortMode) ByModified() *SortMode {
|
||||||
|
return &SortMode{
|
||||||
|
mode: "modified",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// BySize - sort mode
|
||||||
|
func (m *SortMode) BySize() *SortMode {
|
||||||
|
return &SortMode{
|
||||||
|
mode: "size",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reverse - sort mode
|
||||||
|
func (m *SortMode) Reverse() *SortMode {
|
||||||
|
if strings.HasPrefix(m.mode, "-") {
|
||||||
|
return &SortMode{
|
||||||
|
mode: m.mode[1:],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return &SortMode{
|
||||||
|
mode: "-" + m.mode,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *SortMode) String() string {
|
||||||
|
return m.mode
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnmarshalJSON sort mode
|
||||||
|
func (m *SortMode) UnmarshalJSON(value []byte) error {
|
||||||
|
if value == nil || len(value) == 0 {
|
||||||
|
m.mode = ""
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
m.mode = string(value)
|
||||||
|
if strings.HasPrefix(m.mode, "\"") && strings.HasSuffix(m.mode, "\"") {
|
||||||
|
m.mode = m.mode[1 : len(m.mode)-1]
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ErrorResponse represents erroneous API response.
|
||||||
|
// Implements go's built in `error`.
|
||||||
|
type ErrorResponse struct {
|
||||||
|
ErrorName string `json:"error"`
|
||||||
|
Description string `json:"description"`
|
||||||
|
Message string `json:"message"`
|
||||||
|
|
||||||
|
StatusCode int `json:""`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *ErrorResponse) Error() string {
|
||||||
|
return fmt.Sprintf("[%d - %s] %s (%s)", e.StatusCode, e.ErrorName, e.Description, e.Message)
|
||||||
|
}
|
||||||
@@ -1,71 +0,0 @@
|
|||||||
package src
|
|
||||||
|
|
||||||
//from yadisk
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"io"
|
|
||||||
"net/url"
|
|
||||||
"strconv"
|
|
||||||
)
|
|
||||||
|
|
||||||
// UploadResponse struct is returned by the API for upload request.
|
|
||||||
type UploadResponse struct {
|
|
||||||
HRef string `json:"href"`
|
|
||||||
Method string `json:"method"`
|
|
||||||
Templated bool `json:"templated"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Upload will put specified data to Yandex.Disk.
|
|
||||||
func (c *Client) Upload(data io.Reader, remotePath string, overwrite bool, contentType string) error {
|
|
||||||
ur, err := c.UploadRequest(remotePath, overwrite)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.PerformUpload(ur.HRef, data, contentType)
|
|
||||||
}
|
|
||||||
|
|
||||||
// UploadRequest will make an upload request and return a URL to upload data to.
|
|
||||||
func (c *Client) UploadRequest(remotePath string, overwrite bool) (ur *UploadResponse, err error) {
|
|
||||||
values := url.Values{}
|
|
||||||
values.Add("path", remotePath)
|
|
||||||
values.Add("overwrite", strconv.FormatBool(overwrite))
|
|
||||||
|
|
||||||
req, err := c.scopedRequest("GET", "/v1/disk/resources/upload?"+values.Encode(), nil)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
resp, err := c.HTTPClient.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if err := CheckAPIError(resp); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer CheckClose(resp.Body, &err)
|
|
||||||
|
|
||||||
ur, err = ParseUploadResponse(resp.Body)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return ur, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ParseUploadResponse tries to read and parse UploadResponse struct.
|
|
||||||
func ParseUploadResponse(data io.Reader) (*UploadResponse, error) {
|
|
||||||
dec := json.NewDecoder(data)
|
|
||||||
var ur UploadResponse
|
|
||||||
|
|
||||||
if err := dec.Decode(&ur); err == io.EOF {
|
|
||||||
// ok
|
|
||||||
} else if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: check if there is any trash data after JSON and crash if there is.
|
|
||||||
|
|
||||||
return &ur, nil
|
|
||||||
}
|
|
||||||
+824
-374
File diff suppressed because it is too large.
Load diff
Executable
+5
@@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
docker build -t rclone/xgo-cgofuse https://github.com/billziss-gh/cgofuse.git
|
||||||
|
docker images
|
||||||
|
docker push rclone/xgo-cgofuse
|
||||||
@@ -63,7 +63,9 @@ var osarches = []string{
|
|||||||
|
|
||||||
// Special environment flags for a given arch
|
// Special environment flags for a given arch
|
||||||
var archFlags = map[string][]string{
|
var archFlags = map[string][]string{
|
||||||
"386": {"GO386=387"},
|
"386": {"GO386=387"},
|
||||||
|
"mips": {"GOMIPS=softfloat"},
|
||||||
|
"mipsle": {"GOMIPS=softfloat"},
|
||||||
}
|
}
|
||||||
|
|
||||||
// runEnv - run a shell command with env
|
// runEnv - run a shell command with env
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
// +build ignore
|
||||||
|
|
||||||
|
// Test that the tests in the suite passed in are independent
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"flag"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"regexp"
|
||||||
|
)
|
||||||
|
|
||||||
|
var matchLine = regexp.MustCompile(`(?m)^=== RUN\s*(TestIntegration/\S*)\s*$`)
|
||||||
|
|
||||||
|
// run the test pass in and grep out the test names
|
||||||
|
func findTests(packageToTest string) (tests []string) {
|
||||||
|
cmd := exec.Command("go", "test", "-v", packageToTest)
|
||||||
|
out, err := cmd.CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
_, _ = os.Stderr.Write(out)
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
results := matchLine.FindAllSubmatch(out, -1)
|
||||||
|
if results == nil {
|
||||||
|
log.Fatal("No tests found")
|
||||||
|
}
|
||||||
|
for _, line := range results {
|
||||||
|
tests = append(tests, string(line[1]))
|
||||||
|
}
|
||||||
|
return tests
|
||||||
|
}
|
||||||
|
|
||||||
|
// run the test passed in with the -run passed in
|
||||||
|
func runTest(packageToTest string, testName string) {
|
||||||
|
cmd := exec.Command("go", "test", "-v", packageToTest, "-run", "^"+testName+"$")
|
||||||
|
out, err := cmd.CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("%s FAILED ------------------", testName)
|
||||||
|
_, _ = os.Stderr.Write(out)
|
||||||
|
log.Printf("%s FAILED ------------------", testName)
|
||||||
|
} else {
|
||||||
|
log.Printf("%s OK", testName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func main() {
|
||||||
|
flag.Parse()
|
||||||
|
args := flag.Args()
|
||||||
|
if len(args) != 1 {
|
||||||
|
log.Fatalf("Syntax: %s <test_to_run>", os.Args[0])
|
||||||
|
}
|
||||||
|
packageToTest := args[0]
|
||||||
|
testNames := findTests(packageToTest)
|
||||||
|
// fmt.Printf("%s\n", testNames)
|
||||||
|
for _, testName := range testNames {
|
||||||
|
runTest(packageToTest, testName)
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-2
@@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
version="$1"
|
version="$1"
|
||||||
if [ "$version" = "" ]; then
|
if [ "$version" = "" ]; then
|
||||||
echo "Syntax: $0 <version> [delete]"
|
echo "Syntax: $0 <version, eg v1.42> [delete]"
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
dry_run="--dry-run"
|
dry_run="--dry-run"
|
||||||
@@ -14,4 +14,4 @@ else
|
|||||||
echo "Use '$0 $version delete' to actually delete files"
|
echo "Use '$0 $version delete' to actually delete files"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
rclone ${dry_run} --fast-list -P --checkers 16 --transfers 16 delete --include "**/${version}**" memstore:beta-rclone-org
|
rclone ${dry_run} -P --fast-list --checkers 16 --transfers 16 delete --include "**${version}**" memstore:beta-rclone-org
|
||||||
+4
-6
@@ -51,7 +51,7 @@ var (
|
|||||||
errorCommandNotFound = errors.New("command not found")
|
errorCommandNotFound = errors.New("command not found")
|
||||||
errorUncategorized = errors.New("uncategorized error")
|
errorUncategorized = errors.New("uncategorized error")
|
||||||
errorNotEnoughArguments = errors.New("not enough arguments")
|
errorNotEnoughArguments = errors.New("not enough arguments")
|
||||||
errorTooManyArguents = errors.New("too many arguments")
|
errorTooManyArguments = errors.New("too many arguments")
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -294,14 +294,12 @@ func Run(Retry bool, showStats bool, cmd *cobra.Command, f func() error) {
|
|||||||
func CheckArgs(MinArgs, MaxArgs int, cmd *cobra.Command, args []string) {
|
func CheckArgs(MinArgs, MaxArgs int, cmd *cobra.Command, args []string) {
|
||||||
if len(args) < MinArgs {
|
if len(args) < MinArgs {
|
||||||
_ = cmd.Usage()
|
_ = cmd.Usage()
|
||||||
_, _ = fmt.Fprintf(os.Stderr, "Command %s needs %d arguments minimum\n", cmd.Name(), MinArgs)
|
_, _ = fmt.Fprintf(os.Stderr, "Command %s needs %d arguments minimum: you provided %d non flag arguments: %q\n", cmd.Name(), MinArgs, len(args), args)
|
||||||
// os.Exit(1)
|
|
||||||
resolveExitCode(errorNotEnoughArguments)
|
resolveExitCode(errorNotEnoughArguments)
|
||||||
} else if len(args) > MaxArgs {
|
} else if len(args) > MaxArgs {
|
||||||
_ = cmd.Usage()
|
_ = cmd.Usage()
|
||||||
_, _ = fmt.Fprintf(os.Stderr, "Command %s needs %d arguments maximum\n", cmd.Name(), MaxArgs)
|
_, _ = fmt.Fprintf(os.Stderr, "Command %s needs %d arguments maximum: you provided %d non flag arguments: %q\n", cmd.Name(), MaxArgs, len(args), args)
|
||||||
// os.Exit(1)
|
resolveExitCode(errorTooManyArguments)
|
||||||
resolveExitCode(errorTooManyArguents)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+5
-1
@@ -53,7 +53,6 @@ func mountOptions(device string, mountpoint string) (options []string) {
|
|||||||
|
|
||||||
// OSX options
|
// OSX options
|
||||||
if runtime.GOOS == "darwin" {
|
if runtime.GOOS == "darwin" {
|
||||||
options = append(options, "-o", "volname="+mountlib.VolumeName)
|
|
||||||
if mountlib.NoAppleDouble {
|
if mountlib.NoAppleDouble {
|
||||||
options = append(options, "-o", "noappledouble")
|
options = append(options, "-o", "noappledouble")
|
||||||
}
|
}
|
||||||
@@ -70,6 +69,11 @@ func mountOptions(device string, mountpoint string) (options []string) {
|
|||||||
options = append(options, "--FileSystemName=rclone")
|
options = append(options, "--FileSystemName=rclone")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if runtime.GOOS == "darwin" || runtime.GOOS == "windows" {
|
||||||
|
if mountlib.VolumeName != "" {
|
||||||
|
options = append(options, "-o", "volname="+mountlib.VolumeName)
|
||||||
|
}
|
||||||
|
}
|
||||||
if mountlib.AllowNonEmpty {
|
if mountlib.AllowNonEmpty {
|
||||||
options = append(options, "-o", "nonempty")
|
options = append(options, "-o", "nonempty")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -93,6 +93,15 @@ For example to make a swift remote of name myremote using auto config
|
|||||||
you would do:
|
you would do:
|
||||||
|
|
||||||
rclone config create myremote swift env_auth true
|
rclone config create myremote swift env_auth true
|
||||||
|
|
||||||
|
Note that if the config process would normally ask a question the
|
||||||
|
default is taken. Each time that happens rclone will print a message
|
||||||
|
saying how to affect the value taken.
|
||||||
|
|
||||||
|
So for example if you wanted to configure a Google Drive remote but
|
||||||
|
using remote authorization you would do this:
|
||||||
|
|
||||||
|
rclone config create mydrive drive config_is_local false
|
||||||
`,
|
`,
|
||||||
RunE: func(command *cobra.Command, args []string) error {
|
RunE: func(command *cobra.Command, args []string) error {
|
||||||
cmd.CheckArgs(2, 256, command, args)
|
cmd.CheckArgs(2, 256, command, args)
|
||||||
@@ -119,6 +128,11 @@ in pairs of <key> <value>.
|
|||||||
For example to update the env_auth field of a remote of name myremote you would do:
|
For example to update the env_auth field of a remote of name myremote you would do:
|
||||||
|
|
||||||
rclone config update myremote swift env_auth true
|
rclone config update myremote swift env_auth true
|
||||||
|
|
||||||
|
If the remote uses oauth the token will be updated, if you don't
|
||||||
|
require this add an extra parameter thus:
|
||||||
|
|
||||||
|
rclone config update myremote swift env_auth true config_refresh_token false
|
||||||
`,
|
`,
|
||||||
RunE: func(command *cobra.Command, args []string) error {
|
RunE: func(command *cobra.Command, args []string) error {
|
||||||
cmd.CheckArgs(3, 256, command, args)
|
cmd.CheckArgs(3, 256, command, args)
|
||||||
|
|||||||
@@ -51,6 +51,17 @@ written a trailing / - meaning "copy the contents of this directory".
|
|||||||
This applies to all commands and whether you are talking about the
|
This applies to all commands and whether you are talking about the
|
||||||
source or destination.
|
source or destination.
|
||||||
|
|
||||||
|
See the [--no-traverse](/docs/#no-traverse) option for controlling
|
||||||
|
whether rclone lists the destination directory or not. Supplying this
|
||||||
|
option when copying a small number of files into a large destination
|
||||||
|
can speed transfers up greatly.
|
||||||
|
|
||||||
|
For example, if you have many files in /path/to/src but only a few of
|
||||||
|
them change every day, you can to copy all the files which have
|
||||||
|
changed recently very efficiently like this:
|
||||||
|
|
||||||
|
rclone copy --max-age 24h --no-traverse /path/to/src remote:
|
||||||
|
|
||||||
**Note**: Use the ` + "`-P`" + `/` + "`--progress`" + ` flag to view real-time transfer statistics
|
**Note**: Use the ` + "`-P`" + `/` + "`--progress`" + ` flag to view real-time transfer statistics
|
||||||
`,
|
`,
|
||||||
Run: func(command *cobra.Command, args []string) {
|
Run: func(command *cobra.Command, args []string) {
|
||||||
|
|||||||
@@ -138,6 +138,7 @@ func (r *results) checkChar(c rune) {
|
|||||||
escape := false
|
escape := false
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fs.Infof(r.f, "Couldn't write file 0x%02X", c)
|
fs.Infof(r.f, "Couldn't write file 0x%02X", c)
|
||||||
|
escape = true
|
||||||
} else {
|
} else {
|
||||||
fs.Infof(r.f, "OK writing file 0x%02X", c)
|
fs.Infof(r.f, "OK writing file 0x%02X", c)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ package mountlib
|
|||||||
import (
|
import (
|
||||||
"log"
|
"log"
|
||||||
|
|
||||||
"github.com/sevlyar/go-daemon"
|
daemon "github.com/sevlyar/go-daemon"
|
||||||
)
|
)
|
||||||
|
|
||||||
func startBackgroundMode() bool {
|
func startBackgroundMode() bool {
|
||||||
|
|||||||
+38
-4
@@ -4,6 +4,7 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
|
"path/filepath"
|
||||||
"runtime"
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -62,6 +63,28 @@ func checkMountEmpty(mountpoint string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check the root doesn't overlap the mountpoint
|
||||||
|
func checkMountpointOverlap(root, mountpoint string) error {
|
||||||
|
abs := func(x string) string {
|
||||||
|
if absX, err := filepath.EvalSymlinks(x); err == nil {
|
||||||
|
x = absX
|
||||||
|
}
|
||||||
|
if absX, err := filepath.Abs(x); err == nil {
|
||||||
|
x = absX
|
||||||
|
}
|
||||||
|
x = filepath.ToSlash(x)
|
||||||
|
if !strings.HasSuffix(x, "/") {
|
||||||
|
x += "/"
|
||||||
|
}
|
||||||
|
return x
|
||||||
|
}
|
||||||
|
rootAbs, mountpointAbs := abs(root), abs(mountpoint)
|
||||||
|
if strings.HasPrefix(rootAbs, mountpointAbs) || strings.HasPrefix(mountpointAbs, rootAbs) {
|
||||||
|
return errors.Errorf("mount point %q and directory to be mounted %q mustn't overlap", mountpoint, root)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// NewMountCommand makes a mount command with the given name and Mount function
|
// NewMountCommand makes a mount command with the given name and Mount function
|
||||||
func NewMountCommand(commandName string, Mount func(f fs.Fs, mountpoint string) error) *cobra.Command {
|
func NewMountCommand(commandName string, Mount func(f fs.Fs, mountpoint string) error) *cobra.Command {
|
||||||
var commandDefintion = &cobra.Command{
|
var commandDefintion = &cobra.Command{
|
||||||
@@ -147,7 +170,7 @@ systems are a long way from 100% reliable. The rclone sync/copy
|
|||||||
commands cope with this with lots of retries. However rclone ` + commandName + `
|
commands cope with this with lots of retries. However rclone ` + commandName + `
|
||||||
can't use retries in the same way without making local copies of the
|
can't use retries in the same way without making local copies of the
|
||||||
uploads. Look at the [file caching](#file-caching)
|
uploads. Look at the [file caching](#file-caching)
|
||||||
for solutions to make ` + commandName + ` mount more reliable.
|
for solutions to make ` + commandName + ` more reliable.
|
||||||
|
|
||||||
### Attribute caching
|
### Attribute caching
|
||||||
|
|
||||||
@@ -220,7 +243,14 @@ be copied to the vfs cache before opening with --vfs-cache-mode full.
|
|||||||
config.PassConfigKeyForDaemonization = true
|
config.PassConfigKeyForDaemonization = true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
mountpoint := args[1]
|
||||||
fdst := cmd.NewFsDir(args)
|
fdst := cmd.NewFsDir(args)
|
||||||
|
if fdst.Name() == "" || fdst.Name() == "local" {
|
||||||
|
err := checkMountpointOverlap(fdst.Root(), mountpoint)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Fatal error: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Show stats if the user has specifically requested them
|
// Show stats if the user has specifically requested them
|
||||||
if cmd.ShowStats() {
|
if cmd.ShowStats() {
|
||||||
@@ -230,7 +260,7 @@ be copied to the vfs cache before opening with --vfs-cache-mode full.
|
|||||||
// Skip checkMountEmpty if --allow-non-empty flag is used or if
|
// Skip checkMountEmpty if --allow-non-empty flag is used or if
|
||||||
// the Operating System is Windows
|
// the Operating System is Windows
|
||||||
if !AllowNonEmpty && runtime.GOOS != "windows" {
|
if !AllowNonEmpty && runtime.GOOS != "windows" {
|
||||||
err := checkMountEmpty(args[1])
|
err := checkMountEmpty(mountpoint)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Fatal error: %v", err)
|
log.Fatalf("Fatal error: %v", err)
|
||||||
}
|
}
|
||||||
@@ -253,7 +283,7 @@ be copied to the vfs cache before opening with --vfs-cache-mode full.
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
err := Mount(fdst, args[1])
|
err := Mount(fdst, mountpoint)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Fatal error: %v", err)
|
log.Fatalf("Fatal error: %v", err)
|
||||||
}
|
}
|
||||||
@@ -296,7 +326,11 @@ func ClipBlocks(b *uint64) {
|
|||||||
var max uint64
|
var max uint64
|
||||||
switch runtime.GOOS {
|
switch runtime.GOOS {
|
||||||
case "windows":
|
case "windows":
|
||||||
max = (1 << 43) - 1
|
if runtime.GOARCH == "386" {
|
||||||
|
max = (1 << 32) - 1
|
||||||
|
} else {
|
||||||
|
max = (1 << 43) - 1
|
||||||
|
}
|
||||||
case "darwin":
|
case "darwin":
|
||||||
// OSX FUSE only supports 32 bit number of blocks
|
// OSX FUSE only supports 32 bit number of blocks
|
||||||
// https://github.com/osxfuse/osxfuse/issues/396
|
// https://github.com/osxfuse/osxfuse/issues/396
|
||||||
|
|||||||
@@ -37,6 +37,11 @@ into ` + "`dest:path`" + ` then delete the original (if no errors on copy) in
|
|||||||
|
|
||||||
If you want to delete empty source directories after move, use the --delete-empty-src-dirs flag.
|
If you want to delete empty source directories after move, use the --delete-empty-src-dirs flag.
|
||||||
|
|
||||||
|
See the [--no-traverse](/docs/#no-traverse) option for controlling
|
||||||
|
whether rclone lists the destination directory or not. Supplying this
|
||||||
|
option when moving a small number of files into a large destination
|
||||||
|
can speed transfers up greatly.
|
||||||
|
|
||||||
**Important**: Since this can cause data loss, test first with the
|
**Important**: Since this can cause data loss, test first with the
|
||||||
--dry-run flag.
|
--dry-run flag.
|
||||||
|
|
||||||
|
|||||||
+2
-9
@@ -424,20 +424,13 @@ func (u *UI) removeEntry(pos int) {
|
|||||||
func (u *UI) delete() {
|
func (u *UI) delete() {
|
||||||
dirPos := u.sortPerm[u.dirPosMap[u.path].entry]
|
dirPos := u.sortPerm[u.dirPosMap[u.path].entry]
|
||||||
entry := u.entries[dirPos]
|
entry := u.entries[dirPos]
|
||||||
|
|
||||||
file := false
|
|
||||||
d, _ := u.d.GetDir(dirPos)
|
|
||||||
if d == nil {
|
|
||||||
file = true
|
|
||||||
}
|
|
||||||
|
|
||||||
u.boxMenu = []string{"cancel", "confirm"}
|
u.boxMenu = []string{"cancel", "confirm"}
|
||||||
if file {
|
if obj, isFile := entry.(fs.Object); isFile {
|
||||||
u.boxMenuHandler = func(f fs.Fs, p string, o int) (string, error) {
|
u.boxMenuHandler = func(f fs.Fs, p string, o int) (string, error) {
|
||||||
if o != 1 {
|
if o != 1 {
|
||||||
return "Aborted!", nil
|
return "Aborted!", nil
|
||||||
}
|
}
|
||||||
err := f.Rmdir(entry.String())
|
err := operations.DeleteFile(obj)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,6 +27,11 @@ const (
|
|||||||
//
|
//
|
||||||
// It returns a func which should be called to stop the stats.
|
// It returns a func which should be called to stop the stats.
|
||||||
func startProgress() func() {
|
func startProgress() func() {
|
||||||
|
err := initTerminal()
|
||||||
|
if err != nil {
|
||||||
|
fs.Errorf(nil, "Failed to start progress: %v", err)
|
||||||
|
return func() {}
|
||||||
|
}
|
||||||
stopStats := make(chan struct{})
|
stopStats := make(chan struct{})
|
||||||
oldLogPrint := fs.LogPrint
|
oldLogPrint := fs.LogPrint
|
||||||
if !log.Redirected() {
|
if !log.Redirected() {
|
||||||
@@ -51,6 +56,7 @@ func startProgress() func() {
|
|||||||
printProgress("")
|
printProgress("")
|
||||||
case <-stopStats:
|
case <-stopStats:
|
||||||
ticker.Stop()
|
ticker.Stop()
|
||||||
|
printProgress("")
|
||||||
fs.LogPrint = oldLogPrint
|
fs.LogPrint = oldLogPrint
|
||||||
fmt.Println("")
|
fmt.Println("")
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -4,6 +4,10 @@ package cmd
|
|||||||
|
|
||||||
import "os"
|
import "os"
|
||||||
|
|
||||||
|
func initTerminal() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func writeToTerminal(b []byte) {
|
func writeToTerminal(b []byte) {
|
||||||
_, _ = os.Stdout.Write(b)
|
_, _ = os.Stdout.Write(b)
|
||||||
}
|
}
|
||||||
+16
-7
@@ -5,22 +5,31 @@ package cmd
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"sync"
|
"syscall"
|
||||||
|
|
||||||
ansiterm "github.com/Azure/go-ansiterm"
|
ansiterm "github.com/Azure/go-ansiterm"
|
||||||
"github.com/Azure/go-ansiterm/winterm"
|
"github.com/Azure/go-ansiterm/winterm"
|
||||||
|
"github.com/pkg/errors"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
initAnsiParser sync.Once
|
ansiParser *ansiterm.AnsiParser
|
||||||
ansiParser *ansiterm.AnsiParser
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func initTerminal() error {
|
||||||
|
winEventHandler := winterm.CreateWinEventHandler(os.Stdout.Fd(), os.Stdout)
|
||||||
|
if winEventHandler == nil {
|
||||||
|
err := syscall.GetLastError()
|
||||||
|
if err == nil {
|
||||||
|
err = errors.New("initialization failed")
|
||||||
|
}
|
||||||
|
return errors.Wrap(err, "windows terminal")
|
||||||
|
}
|
||||||
|
ansiParser = ansiterm.CreateParser("Ground", winEventHandler)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func writeToTerminal(b []byte) {
|
func writeToTerminal(b []byte) {
|
||||||
initAnsiParser.Do(func() {
|
|
||||||
winEventHandler := winterm.CreateWinEventHandler(os.Stdout.Fd(), os.Stdout)
|
|
||||||
ansiParser = ansiterm.CreateParser("Ground", winEventHandler)
|
|
||||||
})
|
|
||||||
// Remove all non-ASCII characters until this is fixed
|
// Remove all non-ASCII characters until this is fixed
|
||||||
// https://github.com/Azure/go-ansiterm/issues/26
|
// https://github.com/Azure/go-ansiterm/issues/26
|
||||||
r := []rune(string(b))
|
r := []rune(string(b))
|
||||||
|
|||||||
Loaded 100 of 638 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user