A request for the whole file as a range, as "bytes=0-" from serve http or webdav clients, was read as a ranged read, which can't check the file's signed block list. It is now read as a full read. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1287 lines
38 KiB
Go
1287 lines
38 KiB
Go
// Package protondrive implements the Proton Drive backend.
|
|
//
|
|
// The rclone-facing Fs and Object live in this file; the files beside
|
|
// it are a client of the Proton Drive API which follows Proton's Drive
|
|
// SDK, last checked against its tag js/v0.23.0. This file contains no
|
|
// cryptography and no API routes, and the client knows nothing of
|
|
// fs.Fs or fs.Object.
|
|
package protondrive
|
|
|
|
import (
|
|
"context"
|
|
"encoding/base64"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"path"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/pquerna/otp/totp"
|
|
"github.com/rclone/rclone/backend/protondrive/api"
|
|
"github.com/rclone/rclone/fs"
|
|
"github.com/rclone/rclone/fs/config"
|
|
"github.com/rclone/rclone/fs/config/configmap"
|
|
"github.com/rclone/rclone/fs/config/configstruct"
|
|
"github.com/rclone/rclone/fs/config/obscure"
|
|
"github.com/rclone/rclone/fs/fserrors"
|
|
"github.com/rclone/rclone/fs/fshttp"
|
|
"github.com/rclone/rclone/fs/hash"
|
|
"github.com/rclone/rclone/fs/list"
|
|
"github.com/rclone/rclone/lib/dircache"
|
|
"github.com/rclone/rclone/lib/encoder"
|
|
"github.com/rclone/rclone/lib/random"
|
|
)
|
|
|
|
const (
|
|
clientUIDKey = "client_uid"
|
|
clientAccessTokenKey = "client_access_token"
|
|
clientRefreshTokenKey = "client_refresh_token"
|
|
clientSaltedKeyPassKey = "client_salted_key_pass"
|
|
draftClientUIDKey = "draft_client_uid"
|
|
|
|
// defaultEndpoint is the Proton Drive API.
|
|
defaultEndpoint = "https://drive-api.proton.me"
|
|
|
|
// thirdPartyNotice is the statement Proton requires of apps which
|
|
// sign in to it.
|
|
thirdPartyNotice = "rclone is a third-party application not officially supported by Proton."
|
|
|
|
// forkPollInterval and forkPollTimeout pace waiting for a browser
|
|
// sign-in.
|
|
forkPollInterval = 3 * time.Second
|
|
forkPollTimeout = 10 * time.Minute
|
|
)
|
|
|
|
var (
|
|
errCanNotPurgeRootDirectory = errors.New("can't purge root directory")
|
|
errCanNotRemoveRootDirectory = errors.New("can't remove root directory")
|
|
|
|
// errNeedTwoFA is returned by the second factor callback of a
|
|
// password sign-in in Config which has no code yet.
|
|
errNeedTwoFA = errors.New("two-factor authentication code needed")
|
|
)
|
|
|
|
// Register with Fs
|
|
func init() {
|
|
fs.Register(&fs.RegInfo{
|
|
Name: "protondrive",
|
|
Description: "Proton Drive",
|
|
NewFs: NewFs,
|
|
Config: Config,
|
|
Options: []fs.Option{{
|
|
Name: "username",
|
|
Help: `The username of your Proton account.
|
|
|
|
Only needed to sign in with a password. Signing in with a web browser,
|
|
which "rclone config" offers, needs neither username nor password.`,
|
|
}, {
|
|
Name: "password",
|
|
Help: `The password of your Proton account.
|
|
|
|
Only needed to sign in with a password.`,
|
|
IsPassword: true,
|
|
}, {
|
|
Name: "mailbox_password",
|
|
Help: `The mailbox password of your two-password Proton account.
|
|
|
|
For more information regarding the mailbox password, please check the
|
|
following official knowledge base article:
|
|
https://proton.me/support/the-difference-between-the-mailbox-password-and-login-password
|
|
`,
|
|
IsPassword: true,
|
|
Advanced: true,
|
|
}, {
|
|
Name: "2fa",
|
|
Help: `The 2FA code
|
|
|
|
The value can also be provided with --protondrive-2fa=000000
|
|
|
|
The 2FA code of your proton drive account if the account is set up with
|
|
two-factor authentication`,
|
|
Required: false,
|
|
}, {
|
|
Name: "otp_secret_key",
|
|
Help: `The OTP secret key
|
|
|
|
The value can also be provided with --protondrive-otp-secret-key=ABCDEFGHIJKLMNOPQRSTUVWXYZ234567
|
|
|
|
The OTP secret key of your proton drive account if the account is set up with
|
|
two-factor authentication`,
|
|
Required: false,
|
|
Sensitive: true,
|
|
IsPassword: true,
|
|
}, {
|
|
Name: clientUIDKey,
|
|
Help: "Client uid key (internal use only)",
|
|
Required: false,
|
|
Advanced: true,
|
|
Sensitive: true,
|
|
Hide: fs.OptionHideBoth,
|
|
}, {
|
|
Name: clientAccessTokenKey,
|
|
Help: "Client access token key (internal use only)",
|
|
Required: false,
|
|
Advanced: true,
|
|
Sensitive: true,
|
|
Hide: fs.OptionHideBoth,
|
|
}, {
|
|
Name: clientRefreshTokenKey,
|
|
Help: "Client refresh token key (internal use only)",
|
|
Required: false,
|
|
Advanced: true,
|
|
Sensitive: true,
|
|
Hide: fs.OptionHideBoth,
|
|
}, {
|
|
Name: clientSaltedKeyPassKey,
|
|
Help: "Client salted key pass key (internal use only)",
|
|
Required: false,
|
|
Advanced: true,
|
|
Sensitive: true,
|
|
Hide: fs.OptionHideBoth,
|
|
}, {
|
|
Name: config.ConfigEncoding,
|
|
Help: config.ConfigEncodingHelp,
|
|
Advanced: true,
|
|
Default: (encoder.Base |
|
|
encoder.EncodeInvalidUtf8 |
|
|
encoder.EncodeLeftSpace |
|
|
encoder.EncodeRightSpace),
|
|
}, {
|
|
Name: "original_file_size",
|
|
Help: `Return the file size before encryption
|
|
|
|
The size of the encrypted file will be different from (bigger than) the
|
|
original file size. Unless there is a reason to return the file size
|
|
after encryption is performed, otherwise, set this option to true, as
|
|
features like Open() which will need to be supplied with original content
|
|
size, will fail to operate properly`,
|
|
Advanced: true,
|
|
Default: true,
|
|
}, {
|
|
Name: "app_version",
|
|
Help: `The app version string
|
|
|
|
The app version string identifies the client to Proton with every API
|
|
request. If it is left empty, rclone derives the value Proton asks of it
|
|
from its own version. Leave it empty: Proton may block a client which
|
|
sends a wrong or someone else's app version.`,
|
|
Advanced: true,
|
|
}, {
|
|
Name: "replace_existing_draft",
|
|
Help: `Replace a draft another client left when uploading
|
|
|
|
When an upload is cancelled or fails, it may leave a draft behind, and
|
|
another upload of the same file to the same place sees a conflict. Drafts
|
|
this remote left are always replaced.
|
|
|
|
If this is set, a draft left by another client is replaced too and the
|
|
upload goes ahead. If another client is uploading the same file at the
|
|
same time, its upload fails.
|
|
|
|
If this is not set, such an upload fails with an error saying another
|
|
client is uploading the file.`,
|
|
Advanced: true,
|
|
Default: false,
|
|
}, {
|
|
Name: "enable_caching",
|
|
Help: `Caches the files and folders metadata to reduce API calls
|
|
|
|
Notice: If you are mounting ProtonDrive as a VFS, please disable this feature,
|
|
as the current implementation doesn't update or clear the cache when there are
|
|
external changes.
|
|
|
|
The cache holds decrypted file and folder metadata in memory, which saves
|
|
API calls and decryption. Changes made by other clients are not seen while
|
|
it holds an entry, so if other clients change the same files at the same
|
|
time, rclone may act on out of date metadata.`,
|
|
Advanced: true,
|
|
Default: true,
|
|
}, {
|
|
Name: "upload_concurrency",
|
|
Help: `The number of blocks of one file uploaded at once
|
|
|
|
Files are uploaded in blocks of 4 MiB, each held in memory while it is
|
|
uploaded. Values above 5, Proton's limit, are lowered to 5.`,
|
|
Advanced: true,
|
|
Default: defaultUploadConcurrency,
|
|
}, {
|
|
Name: "ignore_signature_errors",
|
|
Help: `Read files whose signatures can't be verified
|
|
|
|
Proton signs file content and keys. By default a file whose signature
|
|
doesn't verify can't be read. If this is set, rclone logs an error and
|
|
reads it anyway, which may be needed for files uploaded by old or
|
|
third-party clients.`,
|
|
Advanced: true,
|
|
Default: false,
|
|
}, {
|
|
Name: draftClientUIDKey,
|
|
Help: "Identifies the drafts of this remote (internal use only)",
|
|
Advanced: true,
|
|
Sensitive: true,
|
|
Hide: fs.OptionHideBoth,
|
|
}, {
|
|
Name: "endpoint",
|
|
Help: "The Proton Drive API endpoint (for tests only)",
|
|
Advanced: true,
|
|
Default: defaultEndpoint,
|
|
Hide: fs.OptionHideBoth,
|
|
}},
|
|
})
|
|
}
|
|
|
|
// Options defines the configuration for this backend
|
|
type Options struct {
|
|
Username string `config:"username"`
|
|
Password string `config:"password"`
|
|
MailboxPassword string `config:"mailbox_password"`
|
|
TwoFA string `config:"2fa"`
|
|
OtpSecretKey string `config:"otp_secret_key"`
|
|
|
|
// advanced
|
|
Enc encoder.MultiEncoder `config:"encoding"`
|
|
ReportOriginalSize bool `config:"original_file_size"`
|
|
AppVersion string `config:"app_version"`
|
|
ReplaceExistingDraft bool `config:"replace_existing_draft"`
|
|
EnableCaching bool `config:"enable_caching"`
|
|
UploadConcurrency int `config:"upload_concurrency"`
|
|
IgnoreSignatureErrors bool `config:"ignore_signature_errors"`
|
|
DraftClientUID string `config:"draft_client_uid"`
|
|
Endpoint string `config:"endpoint"`
|
|
}
|
|
|
|
// Fs represents a remote proton drive
|
|
type Fs struct {
|
|
name string // name of this remote
|
|
root string // the path we are working on
|
|
opt Options // parsed config options
|
|
features *fs.Features // optional features
|
|
c *client // Proton Drive API client
|
|
dirCache *dircache.DirCache // map of directory path to folder ID
|
|
}
|
|
|
|
// Object describes a file
|
|
type Object struct {
|
|
fs *Fs // what this object is part of
|
|
remote string // the remote path
|
|
n *node // the file; nil until uploaded
|
|
}
|
|
|
|
// configStore keeps the credentials of a session in the config of a
|
|
// remote.
|
|
//
|
|
// The key password is kept base64 encoded, as earlier versions of the
|
|
// backend kept it.
|
|
type configStore struct {
|
|
mu sync.Mutex
|
|
m configmap.Mapper
|
|
|
|
// saved is what Save last wrote, and shadowed what the mapper held
|
|
// just before. A value the mapper still reads as shadowed is hidden
|
|
// by one which takes precedence over the config file, as from the
|
|
// environment, so Load returns the saved value instead.
|
|
saved *credentials
|
|
shadowed credentials
|
|
}
|
|
|
|
// Load returns the credentials currently in the config. A key password
|
|
// which can't be decoded is returned empty.
|
|
func (s *configStore) Load() credentials {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
creds := s.read()
|
|
if s.saved == nil {
|
|
return creds
|
|
}
|
|
for _, f := range []struct{ read, shadowed, saved *string }{
|
|
{&creds.UID, &s.shadowed.UID, &s.saved.UID},
|
|
{&creds.AccessToken, &s.shadowed.AccessToken, &s.saved.AccessToken},
|
|
{&creds.RefreshToken, &s.shadowed.RefreshToken, &s.saved.RefreshToken},
|
|
{&creds.KeyPassword, &s.shadowed.KeyPassword, &s.saved.KeyPassword},
|
|
} {
|
|
if *f.read == *f.shadowed {
|
|
*f.read = *f.saved
|
|
}
|
|
}
|
|
return creds
|
|
}
|
|
|
|
// read returns the credentials in the mapper.
|
|
func (s *configStore) read() credentials {
|
|
get := func(key string) string {
|
|
v, _ := s.m.Get(key)
|
|
return v
|
|
}
|
|
creds := credentials{
|
|
UID: get(clientUIDKey),
|
|
AccessToken: get(clientAccessTokenKey),
|
|
RefreshToken: get(clientRefreshTokenKey),
|
|
}
|
|
if keyPass, err := base64.StdEncoding.DecodeString(get(clientSaltedKeyPassKey)); err == nil {
|
|
creds.KeyPassword = string(keyPass)
|
|
}
|
|
return creds
|
|
}
|
|
|
|
// Save writes c to the config.
|
|
func (s *configStore) Save(c credentials) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.shadowed = s.read()
|
|
s.m.Set(clientUIDKey, c.UID)
|
|
s.m.Set(clientAccessTokenKey, c.AccessToken)
|
|
s.m.Set(clientRefreshTokenKey, c.RefreshToken)
|
|
s.m.Set(clientSaltedKeyPassKey, base64.StdEncoding.EncodeToString([]byte(c.KeyPassword)))
|
|
s.saved = &c
|
|
}
|
|
|
|
// errorOp is the kind of operation an error is translated for.
|
|
type errorOp int
|
|
|
|
const (
|
|
opObject errorOp = iota // an operation on a file
|
|
opDir // an operation on a directory
|
|
opMkdir // making a directory
|
|
opMove // moving a file
|
|
opCopy // copying a file
|
|
opDirMove // moving a directory
|
|
)
|
|
|
|
// translateError returns err from the client as the error rclone
|
|
// expects of the operation op.
|
|
func translateError(err error, op errorOp) error {
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
switch {
|
|
case errors.Is(err, errIntegrity), errors.Is(err, errUploadMismatch):
|
|
return fserrors.NoRetryError(err)
|
|
case errors.Is(err, errUploadSuperseded):
|
|
// The upload landed; doing it again would only replace the
|
|
// other client's newer revision.
|
|
return fserrors.NoRetryError(err)
|
|
case errors.Is(err, errUploadOutcomeUnknown):
|
|
// An immediate retry could upload a revision which already
|
|
// committed. A later pass of a sync reads the file first, so
|
|
// may still retry.
|
|
return fserrors.NoLowLevelRetryError(err)
|
|
}
|
|
code := apiErrorCode(err)
|
|
switch {
|
|
case errors.Is(err, errNotFound) || code == api.CodeNotExists:
|
|
if op == opDir || op == opDirMove {
|
|
return fs.ErrorDirNotFound
|
|
}
|
|
return fs.ErrorObjectNotFound
|
|
case errors.Is(err, errExists):
|
|
switch op {
|
|
case opMkdir:
|
|
return nil
|
|
case opMove:
|
|
return fs.ErrorCantMove
|
|
case opCopy:
|
|
return fs.ErrorCantCopy
|
|
case opDirMove:
|
|
return fs.ErrorDirExists
|
|
}
|
|
return err
|
|
}
|
|
switch code {
|
|
case api.CodeInsufficientQuota, api.CodeInsufficientSpace, api.CodeMaxFileSizeForFreeUser,
|
|
api.CodeMaxPublicEditModeForFreeUser, api.CodeTooManyChildren, api.CodeNestingTooDeep:
|
|
return fserrors.NoRetryError(err)
|
|
case api.CodeInvalidRequirements, api.CodeAppVersionBad:
|
|
return fserrors.FatalError(fmt.Errorf("this version of rclone is no longer accepted by Proton: upgrade rclone: %w", err))
|
|
}
|
|
return err
|
|
}
|
|
|
|
// ------------------------------------------------------------
|
|
|
|
// Name of the remote (as passed into NewFs)
|
|
func (f *Fs) Name() string {
|
|
return f.name
|
|
}
|
|
|
|
// Root of the remote (as passed into NewFs)
|
|
func (f *Fs) Root() string {
|
|
return f.root
|
|
}
|
|
|
|
// String converts this Fs to a string
|
|
func (f *Fs) String() string {
|
|
return fmt.Sprintf("Proton Drive root '%s'", f.root)
|
|
}
|
|
|
|
// Features returns the optional features of this Fs
|
|
func (f *Fs) Features() *fs.Features {
|
|
return f.features
|
|
}
|
|
|
|
// parseOptions reads the options from m, revealing the obscured ones.
|
|
func parseOptions(m configmap.Mapper) (*Options, error) {
|
|
opt := new(Options)
|
|
if err := configstruct.Set(m, opt); err != nil {
|
|
return nil, err
|
|
}
|
|
for _, p := range []struct {
|
|
what string
|
|
value *string
|
|
}{
|
|
{"password", &opt.Password},
|
|
{"mailbox password", &opt.MailboxPassword},
|
|
{"OTP secret key", &opt.OtpSecretKey},
|
|
} {
|
|
if *p.value == "" {
|
|
continue
|
|
}
|
|
revealed, err := obscure.Reveal(*p.value)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("couldn't decrypt %s: %w", p.what, err)
|
|
}
|
|
*p.value = revealed
|
|
}
|
|
return opt, nil
|
|
}
|
|
|
|
// newConfigSession returns a session keeping its credentials in m.
|
|
func newConfigSession(ctx context.Context, m configmap.Mapper, opt *Options) *session {
|
|
return newStoreSession(ctx, opt, &configStore{m: m})
|
|
}
|
|
|
|
// newStoreSession returns a session keeping its credentials in store.
|
|
func newStoreSession(ctx context.Context, opt *Options, store credentialStore) *session {
|
|
endpoint := opt.Endpoint
|
|
if endpoint == "" {
|
|
endpoint = defaultEndpoint
|
|
}
|
|
appVersion := opt.AppVersion
|
|
if appVersion == "" {
|
|
appVersion = appVersionFromRcloneVersion(fs.Version)
|
|
}
|
|
return newSession(fshttp.NewClient(ctx), strings.TrimSuffix(endpoint, "/"), appVersion, store)
|
|
}
|
|
|
|
// signOut ends the session old, if it has one, on the server. It is
|
|
// best effort: a failure is only logged.
|
|
func signOut(ctx context.Context, opt *Options, old credentials) {
|
|
if old.UID == "" {
|
|
return
|
|
}
|
|
if err := newStoreSession(ctx, opt, &memoryStore{creds: old}).logout(ctx); err != nil {
|
|
fs.Debugf(nil, "protondrive: signing the previous session out failed: %v", err)
|
|
}
|
|
}
|
|
|
|
// passwordSignIn signs s in with the username and password of opt,
|
|
// taking a second factor from twoFA, else the 2fa option, else a code
|
|
// generated from the OTP secret key.
|
|
func passwordSignIn(ctx context.Context, s *session, opt *Options, twoFA string) error {
|
|
return s.loginSRP(ctx, opt.Username, opt.Password, opt.MailboxPassword, func() (string, error) {
|
|
switch {
|
|
case twoFA != "":
|
|
return twoFA, nil
|
|
case opt.TwoFA != "":
|
|
return opt.TwoFA, nil
|
|
case opt.OtpSecretKey != "":
|
|
// The code is checked against the server's clock.
|
|
now := s.serverTime()
|
|
if now.IsZero() {
|
|
now = time.Now()
|
|
}
|
|
code, err := totp.GenerateCode(opt.OtpSecretKey, now)
|
|
if err != nil {
|
|
return "", fmt.Errorf("couldn't generate 2FA code: %w", err)
|
|
}
|
|
return code, nil
|
|
}
|
|
return "", errNeedTwoFA
|
|
})
|
|
}
|
|
|
|
// connect returns a client for the saved session of s, signing in with
|
|
// the username and password of opt if there is no usable session.
|
|
func connect(ctx context.Context, name string, s *session, opt *Options) (*client, error) {
|
|
copt := clientOptions{
|
|
UploadConcurrency: opt.UploadConcurrency,
|
|
ReplaceExistingDraft: opt.ReplaceExistingDraft,
|
|
EnableCaching: opt.EnableCaching,
|
|
IgnoreSignatureErrors: opt.IgnoreSignatureErrors,
|
|
DraftClientUID: opt.DraftClientUID,
|
|
}
|
|
canSignIn := opt.Username != "" && opt.Password != ""
|
|
reconnect := fmt.Sprintf(`run "rclone config reconnect %s:"`, name)
|
|
s.reconnect = reconnect
|
|
saved := s.current()
|
|
if saved.UID != "" && saved.AccessToken != "" && saved.RefreshToken != "" && saved.KeyPassword != "" {
|
|
c, err := newClient(ctx, s, copt)
|
|
switch {
|
|
case err == nil:
|
|
return c, nil
|
|
case !errors.Is(err, errSessionExpired):
|
|
return nil, err
|
|
case !canSignIn:
|
|
// err says how to reconnect.
|
|
return nil, fserrors.FatalError(fmt.Errorf("the saved session can't be used: %w", err))
|
|
}
|
|
fs.Debugf(nil, "protondrive: the saved session has expired")
|
|
} else if !canSignIn {
|
|
return nil, fserrors.FatalError(fmt.Errorf("not signed in and no username and password set: %s", reconnect))
|
|
}
|
|
fs.Debugf(nil, "protondrive: signing in with username and password")
|
|
if err := passwordSignIn(ctx, s, opt, ""); err != nil {
|
|
switch {
|
|
case errors.Is(err, errNeedTwoFA):
|
|
return nil, fmt.Errorf("the account needs a two-factor authentication code: set otp_secret_key or %s", reconnect)
|
|
case errors.Is(err, errCaptcha):
|
|
return nil, fserrors.FatalError(fmt.Errorf("%w: %s and choose browser sign-in", err, reconnect))
|
|
}
|
|
return nil, err
|
|
}
|
|
return newClient(ctx, s, copt)
|
|
}
|
|
|
|
// Config signs a remote in, with a web browser or a password.
|
|
func Config(ctx context.Context, name string, m configmap.Mapper, in fs.ConfigIn) (*fs.ConfigOut, error) {
|
|
return configure(ctx, name, m, in, signInOptions{
|
|
showURL: showSignInURL,
|
|
pollInterval: forkPollInterval,
|
|
pollTimeout: forkPollTimeout,
|
|
})
|
|
}
|
|
|
|
// signInOptions configure a browser sign-in.
|
|
type signInOptions struct {
|
|
showURL func(signInURL string) // shows the sign-in page to the user
|
|
pollInterval time.Duration // how often to check whether the user signed in
|
|
pollTimeout time.Duration // how long to wait for the user to sign in
|
|
}
|
|
|
|
// showSignInURL shows the user the browser sign-in page signInURL.
|
|
//
|
|
// It is printed rather than logged as it holds a secret.
|
|
func showSignInURL(signInURL string) {
|
|
fmt.Printf("Open this link in a web browser, on any device, and sign in to Proton:\n\n%s\n\nWaiting for the sign-in to complete...\n", signInURL)
|
|
}
|
|
|
|
// configure runs the Config state machine, with signIn configuring a
|
|
// browser sign-in.
|
|
func configure(ctx context.Context, name string, m configmap.Mapper, in fs.ConfigIn, signIn signInOptions) (*fs.ConfigOut, error) {
|
|
opt, err := parseOptions(m)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
hasPassword := opt.Username != "" && opt.Password != ""
|
|
store := &configStore{m: m}
|
|
switch in.State {
|
|
case "":
|
|
if saved := store.Load(); saved.UID != "" && saved.AccessToken != "" && saved.RefreshToken != "" && saved.KeyPassword != "" {
|
|
return fs.ConfigConfirm("reauth", false, "config_refresh_token", "Already signed in - sign in again?")
|
|
}
|
|
return fs.ConfigGoto("method")
|
|
case "reauth":
|
|
if in.Result != "true" {
|
|
return nil, nil
|
|
}
|
|
return fs.ConfigGoto("method")
|
|
case "method":
|
|
return fs.ConfigConfirm("choose", !hasPassword, "config_browser_sign_in", `Sign in with a web browser?
|
|
|
|
`+thirdPartyNotice+`
|
|
|
|
Choose yes to sign in on Proton's sign-in page, on any device; rclone
|
|
never sees your password. Choose no to sign in with the username and
|
|
password set above.`)
|
|
case "choose":
|
|
if in.Result == "true" {
|
|
return fs.ConfigGoto("browser")
|
|
}
|
|
return fs.ConfigGoto("password")
|
|
case "browser":
|
|
old := store.Load()
|
|
s := newStoreSession(ctx, opt, store)
|
|
fork, err := s.forkStart(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
signIn.showURL(fork.URL)
|
|
if err := s.forkPoll(ctx, fork, signIn.pollInterval, signIn.pollTimeout); err != nil {
|
|
return nil, err
|
|
}
|
|
signOut(ctx, opt, old)
|
|
return nil, nil
|
|
case "password", "password_2fa":
|
|
if !hasPassword {
|
|
return fs.ConfigError("", "Password sign-in needs the username and password options set.")
|
|
}
|
|
twoFA := ""
|
|
if in.State == "password_2fa" {
|
|
twoFA = strings.TrimSpace(in.Result)
|
|
}
|
|
old := store.Load()
|
|
s := newStoreSession(ctx, opt, store)
|
|
err := passwordSignIn(ctx, s, opt, twoFA)
|
|
if errors.Is(err, errNeedTwoFA) {
|
|
return fs.ConfigInput("password_2fa", "config_2fa", "Two-factor authentication code")
|
|
}
|
|
if errors.Is(err, errCaptcha) {
|
|
return fs.ConfigError("method", "Proton asks for a CAPTCHA, which password sign-in can't solve: sign in with a web browser instead.")
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
signOut(ctx, opt, old)
|
|
return nil, nil
|
|
}
|
|
return nil, fmt.Errorf("unknown state %q", in.State)
|
|
}
|
|
|
|
// NewFs constructs an Fs from the path, container:path
|
|
func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {
|
|
opt, err := parseOptions(m)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if opt.UploadConcurrency > maxUploadConcurrency {
|
|
fs.Logf(nil, "protondrive: upload_concurrency %d is more than Proton allows: using %d", opt.UploadConcurrency, maxUploadConcurrency)
|
|
opt.UploadConcurrency = maxUploadConcurrency
|
|
}
|
|
if opt.DraftClientUID == "" {
|
|
// Saved before any upload, so drafts this remote leaves can be
|
|
// told apart from other clients' by later runs.
|
|
opt.DraftClientUID = random.String(32)
|
|
m.Set(draftClientUIDKey, opt.DraftClientUID)
|
|
}
|
|
|
|
c, err := connect(ctx, name, newConfigSession(ctx, m, opt), opt)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
root = strings.Trim(root, "/")
|
|
f := &Fs{
|
|
name: name,
|
|
root: root,
|
|
opt: *opt,
|
|
c: c,
|
|
}
|
|
f.features = (&fs.Features{
|
|
ReadMimeType: true,
|
|
CanHaveEmptyDirectories: true,
|
|
}).Fill(ctx, f)
|
|
|
|
f.dirCache = dircache.New(root, c.rootID(), f)
|
|
err = f.dirCache.FindRoot(ctx, false)
|
|
if err != nil {
|
|
if err != fs.ErrorDirNotFound {
|
|
c.close()
|
|
return nil, fmt.Errorf("couldn't find the root: %w", err)
|
|
}
|
|
// Assume it is a file
|
|
newRoot, remote := dircache.SplitPath(root)
|
|
tempF := *f
|
|
tempF.dirCache = dircache.New(newRoot, c.rootID(), &tempF)
|
|
tempF.root = newRoot
|
|
// Make new Fs which is the parent
|
|
err = tempF.dirCache.FindRoot(ctx, false)
|
|
if err != nil {
|
|
// No root so return old f
|
|
return f, nil
|
|
}
|
|
_, err := tempF.NewObject(ctx, remote)
|
|
if err != nil {
|
|
if err == fs.ErrorObjectNotFound {
|
|
// File doesn't exist so return old f
|
|
return f, nil
|
|
}
|
|
c.close()
|
|
return nil, err
|
|
}
|
|
f.features.Fill(ctx, &tempF)
|
|
// Update the old f here instead of returning tempF, since
|
|
// `features` were already filled with functions having *f as a receiver.
|
|
// See https://github.com/rclone/rclone/issues/2182
|
|
f.dirCache = tempF.dirCache
|
|
f.root = tempF.root
|
|
// return an error with an fs which points to the parent
|
|
return f, fs.ErrorIsFile
|
|
}
|
|
return f, nil
|
|
}
|
|
|
|
// newObjectWithNode returns an Object at remote for the file n.
|
|
func (f *Fs) newObjectWithNode(remote string, n *node) *Object {
|
|
return &Object{fs: f, remote: remote, n: n}
|
|
}
|
|
|
|
// NewObject finds the Object at remote. If it can't be found
|
|
// it returns the error fs.ErrorObjectNotFound.
|
|
func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) {
|
|
leaf, directoryID, err := f.dirCache.FindPath(ctx, remote, false)
|
|
if err != nil {
|
|
if err == fs.ErrorDirNotFound {
|
|
return nil, fs.ErrorObjectNotFound
|
|
}
|
|
return nil, err
|
|
}
|
|
n, err := f.c.findChild(ctx, directoryID, f.opt.Enc.FromStandardName(leaf))
|
|
if err != nil {
|
|
return nil, translateError(err, opObject)
|
|
}
|
|
if n.IsFolder {
|
|
return nil, fs.ErrorIsDir
|
|
}
|
|
return f.newObjectWithNode(remote, n), nil
|
|
}
|
|
|
|
// FindLeaf finds a directory of name leaf in the folder with ID pathID
|
|
func (f *Fs) FindLeaf(ctx context.Context, pathID, leaf string) (pathIDOut string, found bool, err error) {
|
|
n, err := f.c.findChild(ctx, pathID, f.opt.Enc.FromStandardName(leaf))
|
|
if errors.Is(err, errNotFound) {
|
|
return "", false, nil
|
|
}
|
|
if err != nil {
|
|
return "", false, translateError(err, opDir)
|
|
}
|
|
if !n.IsFolder {
|
|
return "", false, nil
|
|
}
|
|
return n.ID, true, nil
|
|
}
|
|
|
|
// CreateDir makes a directory with pathID as parent and name leaf
|
|
func (f *Fs) CreateDir(ctx context.Context, pathID, leaf string) (newID string, err error) {
|
|
name := f.opt.Enc.FromStandardName(leaf)
|
|
n, err := f.c.createFolder(ctx, pathID, name, time.Now())
|
|
if errors.Is(err, errExists) {
|
|
// Another client, or a call whose response was lost, may have
|
|
// made the folder.
|
|
if existing, findErr := f.c.findChild(ctx, pathID, name); findErr == nil && existing.IsFolder {
|
|
return existing.ID, nil
|
|
}
|
|
return "", err
|
|
}
|
|
if err != nil {
|
|
return "", translateError(err, opDir)
|
|
}
|
|
return n.ID, nil
|
|
}
|
|
|
|
// List the objects and directories in dir into entries. The
|
|
// entries can be returned in any order but should be for a
|
|
// complete directory.
|
|
//
|
|
// dir should be "" to list the root, and should not have
|
|
// trailing slashes.
|
|
//
|
|
// This should return ErrDirNotFound if the directory isn't
|
|
// found.
|
|
func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) {
|
|
return list.WithListP(ctx, dir, f)
|
|
}
|
|
|
|
// ListP lists the objects and directories of the Fs starting
|
|
// from dir non recursively into out.
|
|
//
|
|
// dir should be "" to start from the root, and should not
|
|
// have trailing slashes.
|
|
//
|
|
// This should return ErrDirNotFound if the directory isn't
|
|
// found.
|
|
//
|
|
// It should call callback for each tranche of entries read.
|
|
// These need not be returned in any particular order. If
|
|
// callback returns an error then the listing will stop
|
|
// immediately.
|
|
func (f *Fs) ListP(ctx context.Context, dir string, callback fs.ListRCallback) error {
|
|
list := list.NewHelper(callback)
|
|
directoryID, err := f.dirCache.FindDir(ctx, dir, false)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
err = f.c.listChildren(ctx, directoryID, func(nodes []*node) error {
|
|
for _, n := range nodes {
|
|
remote := path.Join(dir, f.opt.Enc.ToStandardName(n.Name))
|
|
var entry fs.DirEntry
|
|
if n.IsFolder {
|
|
f.dirCache.Put(remote, n.ID)
|
|
entry = fs.NewDir(remote, n.modTime()).SetID(n.ID)
|
|
} else {
|
|
entry = f.newObjectWithNode(remote, n)
|
|
}
|
|
if err := list.Add(entry); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return translateError(err, opDir)
|
|
}
|
|
return list.Flush()
|
|
}
|
|
|
|
// Put the object
|
|
//
|
|
// Copy the reader in to the new object which is returned.
|
|
//
|
|
// The new object may have been created if an error is returned
|
|
func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
|
|
existing, err := f.NewObject(ctx, src.Remote())
|
|
switch err {
|
|
case nil:
|
|
return existing, existing.Update(ctx, in, src, options...)
|
|
case fs.ErrorObjectNotFound:
|
|
o := &Object{fs: f, remote: src.Remote()}
|
|
if err := o.Update(ctx, in, src, options...); err != nil {
|
|
return nil, err
|
|
}
|
|
return o, nil
|
|
default:
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
// PutStream uploads to the remote path with the modTime given of indeterminate size
|
|
func (f *Fs) PutStream(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
|
|
return f.Put(ctx, in, src, options...)
|
|
}
|
|
|
|
// Mkdir makes the directory (container, bucket)
|
|
//
|
|
// Shouldn't return an error if it already exists
|
|
func (f *Fs) Mkdir(ctx context.Context, dir string) error {
|
|
_, err := f.dirCache.FindDir(ctx, dir, true)
|
|
return err
|
|
}
|
|
|
|
// Rmdir deletes the directory dir by moving it to the trash
|
|
//
|
|
// Returns an error if it isn't empty
|
|
func (f *Fs) Rmdir(ctx context.Context, dir string) error {
|
|
directoryID, err := f.dirCache.FindDir(ctx, dir, false)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if directoryID == f.c.rootID() {
|
|
return errCanNotRemoveRootDirectory
|
|
}
|
|
// Asked of the server, as a listing leaves out children rclone
|
|
// can't read, which trashing the folder would trash too.
|
|
nonEmpty, err := f.c.hasChildren(ctx, directoryID)
|
|
if err != nil {
|
|
return translateError(err, opDir)
|
|
}
|
|
if nonEmpty {
|
|
return fs.ErrorDirectoryNotEmpty
|
|
}
|
|
if err := f.c.trash(ctx, directoryID); err != nil {
|
|
return translateError(err, opDir)
|
|
}
|
|
f.dirCache.FlushDir(dir)
|
|
return nil
|
|
}
|
|
|
|
// Precision of the ModTimes in this Fs
|
|
func (f *Fs) Precision() time.Duration {
|
|
return time.Second
|
|
}
|
|
|
|
// Copy src to this remote using server-side copy operations.
|
|
//
|
|
// This is stored with the remote path given.
|
|
//
|
|
// It returns the destination Object and a possible error.
|
|
//
|
|
// Will only be called if src.Fs().Name() == f.Name()
|
|
//
|
|
// If it isn't possible then return fs.ErrorCantCopy
|
|
func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object, error) {
|
|
srcObj, ok := src.(*Object)
|
|
if !ok || srcObj.n == nil {
|
|
fs.Debugf(src, "Can't copy - not same remote type")
|
|
return nil, fs.ErrorCantCopy
|
|
}
|
|
n, err := f.c.activeNode(ctx, srcObj.n.ID)
|
|
if err != nil {
|
|
return nil, translateError(err, opObject)
|
|
}
|
|
leaf, directoryID, err := f.dirCache.FindPath(ctx, remote, true)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
copied, err := f.c.copyNode(ctx, n, directoryID, f.opt.Enc.FromStandardName(leaf))
|
|
if err != nil {
|
|
return nil, translateError(err, opCopy)
|
|
}
|
|
return f.newObjectWithNode(remote, copied), nil
|
|
}
|
|
|
|
// Purge deletes all the files and the directory dir by moving it to
|
|
// the trash
|
|
//
|
|
// Returns an error if it doesn't exist
|
|
func (f *Fs) Purge(ctx context.Context, dir string) error {
|
|
if path.Join(f.root, dir) == "" {
|
|
return errCanNotPurgeRootDirectory
|
|
}
|
|
directoryID, err := f.dirCache.FindDir(ctx, dir, false)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if directoryID == f.c.rootID() {
|
|
return errCanNotPurgeRootDirectory
|
|
}
|
|
if err := f.c.trash(ctx, directoryID); err != nil {
|
|
return translateError(err, opDir)
|
|
}
|
|
f.dirCache.FlushDir(dir)
|
|
return nil
|
|
}
|
|
|
|
// CleanUp empties the trash
|
|
func (f *Fs) CleanUp(ctx context.Context) error {
|
|
return translateError(f.c.emptyTrash(ctx), opDir)
|
|
}
|
|
|
|
// Move src to this remote using server-side move operations.
|
|
//
|
|
// This is stored with the remote path given.
|
|
//
|
|
// It returns the destination Object and a possible error.
|
|
//
|
|
// Will only be called if src.Fs().Name() == f.Name()
|
|
//
|
|
// If it isn't possible then return fs.ErrorCantMove
|
|
func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object, error) {
|
|
srcObj, ok := src.(*Object)
|
|
if !ok || srcObj.n == nil {
|
|
fs.Debugf(src, "Can't move - not same remote type")
|
|
return nil, fs.ErrorCantMove
|
|
}
|
|
n, err := f.c.activeNode(ctx, srcObj.n.ID)
|
|
if err != nil {
|
|
return nil, translateError(err, opObject)
|
|
}
|
|
leaf, directoryID, err := f.dirCache.FindPath(ctx, remote, true)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := f.moveNode(ctx, n, directoryID, f.opt.Enc.FromStandardName(leaf)); err != nil {
|
|
return nil, translateError(err, opMove)
|
|
}
|
|
srcObj.fs.forget(f, n.ID, n.ParentID, directoryID)
|
|
moved, err := f.c.getNode(ctx, n.ID)
|
|
if err != nil {
|
|
return nil, translateError(err, opObject)
|
|
}
|
|
return f.newObjectWithNode(remote, moved), nil
|
|
}
|
|
|
|
// forget drops node id and the listings of parentIDs from the cache of
|
|
// f after dst changed them, unless dst shares f's client, which then
|
|
// already has.
|
|
func (f *Fs) forget(dst *Fs, id string, parentIDs ...string) {
|
|
if f.c != dst.c {
|
|
f.c.forget(id, parentIDs...)
|
|
}
|
|
}
|
|
|
|
// moveNode moves n into folder parentID as name, renaming it if it is
|
|
// already in that folder.
|
|
func (f *Fs) moveNode(ctx context.Context, n *node, parentID, name string) error {
|
|
if n.ParentID != parentID {
|
|
return f.c.move(ctx, n, parentID, name)
|
|
}
|
|
if n.Name == name {
|
|
return nil
|
|
}
|
|
return f.c.rename(ctx, n, name)
|
|
}
|
|
|
|
// About gets quota information
|
|
func (f *Fs) About(ctx context.Context) (*fs.Usage, error) {
|
|
used, total, err := f.c.about(ctx)
|
|
if err != nil {
|
|
return nil, translateError(err, opDir)
|
|
}
|
|
free := max(total-used, 0)
|
|
return &fs.Usage{
|
|
Total: &total,
|
|
Used: &used,
|
|
Free: &free,
|
|
}, nil
|
|
}
|
|
|
|
// DirMove moves src, srcRemote to this remote at dstRemote
|
|
// using server-side move operations.
|
|
//
|
|
// Will only be called if src.Fs().Name() == f.Name()
|
|
//
|
|
// If it isn't possible then return fs.ErrorCantDirMove
|
|
//
|
|
// If destination exists then return fs.ErrorDirExists
|
|
func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string) error {
|
|
srcFs, ok := src.(*Fs)
|
|
if !ok {
|
|
fs.Debugf(srcFs, "Can't move directory - not same remote type")
|
|
return fs.ErrorCantDirMove
|
|
}
|
|
srcID, _, _, dstDirectoryID, dstLeaf, err := f.dirCache.DirMove(ctx, srcFs.dirCache, srcFs.root, srcRemote, f.root, dstRemote)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
n, err := f.c.activeNode(ctx, srcID)
|
|
if err != nil {
|
|
return translateError(err, opDirMove)
|
|
}
|
|
if err := f.moveNode(ctx, n, dstDirectoryID, f.opt.Enc.FromStandardName(dstLeaf)); err != nil {
|
|
return translateError(err, opDirMove)
|
|
}
|
|
srcFs.forget(f, n.ID, n.ParentID, dstDirectoryID)
|
|
srcFs.dirCache.FlushDir(srcRemote)
|
|
return nil
|
|
}
|
|
|
|
// Disconnect signs the session out and removes it from the config.
|
|
// Afterwards the Fs returns a "not signed in" error.
|
|
func (f *Fs) Disconnect(ctx context.Context) error {
|
|
err := f.c.s.logout(ctx)
|
|
f.c.cache.clear()
|
|
return err
|
|
}
|
|
|
|
// DirCacheFlush resets the directory cache - used in testing as an
|
|
// optional interface
|
|
func (f *Fs) DirCacheFlush() {
|
|
f.dirCache.ResetRoot()
|
|
f.c.cache.clear()
|
|
}
|
|
|
|
// Shutdown drops the caches of the Fs. The Fs stays usable, as rclone
|
|
// may still be using it.
|
|
func (f *Fs) Shutdown(ctx context.Context) error {
|
|
f.c.cache.clear()
|
|
return nil
|
|
}
|
|
|
|
// Hashes returns the supported hash types of the filesystem
|
|
func (f *Fs) Hashes() hash.Set {
|
|
return hash.Set(hash.SHA1)
|
|
}
|
|
|
|
// ------------------------------------------------------------
|
|
|
|
// Fs returns the parent Fs
|
|
func (o *Object) Fs() fs.Info {
|
|
return o.fs
|
|
}
|
|
|
|
// Return a string version
|
|
func (o *Object) String() string {
|
|
if o == nil {
|
|
return "<nil>"
|
|
}
|
|
return o.remote
|
|
}
|
|
|
|
// Remote returns the remote path
|
|
func (o *Object) Remote() string {
|
|
return o.remote
|
|
}
|
|
|
|
// Hash returns the SHA-1 of the object's content which its uploader
|
|
// recorded, or "" if it isn't known
|
|
func (o *Object) Hash(ctx context.Context, t hash.Type) (string, error) {
|
|
if t != hash.SHA1 {
|
|
return "", hash.ErrUnsupported
|
|
}
|
|
if o.n == nil {
|
|
return "", nil
|
|
}
|
|
return o.n.sha1(), nil
|
|
}
|
|
|
|
// Size returns the size of an object in bytes
|
|
func (o *Object) Size() int64 {
|
|
if o.n == nil {
|
|
return -1
|
|
}
|
|
return o.n.size(o.fs.opt.ReportOriginalSize)
|
|
}
|
|
|
|
// ModTime returns the modification time of the object
|
|
func (o *Object) ModTime(ctx context.Context) time.Time {
|
|
if o.n == nil {
|
|
return time.Time{}
|
|
}
|
|
return o.n.modTime()
|
|
}
|
|
|
|
// SetModTime is not supported: the modification time is part of the
|
|
// uploaded revision
|
|
func (o *Object) SetModTime(ctx context.Context, modTime time.Time) error {
|
|
return fs.ErrorCantSetModTime
|
|
}
|
|
|
|
// Storable returns a boolean showing whether this object storable
|
|
func (o *Object) Storable() bool {
|
|
return true
|
|
}
|
|
|
|
// Open opens the file for read. Call Close() on the returned io.ReadCloser
|
|
func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadCloser, error) {
|
|
if o.n == nil {
|
|
return nil, fs.ErrorObjectNotFound
|
|
}
|
|
// Ranges are of the content the reader serves, whatever size the
|
|
// object reports.
|
|
size, known := o.n.plaintextSize()
|
|
if !known && hasSuffixRange(options) {
|
|
var err error
|
|
if size, err = o.countContent(ctx); err != nil {
|
|
return nil, err
|
|
}
|
|
known = true
|
|
}
|
|
if known {
|
|
fs.FixRangeOption(options, size)
|
|
}
|
|
var offset, limit int64 = 0, -1
|
|
for _, option := range options {
|
|
switch x := option.(type) {
|
|
case *fs.SeekOption:
|
|
offset = x.Offset
|
|
case *fs.RangeOption:
|
|
offset, limit = x.Decode(size)
|
|
default:
|
|
if option.Mandatory() {
|
|
fs.Logf(o, "Unsupported mandatory option: %v", option)
|
|
}
|
|
}
|
|
}
|
|
if known && offset == 0 && limit >= size {
|
|
// The whole file, as a full read, so the manifest is checked.
|
|
limit = -1
|
|
}
|
|
rc, err := o.fs.c.open(ctx, o.n, offset, limit)
|
|
if err != nil {
|
|
return nil, translateError(err, opObject)
|
|
}
|
|
return rc, nil
|
|
}
|
|
|
|
// hasSuffixRange reports whether options ask for the end of the
|
|
// content, which needs its size.
|
|
func hasSuffixRange(options []fs.OpenOption) bool {
|
|
for _, option := range options {
|
|
if r, ok := option.(*fs.RangeOption); ok && r.Start < 0 {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// countContent returns the size of the content of a file whose
|
|
// extended attributes don't record it, by reading all of it.
|
|
func (o *Object) countContent(ctx context.Context) (int64, error) {
|
|
fs.Debugf(o, "reading the whole file to find its size")
|
|
rc, err := o.fs.c.open(ctx, o.n, 0, -1)
|
|
if err != nil {
|
|
return 0, translateError(err, opObject)
|
|
}
|
|
n, err := io.Copy(io.Discard, rc)
|
|
closeErr := rc.Close()
|
|
if err == nil {
|
|
err = closeErr
|
|
}
|
|
if err != nil {
|
|
return 0, translateError(err, opObject)
|
|
}
|
|
return n, nil
|
|
}
|
|
|
|
// Update the object with the contents of the io.Reader, modTime and size
|
|
//
|
|
// If the object exists, its content becomes a new revision of it.
|
|
func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) error {
|
|
r := uploadRequest{
|
|
In: in,
|
|
Size: src.Size(),
|
|
ModTime: src.ModTime(ctx),
|
|
MIMEType: fs.MimeType(ctx, src),
|
|
}
|
|
if srcFs := src.Fs(); srcFs != nil && srcFs.Hashes().Contains(hash.SHA1) {
|
|
r.SHA1, _ = src.Hash(ctx, hash.SHA1)
|
|
}
|
|
if o.n != nil {
|
|
n, err := o.fs.c.activeNode(ctx, o.n.ID)
|
|
if err != nil {
|
|
return translateError(err, opObject)
|
|
}
|
|
r.Existing = n
|
|
} else {
|
|
leaf, directoryID, err := o.fs.dirCache.FindPath(ctx, o.remote, true)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
r.ParentID, r.Name = directoryID, o.fs.opt.Enc.FromStandardName(leaf)
|
|
}
|
|
n, err := o.fs.c.upload(ctx, r)
|
|
if err != nil {
|
|
return translateError(err, opObject)
|
|
}
|
|
o.n = n
|
|
return nil
|
|
}
|
|
|
|
// Remove the object by moving it to the trash
|
|
func (o *Object) Remove(ctx context.Context) error {
|
|
if o.n == nil {
|
|
return fs.ErrorObjectNotFound
|
|
}
|
|
err := o.fs.c.trash(ctx, o.n.ID)
|
|
if errors.Is(err, errNotFound) {
|
|
// Already gone.
|
|
return nil
|
|
}
|
|
return translateError(err, opObject)
|
|
}
|
|
|
|
// MimeType of an Object if known, "" otherwise
|
|
func (o *Object) MimeType(ctx context.Context) string {
|
|
if o.n == nil {
|
|
return ""
|
|
}
|
|
return o.n.MIMEType
|
|
}
|
|
|
|
// ID returns the ID of the Object if known, or "" if not
|
|
func (o *Object) ID() string {
|
|
if o.n == nil {
|
|
return ""
|
|
}
|
|
return o.n.ID
|
|
}
|
|
|
|
// Check the interfaces are satisfied
|
|
var (
|
|
_ fs.Fs = (*Fs)(nil)
|
|
_ fs.Purger = (*Fs)(nil)
|
|
_ fs.Copier = (*Fs)(nil)
|
|
_ fs.Mover = (*Fs)(nil)
|
|
_ fs.DirMover = (*Fs)(nil)
|
|
_ fs.PutStreamer = (*Fs)(nil)
|
|
_ fs.ListPer = (*Fs)(nil)
|
|
_ fs.CleanUpper = (*Fs)(nil)
|
|
_ fs.Abouter = (*Fs)(nil)
|
|
_ fs.Disconnecter = (*Fs)(nil)
|
|
_ fs.Shutdowner = (*Fs)(nil)
|
|
_ fs.DirCacheFlusher = (*Fs)(nil)
|
|
_ fs.Object = (*Object)(nil)
|
|
_ fs.MimeTyper = (*Object)(nil)
|
|
_ fs.IDer = (*Object)(nil)
|
|
)
|