Skip to content

"rsync for cloud storage" - Google Drive, S3, Dropbox, Backblaze B2, One Drive, Swift, Hubic, Wasabi, Google Cloud Storage, Azure Blob, Azure Files, Yandex Files

kdrive: add backend for Infomaniak kDrive

Guillaume MALLERET5118e0c32a34
diff --git a/README.md b/README.md
index f5705b2ad..a8ffb14d7 100644
--- a/README.md
+++ b/README.md
@@ -75,6 +75,7 @@ directories to and from different cloud storage providers.
- Impossible Cloud [:page_facing_up:](https://rclone.org/s3/#impossible-cloud)
- Intercolo Object Storage [:page_facing_up:](https://rclone.org/s3/#intercolo)
- IONOS Cloud [:page_facing_up:](https://rclone.org/s3/#ionos)
+- kDrive [:page_facing_up:](https://rclone.org/kdrive/)
- Koofr [:page_facing_up:](https://rclone.org/koofr/)
- Leviia Object Storage [:page_facing_up:](https://rclone.org/s3/#leviia)
- Liara Object Storage [:page_facing_up:](https://rclone.org/s3/#liara-object-storage)
diff --git a/backend/all/all.go b/backend/all/all.go
index 0d8bed8c8..825f3b3ec 100644
--- a/backend/all/all.go
+++ b/backend/all/all.go
@@ -39,6 +39,7 @@ import (
_ "github.com/rclone/rclone/backend/internetarchive"
_ "github.com/rclone/rclone/backend/internxt"
_ "github.com/rclone/rclone/backend/jottacloud"
+ _ "github.com/rclone/rclone/backend/kdrive"
_ "github.com/rclone/rclone/backend/koofr"
_ "github.com/rclone/rclone/backend/linkbox"
_ "github.com/rclone/rclone/backend/local"
diff --git a/backend/kdrive/api/types.go b/backend/kdrive/api/types.go
new file mode 100644
index 000000000..170fc31a8
--- /dev/null
+++ b/backend/kdrive/api/types.go
@@ -0,0 +1,235 @@
+// Package api has type definitions for kDrive
+//
+// Converted from the API docs with help from https://mholt.github.io/json-to-go/
+package api
+
+import (
+ "fmt"
+ "strconv"
+ "time"
+)
+
+// Time represents unix timestamp date and time information for the
+// kDrive API
+type Time time.Time
+
+// UnmarshalJSON turns JSON into a Time
+func (t *Time) UnmarshalJSON(data []byte) error {
+ if string(data) == "null" {
+ return nil
+ }
+
+ timestamp, err := strconv.ParseInt(string(data), 10, 64)
+ if err != nil {
+ return err
+ }
+ newT := time.Unix(timestamp, 0)
+ *t = Time(newT)
+ return nil
+}
+
+// ResultStatus return error details from kdrive when things go wrong
+//
+// If Status is "success" then everything is OK
+type ResultStatus struct {
+ Status string `json:"result"`
+ ErrorDetail struct {
+ Result string `json:"code"`
+ ErrorString string `json:"description"`
+ Context struct {
+ Values []string `json:"values"`
+ } `json:"context"`
+ Errors []struct {
+ Result string `json:"code"`
+ ErrorString string `json:"description"`
+ } `json:"errors"`
+ } `json:"error"`
+}
+
+// Error returns a string for the error and satisfies the error interface
+func (e *ResultStatus) Error() string {
+ var details string
+ for i := range e.ErrorDetail.Errors {
+ details += "|" + e.ErrorDetail.Errors[i].Result
+ }
+
+ return fmt.Sprintf("kDrive error: %s (%s: %s %s)", e.Status, e.ErrorDetail.Result, e.ErrorDetail.ErrorString, details)
+}
+
+// IsError returns true if there is an error
+func (e *ResultStatus) IsError() bool {
+ return e.Status != "success"
+}
+
+// Update returns err directly if it was != nil, otherwise it returns
+// an Error or nil if no error was detected
+func (e *ResultStatus) Update(err error) error {
+ if err != nil {
+ return err
+ }
+ if e.IsError() {
+ return e
+ }
+ return nil
+}
+
+// Check ResultStatus satisfies the error interface
+var _ error = (*ResultStatus)(nil)
+
+// Item describes a folder or a file as returned by Get Folder Items and others
+type Item struct {
+ ID int `json:"id"`
+ Name string `json:"name"`
+ Type string `json:"type"`
+ FullPath string `json:"path"`
+ Status string `json:"status"`
+ Hash string `json:"hash"`
+ Size int64 `json:"size"`
+ Visibility string `json:"visibility"`
+ DriveID int `json:"drive_id"`
+ Depth int `json:"depth"`
+ CreatedBy int `json:"created_by"`
+ CreatedAt Time `json:"created_at"`
+ AddedAt int `json:"added_at"`
+ LastModifiedAt Time `json:"last_modified_at"`
+ LastModifiedBy int `json:"last_modified_by"`
+ RevisedAt int `json:"revised_at"`
+ UpdatedAt int `json:"updated_at"`
+ MimeType string `json:"mime_type"`
+ ParentID int `json:"parent_id"`
+ Color string `json:"color"`
+}
+
+// ItemResult is returned when an item is queried
+type ItemResult struct {
+ ResultStatus
+ Data Item `json:"data"`
+}
+
+// SearchResult is returned when a list of items is requested
+type SearchResult struct {
+ ResultStatus
+ Data []Item `json:"data"`
+ Cursor string `json:"cursor"`
+ HasMore bool `json:"has_more"`
+ ResponseAt int `json:"response_at"`
+}
+
+// ModTime returns the modification time of the item
+func (i *Item) ModTime() (t time.Time) {
+ t = time.Time(i.LastModifiedAt)
+ if t.IsZero() {
+ t = time.Time(i.CreatedAt)
+ }
+ return t
+}
+
+// CancelResource is a kdrive resource that can be cancelled after some action
+type CancelResource struct {
+ CancelID string `json:"cancel_id"`
+ ValidUntil int `json:"valid_until"`
+}
+
+// CancellableResponse is returned from kdrive when an action can be cancelled afterwards
+type CancellableResponse struct {
+ ResultStatus
+ Data CancelResource `json:"data"`
+}
+
+// CreateDirResult is returned from kdrive after a call to MkDir
+type CreateDirResult struct {
+ ResultStatus
+ Data Item `json:"data"`
+}
+
+// FileCopyResponse is returned from kdrive after a call to Copy
+type FileCopyResponse struct {
+ ResultStatus
+ Data Item `json:"data"`
+}
+
+// UploadFileResponse is returned from kdrive after a call to Upload
+type UploadFileResponse struct {
+ ResultStatus
+ Data Item `json:"data"`
+}
+
+// ChecksumFileResult is returned from kdrive after a call to Hash
+type ChecksumFileResult struct {
+ ResultStatus
+ Data struct {
+ Hash string `json:"hash"`
+ } `json:"data"`
+}
+
+// PubLinkResult is returned from kdrive after a call to public link API
+type PubLinkResult struct {
+ ResultStatus
+ Data struct {
+ URL string `json:"url"`
+ FileID int `json:"file_id"`
+ Right string `json:"right"`
+ ValidUntil int `json:"valid_until"`
+ CreatedBy int `json:"created_by"`
+ CreatedAt int `json:"created_at"`
+ UpdatedAt int `json:"updated_at"`
+ Capabilities struct {
+ CanEdit bool `json:"can_edit"`
+ CanSeeStats bool `json:"can_see_stats"`
+ CanSeeInfo bool `json:"can_see_info"`
+ CanDownload bool `json:"can_download"`
+ CanComment bool `json:"can_comment"`
+ CanRequestAccess bool `json:"can_request_access"`
+ } `json:"capabilities"`
+ AccessBlocked bool `json:"access_blocked"`
+ } `json:"data"`
+}
+
+// PubLinkUpdateResult is returned from kdrive after a updating a public link
+type PubLinkUpdateResult struct {
+ ResultStatus
+ Data bool `json:"data"`
+}
+
+// QuotaInfo is return from kdrive after a call get drive info
+type QuotaInfo struct {
+ ResultStatus
+ Data struct {
+ Size int64 `json:"size"`
+ UsedSize int64 `json:"used_size"`
+ } `json:"data"`
+}
+
+// SessionStartResponse is used to start a multichunk upload session
+type SessionStartResponse struct {
+ ResultStatus
+ Data struct {
+ Token string `json:"token"`
+ UploadURL string `json:"upload_url"` // URL pour uploader les chunks
+ } `json:"data"`
+}
+
+// ChunkUploadResponse is returned by kdrive after a chunk upload
+type ChunkUploadResponse struct {
+ ResultStatus
+ Data struct {
+ Hash string `json:"hash,omitempty"` // Only present when requested with with:'hash'
+ } `json:"data"`
+}
+
+// SessionFinishResponse is used to end a multichunk upload session
+type SessionFinishResponse struct {
+ ResultStatus
+ Data struct {
+ Token string `json:"token"`
+ File Item `json:"file"`
+ Result bool `json:"result"`
+ Message string `json:"message"`
+ } `json:"data"`
+}
+
+// SessionCancelResponse is used to cancel a multichunk upload session
+type SessionCancelResponse struct {
+ ResultStatus
+ Data bool `json:"data"`
+}
diff --git a/backend/kdrive/kdrive.go b/backend/kdrive/kdrive.go
new file mode 100644
index 000000000..22e071560
--- /dev/null
+++ b/backend/kdrive/kdrive.go
@@ -0,0 +1,1552 @@
+// Package kdrive provides an interface to the kDrive
+// object storage system.
+package kdrive
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "path"
+ "slices"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/rclone/rclone/backend/kdrive/api"
+ "github.com/rclone/rclone/backend/kdrive/khash"
+ "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/fserrors"
+ "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/multipart"
+ "github.com/rclone/rclone/lib/oauthutil"
+ "github.com/rclone/rclone/lib/pacer"
+ "github.com/rclone/rclone/lib/rest"
+ "golang.org/x/text/unicode/norm"
+)
+
+const (
+ rcloneClientID = "EB9BE55E-C6EA-43BB-8719-262EE2BAED0E"
+ defaultEndpoint = "https://api.infomaniak.com"
+ minSleep = 10 * time.Millisecond
+ maxSleep = 2 * time.Second
+ decayConstant = 2 // bigger for slower decay, exponential
+
+ // userRootDirID is the ID of the user's private root directory
+ userRootDirID = "1"
+)
+
+var (
+ // Base config for how to auth
+ oauthConfig = &oauthutil.Config{
+ Scopes: []string{
+ "drive",
+ },
+ AuthURL: "https://login.infomaniak.com/authorize",
+ TokenURL: "https://login.infomaniak.com/token",
+ ClientID: rcloneClientID,
+ RedirectURL: oauthutil.RedirectLocalhostURL,
+ UsePKCE: true,
+ }
+)
+
+// Register with Fs
+func init() {
+ fs.Register(&fs.RegInfo{
+ Name: "kdrive",
+ Description: "Infomaniak kDrive",
+ NewFs: NewFs,
+ Config: func(ctx context.Context, name string, m configmap.Mapper, config fs.ConfigIn) (*fs.ConfigOut, error) {
+ return oauthutil.ConfigOut("", &oauthutil.Options{
+ OAuth2Config: oauthConfig,
+ })
+ },
+ Options: append(oauthutil.SharedOptionsPKCE, []fs.Option{{
+ Name: config.ConfigEncoding,
+ Help: config.ConfigEncodingHelp,
+ Advanced: true,
+ Default: encoder.Display | encoder.EncodeLeftSpace | encoder.EncodeRightSpace | encoder.EncodeInvalidUtf8,
+ }, {
+ Name: "root_folder_id",
+ Help: `The folder to use as root.
+
+You may use either one of the convenience shortcuts [private or common]
+or an explicit folder ID.
+
+- private: your user private directory
+- common: the kDrive common directory, shared among users`,
+ Advanced: true,
+ Sensitive: true,
+ }, {
+ Name: "drive_id",
+ Help: `ID of the kDrive to use.
+
+When showing a folder on kdrive, you can find the drive_id here:
+https://ksuite.infomaniak.com/{account_id}/kdrive/app/drive/{drive_id}/files/...`,
+ Default: "",
+ }, {
+ Name: "chunk_size",
+ Help: `Files above this size are uploaded in chunks of this size.
+
+The kDrive API accepts chunks between 1 MB and 1 GB, up to 10,000
+chunks per file and a total file size of 1 TiB. The chunk size is
+raised automatically for very large files to stay within the 10,000
+chunks limit.`,
+ Default: fs.SizeSuffix(20 * 1024 * 1024),
+ Advanced: true,
+ }, {
+ Name: "upload_concurrency",
+ Help: `Concurrency for chunked uploads.`,
+ Default: 4,
+ Advanced: true,
+ }, {
+ Name: "endpoint",
+ Help: `The API endpoint to use.
+
+Leave blank normally. There is no reason to change the endpoint except for internal use or beta-testing.`,
+ Advanced: true,
+ }}...),
+ })
+}
+
+// Options defines the configuration for this backend
+type Options struct {
+ Enc encoder.MultiEncoder `config:"encoding"`
+ RootFolderID string `config:"root_folder_id"`
+ DriveID string `config:"drive_id"`
+ ChunkSize fs.SizeSuffix `config:"chunk_size"`
+ UploadConcurrency int `config:"upload_concurrency"`
+ Endpoint string `config:"endpoint"`
+}
+
+// Fs represents a remote kdrive
+type Fs struct {
+ name string // name of this remote
+ root string // the path we are working on
+ opt Options // parsed options
+ features *fs.Features // optional features
+ srv *rest.Client // the connection to the server
+ dirCache *dircache.DirCache // Map of directory path to directory id
+ pacer *fs.Pacer // pacer for API calls
+}
+
+// Object describes a kdrive object
+//
+// Will definitely have info but maybe not meta
+type Object struct {
+ fs *Fs // what this object is part of
+ remote string // The remote path
+ hasMetaData bool // whether info below has been set
+ size int64 // size of the object
+ modTime time.Time // modification time of the object
+ id string // ID of the object
+ xxh3 string // XXH3 if known
+ nestedHash bool // if XXH3 is a nested hash
+}
+
+// ------------------------------------------------------------
+
+// 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("kdrive root '%s'", f.root)
+}
+
+// Features returns the optional features of this Fs
+func (f *Fs) Features() *fs.Features {
+ return f.features
+}
+
+// parsePath parses a kdrive 'url'
+func parsePath(path string) (root string) {
+ root = strings.Trim(path, "/")
+ return
+}
+
+// retryErrorCodes is a slice of error codes that we will retry
+var retryErrorCodes = []int{
+ 408, // Request Timeout
+ 429, // Too Many Requests
+ 500, // Internal Server Error
+ 502, // Bad Gateway
+ 503, // Service Unavailable
+ 504, // Gateway Timeout
+ 509, // Bandwidth Limit Exceeded
+}
+
+// shouldRetry returns a boolean as to whether this resp and err
+// deserve to be retried. It returns the err as a convenience
+func shouldRetry(ctx context.Context, resp *http.Response, err error) (bool, error) {
+ if fserrors.ContextError(ctx, &err) {
+ return false, err
+ }
+
+ // Server side copies hold a transient lock on the source and
+ // destination: retrying gives the concurrent copy time to finish.
+ if isLockedByInternalCopy(err) {
+ return true, err
+ }
+
+ return fserrors.ShouldRetry(err) || fserrors.ShouldRetryHTTP(resp, retryErrorCodes), err
+}
+
+// isLockedByInternalCopy checks if the error is a kDrive "lock_error"
+// raised because the file/directory is locked by a server side copy.
+// These locks are transient: the API releases them as soon as the copy
+// completes, so the operation can be retried.
+func isLockedByInternalCopy(err error) bool {
+ var apiErr *api.ResultStatus
+ return errors.As(err, &apiErr) &&
+ apiErr.ErrorDetail.Result == "lock_error" &&
+ slices.Contains(apiErr.ErrorDetail.Context.Values, "internal_copy")
+}
+
+// errorHandler parses a non 2xx error response into an error
+func errorHandler(resp *http.Response) error {
+ // Decode error response
+ errResponse := new(api.ResultStatus)
+ err := rest.DecodeJSON(resp, &errResponse)
+ if err != nil {
+ fs.Debugf(nil, "Couldn't decode error response: %v", err)
+ }
+ if errResponse.ErrorDetail.ErrorString == "" {
+ errResponse.ErrorDetail.ErrorString = resp.Status
+ }
+ if errResponse.ErrorDetail.Result == "" {
+ errResponse.ErrorDetail.Result = resp.Status
+ }
+ return errResponse
+}
+
+// isNotFoundError checks if the given error is a standard kDrive API "Not Found" error.
+func isNotFoundError(err error) bool {
+ var apiErr *api.ResultStatus
+
+ return errors.As(err, &apiErr) && apiErr.ErrorDetail.Result == "object_not_found"
+}
+
+// NewFs constructs an Fs from the path, container:path
+func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {
+ // Parse config into Options struct
+ opt := new(Options)
+ err := configstruct.Set(m, opt)
+ if err != nil {
+ return nil, err
+ }
+
+ // All API calls are scoped to the drive_id, so it is required
+ if opt.DriveID == "" {
+ return nil, errors.New("drive_id is required for kDrive")
+ }
+
+ // Validate the chunk size: an out of range value breaks uploads
+ if err := checkChunkSize(opt.ChunkSize); err != nil {
+ return nil, err
+ }
+
+ // Use the default API endpoint unless explicitly defined;
+ // not defined as option default to keep it hidden from end user,
+ // since there is little to no reason to change it.
+ if opt.Endpoint == "" {
+ opt.Endpoint = defaultEndpoint
+ }
+
+ oAuthClient, _, err := oauthutil.NewClient(ctx, name, m, oauthConfig)
+ if err != nil {
+ return nil, fmt.Errorf("failed to configure kDrive: %w", err)
+ }
+
+ root = parsePath(root)
+ root = norm.NFC.String(root)
+
+ f := &Fs{
+ name: name,
+ root: root,
+ opt: *opt,
+ srv: rest.NewClient(oAuthClient).SetRoot(opt.Endpoint),
+ pacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
+ }
+
+ f.features = (&fs.Features{
+ CaseInsensitive: false,
+ CanHaveEmptyDirectories: true,
+ PartialUploads: false,
+ }).Fill(ctx, f)
+ f.srv.SetErrorHandler(errorHandler)
+
+ rootID, err := f.computeRootID(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ f.dirCache = dircache.New(root, rootID, f)
+ // Find the current root
+ err = f.dirCache.FindRoot(ctx, false)
+ if err != nil {
+ // Assume it is a file
+ newRoot, remote := dircache.SplitPath(root)
+ tempF := *f
+ tempF.dirCache = dircache.New(newRoot, 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.newObjectWithInfo(ctx, remote, nil)
+ if err != nil {
+ if errors.Is(err, fs.ErrorObjectNotFound) {
+ // File doesn't exist so return old f
+ return f, nil
+ }
+ return nil, err
+ }
+ // XXX: 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
+}
+
+// computeRootID finds the real RootId of the configured RootFolderID.
+func (f *Fs) computeRootID(ctx context.Context) (rootID string, err error) {
+ // A numeric root_folder_id is the ID of the folder itself
+ if _, err := strconv.Atoi(f.opt.RootFolderID); err == nil {
+ return f.opt.RootFolderID, nil
+ }
+
+ var leaf string
+ switch f.opt.RootFolderID {
+ case "private", "":
+ leaf = "Private"
+ case "common":
+ leaf = "Common documents"
+ default:
+ leaf = f.opt.RootFolderID
+ }
+
+ var found bool
+ rootID, found, err = f.FindLeaf(ctx, userRootDirID, leaf)
+ if err != nil {
+ return "", fmt.Errorf("failed to find root folder %q: %w", leaf, err)
+ }
+ if !found {
+ return "", fmt.Errorf("root folder %q not found", leaf)
+ }
+
+ return rootID, nil
+}
+
+// getItem retrieves a file or directory by its ID.
+func (f *Fs) getItem(ctx context.Context, id string) (*api.Item, error) {
+ // https://developer.infomaniak.com/docs/api/get/2/drive/%7Bdrive_id%7D/files/%7Bfile_id%7D
+ opts := rest.Opts{
+ Method: "GET",
+ Path: fmt.Sprintf("/3/drive/%s/files/%s", f.opt.DriveID, id),
+ Parameters: url.Values{},
+ }
+ opts.Parameters.Set("with", "path")
+
+ var result api.ItemResult
+ var resp *http.Response
+ var err error
+ err = f.pacer.Call(func() (bool, error) {
+ resp, err = f.srv.CallJSON(ctx, &opts, nil, &result)
+ err = result.ResultStatus.Update(err)
+ return shouldRetry(ctx, resp, err)
+ })
+ if err != nil {
+ if isNotFoundError(err) {
+ return nil, fs.ErrorObjectNotFound
+ }
+ return nil, fmt.Errorf("couldn't get item: %w", err)
+ }
+
+ item := result.Data
+ if item.ID == 0 {
+ return nil, fs.ErrorObjectNotFound
+ }
+ item.Name = f.opt.Enc.ToStandardName(norm.NFC.String(item.Name))
+ return &item, nil
+}
+
+// findItemInDir retrieves a file or directory by its name in a specific directory using the API.
+func (f *Fs) findItemInDir(ctx context.Context, directoryID string, leaf string) (*api.Item, error) {
+ // https://developer.infomaniak.com/docs/api/get/3/drive/%7Bdrive_id%7D/files/%7Bfile_id%7D/name
+ opts := rest.Opts{
+ Method: "GET",
+ Path: fmt.Sprintf("/3/drive/%s/files/%s/name", f.opt.DriveID, directoryID),
+ Parameters: url.Values{},
+ }
+ opts.Parameters.Set("name", f.opt.Enc.FromStandardName(norm.NFC.String(leaf)))
+ opts.Parameters.Set("with", "path,hash")
+
+ var result api.ItemResult
+ var resp *http.Response
+ var err error
+ err = f.pacer.Call(func() (bool, error) {
+ resp, err = f.srv.CallJSON(ctx, &opts, nil, &result)
+ err = result.ResultStatus.Update(err)
+ return shouldRetry(ctx, resp, err)
+ })
+ if err != nil {
+ if isNotFoundError(err) {
+ return nil, fs.ErrorObjectNotFound
+ }
+ return nil, fmt.Errorf("couldn't find item in dir: %w", err)
+ }
+
+ item := result.Data
+ // Check if item is valid (has an ID)
+ if item.ID == 0 {
+ return nil, fs.ErrorObjectNotFound
+ }
+ // Normalize the name
+ item.Name = f.opt.Enc.ToStandardName(norm.NFC.String(item.Name))
+
+ return &item, nil
+}
+
+// findItemByPath retrieves a file or directory by its path
+func (f *Fs) findItemByPath(ctx context.Context, remote string) (*api.Item, error) {
+ if remote == "" || remote == "." {
+ rootID, err := f.dirCache.FindDir(ctx, "", false)
+ if err != nil {
+ return nil, err
+ }
+ return f.getItem(ctx, rootID)
+ }
+
+ // Get the directoryID of the parent directory
+ directory, leaf := path.Split(remote)
+ directory = strings.TrimSuffix(directory, "/")
+
+ directoryID, err := f.dirCache.FindDir(ctx, directory, false)
+ if err != nil {
+ if errors.Is(err, fs.ErrorDirNotFound) {
+ return nil, fs.ErrorObjectNotFound
+ }
+ return nil, err
+ }
+
+ return f.findItemInDir(ctx, directoryID, leaf)
+}
+
+// Return an Object from a path
+//
+// If it can't be found it returns the error fs.ErrorObjectNotFound.
+func (f *Fs) newObjectWithInfo(ctx context.Context, remote string, info *api.Item) (fs.Object, error) {
+ o := &Object{
+ fs: f,
+ remote: remote,
+ }
+ var err error
+ if info != nil {
+ // Set info
+ err = o.setMetaData(info)
+ } else {
+ err = o.readMetaData(ctx) // reads info and meta, returning an error
+ }
+ if err != nil {
+ return nil, err
+ }
+ return o, nil
+}
+
+// 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) {
+ return f.newObjectWithInfo(ctx, remote, 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) {
+ // Use API endpoint to find item directly by name
+ item, err := f.findItemInDir(ctx, pathID, leaf)
+ if err != nil {
+ if errors.Is(err, fs.ErrorObjectNotFound) {
+ return "", false, nil
+ }
+ return "", false, err
+ }
+
+ if item.Type == "dir" {
+ return strconv.Itoa(item.ID), true, nil
+ }
+
+ // Not a directory
+ return "", false, 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) {
+ // fs.Debugf(f, "CreateDir(%q, %q)\n", pathID, leaf)
+ var resp *http.Response
+ var result api.CreateDirResult
+
+ // https://developer.infomaniak.com/docs/api/post/3/drive/%7Bdrive_id%7D/files/%7Bfile_id%7D/directory
+ opts := rest.Opts{
+ Method: "POST",
+ Path: fmt.Sprintf("/3/drive/%s/files/%s/directory", f.opt.DriveID, pathID),
+ Parameters: url.Values{},
+ }
+ opts.Parameters.Set("name", f.opt.Enc.FromStandardName(norm.NFC.String(leaf)))
+ err = f.pacer.Call(func() (bool, error) {
+ resp, err = f.srv.CallJSON(ctx, &opts, nil, &result)
+ err = result.ResultStatus.Update(err)
+ return shouldRetry(ctx, resp, err)
+ })
+ if err != nil {
+ return "", err
+ }
+
+ return strconv.Itoa(result.Data.ID), nil
+}
+
+// list the objects into the function supplied
+//
+// If directories is set it only sends directories
+// User function to process a File item from listAll
+//
+// Should return true to finish processing
+type listAllFn func(*api.Item) bool
+
+// Lists the directory required calling the user function on each item found.
+//
+// If the user fn ever returns true then it early exits with found = true.
+func (f *Fs) listAll(ctx context.Context, dirID string, directoriesOnly bool, filesOnly bool, recursive bool, fn listAllFn) (found bool, err error) {
+ var rootPath string
+ if recursive {
+ // Only recursive listings need the root item to build
+ // relative paths from the returned FullPaths
+ rootItem, err := f.getItem(ctx, dirID)
+ if err != nil {
+ return false, err
+ }
+ rootPath = rootItem.FullPath + "/"
+ }
+
+ listSomeFiles := func(currentDirID string, fromCursor string) (api.SearchResult, error) {
+ // https://developer.infomaniak.com/docs/api/get/3/drive/%7Bdrive_id%7D/files/%7Bfile_id%7D/files
+ opts := rest.Opts{
+ Method: "GET",
+ Path: fmt.Sprintf("/3/drive/%s/files/%s/files", f.opt.DriveID, currentDirID),
+ Parameters: url.Values{},
+ }
+ opts.Parameters.Set("limit", "1000")
+ opts.Parameters.Set("with", "path,hash")
+ if recursive {
+ opts.Parameters.Set("depth", "unlimited")
+ }
+
+ if len(fromCursor) > 0 {
+ opts.Parameters.Set("cursor", fromCursor)
+ }
+
+ var result api.SearchResult
+ var resp *http.Response
+ err = f.pacer.Call(func() (bool, error) {
+ resp, err = f.srv.CallJSON(ctx, &opts, nil, &result)
+ err = result.ResultStatus.Update(err)
+ return shouldRetry(ctx, resp, err)
+ })
+ if err != nil {
+ return result, fmt.Errorf("couldn't list files: %w", err)
+ }
+ return result, nil
+ }
+
+ var listErr error
+ var recursiveContents func(currentDirID string, currentSubDir string, fromCursor string)
+
+ recursiveContents = func(currentDirID string, currentSubDir string, fromCursor string) {
+ if listErr != nil || found {
+ return
+ }
+ result, err := listSomeFiles(currentDirID, fromCursor)
+ if err != nil {
+ listErr = err
+ return
+ }
+
+ // First, analyze what has been returned, and go in-depth if required
+ for i := range result.Data {
+ item := &result.Data[i]
+ if item.Type == "dir" {
+ if filesOnly {
+ continue
+ }
+ } else {
+ if directoriesOnly {
+ continue
+ }
+ }
+
+ item.Name = f.opt.Enc.ToStandardName(norm.NFC.String(item.Name))
+ if recursive {
+ item.FullPath = f.opt.Enc.ToStandardPath(norm.NFC.String(strings.TrimPrefix(item.FullPath, rootPath)))
+ } else {
+ // Without depth=unlimited the API returns direct
+ // children only, so the remote is just the name
+ item.FullPath = item.Name
+ }
+
+ if fn(item) {
+ found = true
+ return
+ }
+
+ // The API refuses depth=unlimited on the root directory
+ // (userRootDirID), so recurse into each child manually
+ if recursive && currentDirID == userRootDirID && item.Type == "dir" {
+ recursiveContents(strconv.Itoa(item.ID), path.Join(currentSubDir, item.Name), "" /*reset cursor*/)
+ if found {
+ return
+ }
+ }
+ }
+
+ // Then load the rest of the files in that folder and apply the same logic
+ if result.HasMore {
+ recursiveContents(currentDirID, currentSubDir, result.Cursor)
+ }
+ }
+
+ recursiveContents(dirID, "", "")
+
+ if listErr != nil {
+ return found, listErr
+ }
+ return
+}
+
+// listHelper iterates over all items from the directory
+// and calls the callback for each element.
+func (f *Fs) listHelper(ctx context.Context, dir string, recursive bool, callback func(entries fs.DirEntry) error) (err error) {
+ directoryID, err := f.dirCache.FindDir(ctx, dir, false)
+ //fs.Debugf(ctx, "listHelper: root=%s dir=%s directoryID=%s", f.root, dir, directoryID)
+ if err != nil {
+ return err
+ }
+ var iErr error
+
+ _, err = f.listAll(ctx, directoryID, false, false, recursive, func(info *api.Item) bool {
+ remote := path.Join(dir, info.FullPath)
+
+ if info.Type == "dir" {
+ // cache the directory ID for later lookups
+ f.dirCache.Put(remote, strconv.Itoa(info.ID))
+
+ d := fs.NewDir(remote, info.ModTime()).SetID(strconv.Itoa(info.ID))
+ d.SetParentID(strconv.Itoa(info.ParentID))
+ d.SetSize(info.Size)
+
+ iErr = callback(d)
+ } else {
+ o, err := f.newObjectWithInfo(ctx, remote, info)
+ if err != nil {
+ iErr = err
+ return true
+ }
+
+ iErr = callback(o)
+ }
+
+ if iErr != nil {
+ return true
+ }
+ return false
+ })
+
+ if err != nil {
+ return err
+ }
+
+ if iErr != nil {
+ return iErr
+ }
+
+ return 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) (err error) {
+ l := list.NewHelper(callback)
+ err = f.listHelper(ctx, dir, false, func(o fs.DirEntry) error {
+ return l.Add(o)
+ })
+ if err != nil {
+ return err
+ }
+ return l.Flush()
+}
+
+// ListR lists the objects and directories of the Fs starting
+// from dir recursively into out.
+func (f *Fs) ListR(ctx context.Context, dir string, callback fs.ListRCallback) (err error) {
+ l := list.NewHelper(callback)
+ err = f.listHelper(ctx, dir, true, func(o fs.DirEntry) error {
+ // fs.Debugf(nil, "ADD OBJECT %s", o.Remote())
+ return l.Add(o)
+ })
+ if err != nil {
+ return err
+ }
+ return l.Flush()
+}
+
+// Creates from the parameters passed in a half finished Object which
+// must have setMetaData called on it
+//
+// Returns the object, leaf, directoryID and error.
+//
+// Used to create new objects
+func (f *Fs) createObject(ctx context.Context, remote string, modTime time.Time, size int64) (o *Object, leaf string, directoryID string, err error) {
+ // Create the directory for the object if it doesn't exist
+ // fs.Debugf(ctx, "createObject: remote = %s", remote)
+ leaf, directoryID, err = f.dirCache.FindPath(ctx, remote, true)
+ if err != nil {
+ return
+ }
+ // Temporary Object under construction
+ o = &Object{
+ fs: f,
+ remote: remote,
+ size: size,
+ modTime: modTime,
+ }
+ return o, leaf, directoryID, nil
+}
+
+// Put the object into the container
+//
+// 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) {
+ remote := src.Remote()
+ size := src.Size()
+ modTime := src.ModTime(ctx)
+
+ o, leaf, directoryID, err := f.createObject(ctx, remote, modTime, size)
+ if err != nil {
+ return nil, err
+ }
+ return o, o.update(ctx, in, src, directoryID, leaf, options...)
+}
+
+// Mkdir creates the container if it doesn't exist
+func (f *Fs) Mkdir(ctx context.Context, dir string) error {
+ _, err := f.dirCache.FindDir(ctx, dir, true)
+ return err
+}
+
+// purgeCheck removes the root directory, if check is set then it
+// refuses to do so if it has anything in
+func (f *Fs) purgeCheck(ctx context.Context, dir string, check bool) error {
+ root := path.Join(f.root, dir)
+ if root == "" {
+ return errors.New("can't purge root directory")
+ }
+ dc := f.dirCache
+ rootID, err := dc.FindDir(ctx, dir, false)
+ if err != nil {
+ return err
+ }
+
+ if check {
+ nonEmpty, err := f.listAll(ctx, rootID, false, false, false, func(i *api.Item) bool {
+ return true
+ })
+ if err != nil {
+ return err
+ }
+ if nonEmpty {
+ return fs.ErrorDirectoryNotEmpty
+ }
+ }
+
+ // https://developer.infomaniak.com/docs/api/delete/2/drive/%7Bdrive_id%7D/files/%7Bfile_id%7D
+ opts := rest.Opts{
+ Method: "DELETE",
+ Path: fmt.Sprintf("/2/drive/%s/files/%s", f.opt.DriveID, rootID),
+ Parameters: url.Values{},
+ }
+ var resp *http.Response
+ var result api.CancellableResponse
+ err = f.pacer.Call(func() (bool, error) {
+ resp, err = f.srv.CallJSON(ctx, &opts, nil, &result)
+ err = result.ResultStatus.Update(err)
+ return shouldRetry(ctx, resp, err)
+ })
+ if err != nil {
+ return fmt.Errorf("rmdir failed: %w", err)
+ }
+ f.dirCache.FlushDir(dir)
+
+ return nil
+}
+
+// Rmdir deletes the root folder
+//
+// Returns an error if it isn't empty
+func (f *Fs) Rmdir(ctx context.Context, dir string) error {
+ return f.purgeCheck(ctx, dir, true)
+}
+
+// Precision return the precision of 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 {
+ fs.Debugf(src, "Can't copy - not same remote type")
+ return nil, fs.ErrorCantCopy
+ }
+ err := srcObj.readMetaData(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ // Create temporary object
+ dstObj, leaf, directoryID, err := f.createObject(ctx, remote, srcObj.modTime, srcObj.size)
+ if err != nil {
+ return nil, err
+ }
+
+ // https://developer.infomaniak.com/docs/api/post/3/drive/%7Bdrive_id%7D/files/%7Bfile_id%7D/copy/%7Bdestination_directory_id%7D
+ opts := rest.Opts{
+ Method: "POST",
+ Path: fmt.Sprintf("/3/drive/%s/files/%s/copy/%s", f.opt.DriveID, srcObj.id, directoryID),
+ Parameters: url.Values{},
+ }
+ opts.Parameters.Set("name", f.opt.Enc.FromStandardName(norm.NFC.String(leaf)))
+ opts.Parameters.Set("conflict", "version")
+ var resp *http.Response
+ var result api.FileCopyResponse
+ err = f.pacer.Call(func() (bool, error) {
+ resp, err = f.srv.CallJSON(ctx, &opts, nil, &result)
+ err = result.ResultStatus.Update(err)
+ return shouldRetry(ctx, resp, err)
+ })
+ if err != nil {
+ return nil, err
+ }
+ err = dstObj.setMetaData(&result.Data)
+ if err != nil {
+ return nil, err
+ }
+
+ return dstObj, nil
+}
+
+// Purge deletes all the files in the directory
+//
+// Optional interface: Only implement this if you have a way of
+// deleting all the files quicker than just running Remove() on the
+// result of List()
+func (f *Fs) Purge(ctx context.Context, dir string) error {
+ return f.purgeCheck(ctx, dir, false)
+}
+
+// CleanUp empties the trash
+func (f *Fs) CleanUp(ctx context.Context) error {
+ // https://developer.infomaniak.com/docs/api/delete/2/drive/%7Bdrive_id%7D/trash
+ opts := rest.Opts{
+ Method: "DELETE",
+ Path: fmt.Sprintf("/2/drive/%s/trash", f.opt.DriveID),
+ Parameters: url.Values{},
+ }
+ var resp *http.Response
+ var result api.ResultStatus
+ var err error
+ return f.pacer.Call(func() (bool, error) {
+ resp, err = f.srv.CallJSON(ctx, &opts, nil, &result)
+ err = result.Update(err)
+ return shouldRetry(ctx, resp, err)
+ })
+}
+
+// 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 {
+ fs.Debugf(src, "Can't move - not same remote type")
+ return nil, fs.ErrorCantMove
+ }
+
+ // Create temporary object
+ _, leaf, directoryID, err := f.createObject(ctx, remote, srcObj.modTime, srcObj.size)
+ if err != nil {
+ return nil, err
+ }
+
+ // https://developer.infomaniak.com/docs/api/post/3/drive/%7Bdrive_id%7D/files/%7Bfile_id%7D/move/%7Bdestination_directory_id%7D
+ opts := rest.Opts{
+ Method: "POST",
+ Path: fmt.Sprintf("/3/drive/%s/files/%s/move/%s", f.opt.DriveID, srcObj.id, directoryID),
+ Parameters: url.Values{},
+ }
+ opts.Parameters.Set("name", f.opt.Enc.FromStandardName(norm.NFC.String(leaf)))
+ var resp *http.Response
+ var result api.CancellableResponse
+ // The API fails a move onto an occupied destination by default
+ // (conflict=error): that is what we want, rclone removes the
+ // destination itself before calling Move
+ err = f.pacer.Call(func() (bool, error) {
+ resp, err = f.srv.CallJSON(ctx, &opts, nil, &result)
+ err = result.ResultStatus.Update(err)
+ return shouldRetry(ctx, resp, err)
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ dstObj, err := f.NewObject(ctx, remote)
+ if err != nil {
+ return nil, err
+ }
+
+ // The move API carries no info about the destination and conflicts
+ // are resolved above, so make sure the file at the destination
+ // really is the moved one before reporting success
+ if moved, ok := dstObj.(*Object); !ok || moved.id != srcObj.id {
+ return nil, fmt.Errorf("move failed: %q at destination is not the moved file", remote)
+ }
+
+ return dstObj, 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
+ }
+
+ // https://developer.infomaniak.com/docs/api/post/3/drive/%7Bdrive_id%7D/files/%7Bfile_id%7D/move/%7Bdestination_directory_id%7D
+ opts := rest.Opts{
+ Method: "POST",
+ Path: fmt.Sprintf("/3/drive/%s/files/%s/move/%s", f.opt.DriveID, srcID, dstDirectoryID),
+ Parameters: url.Values{},
+ }
+ opts.Parameters.Set("name", f.opt.Enc.FromStandardName(norm.NFC.String(dstLeaf)))
+ var resp *http.Response
+ var result api.CancellableResponse
+ err = f.pacer.Call(func() (bool, error) {
+ resp, err = f.srv.CallJSON(ctx, &opts, nil, &result)
+ err = result.ResultStatus.Update(err)
+ return shouldRetry(ctx, resp, err)
+ })
+ if err != nil {
+ return err
+ }
+
+ srcFs.dirCache.FlushDir(srcRemote)
+ f.dirCache.FlushDir(dstRemote)
+ return nil
+}
+
+// DirCacheFlush resets the directory cache - used in testing as an
+// optional interface
+func (f *Fs) DirCacheFlush() {
+ f.dirCache.ResetRoot()
+}
+
+func (f *Fs) getPublicLink(ctx context.Context, fileID int) (string, bool, error) {
+ // https://developer.infomaniak.com/docs/api/get/2/drive/%7Bdrive_id%7D/files/%7Bfile_id%7D/link
+ opts := rest.Opts{
+ Method: "GET",
+ Path: fmt.Sprintf("/2/drive/%s/files/%d/link", f.opt.DriveID, fileID),
+ }
+ var result api.PubLinkResult
+ err := f.pacer.Call(func() (bool, error) {
+ resp, err := f.srv.CallJSON(ctx, &opts, nil, &result)
+ err = result.Update(err)
+ return shouldRetry(ctx, resp, err)
+ })
+
+ expired := false
+ if err != nil {
+ return "", expired, fmt.Errorf("failed to get public link: %w", err)
+ }
+
+ // check if the shared link is blocked
+ if result.Data.AccessBlocked {
+ return "", expired, nil
+ }
+
+ // check if the shared link is expired
+ if result.Data.ValidUntil > 0 {
+ // ValidUntil is a Unix timestamp (UTC)
+ if time.Now().Unix() > int64(result.Data.ValidUntil) {
+ // link is expired
+ expired = true
+ }
+ }
+
+ return result.Data.URL, expired, nil
+}
+
+func (f *Fs) deletePublicLink(ctx context.Context, fileID int) error {
+ // https://developer.infomaniak.com/docs/api/delete/2/drive/%7Bdrive_id%7D/files/%7Bfile_id%7D/link
+ opts := rest.Opts{
+ Method: "DELETE",
+ Path: fmt.Sprintf("/2/drive/%s/files/%d/link", f.opt.DriveID, fileID),
+ }
+ var result api.ResultStatus
+ err := f.pacer.Call(func() (bool, error) {
+ resp, err := f.srv.CallJSON(ctx, &opts, nil, &result)
+ err = result.Update(err)
+ return shouldRetry(ctx, resp, err)
+ })
+
+ if err != nil {
+ return fmt.Errorf("failed to remove public link: %w", err)
+ }
+
+ return nil
+}
+
+func (f *Fs) createPublicLink(ctx context.Context, fileID int, expire fs.Duration) (string, error) {
+ createReq := struct {
+ Right string `json:"right"` // true for read access
+ ValidUntil int `json:"valid_until,omitempty"`
+ }{
+ Right: "public",
+ }
+
+ // Set expiry if provided
+ if expire != fs.DurationOff {
+ createReq.ValidUntil = int(time.Now().Add(time.Duration(expire)).Unix())
+ }
+
+ // https://developer.infomaniak.com/docs/api/post/2/drive/%7Bdrive_id%7D/files/%7Bfile_id%7D/link
+ opts := rest.Opts{
+ Method: "POST",
+ Path: fmt.Sprintf("/2/drive/%s/files/%d/link", f.opt.DriveID, fileID),
+ }
+
+ var result api.PubLinkResult
+ err := f.pacer.Call(func() (bool, error) {
+ resp, err := f.srv.CallJSON(ctx, &opts, createReq, &result)
+ err = result.ResultStatus.Update(err)
+ return shouldRetry(ctx, resp, err)
+ })
+
+ if err != nil {
+ return "", fmt.Errorf("failed to create public link: %w", err)
+ }
+
+ return result.Data.URL, nil
+}
+
+func (f *Fs) updatePublicLink(ctx context.Context, fileID int, expire fs.Duration) error {
+ createReq := struct {
+ ValidUntil int `json:"valid_until,omitempty"`
+ }{}
+
+ // Set expiry if provided
+ if expire != fs.DurationOff {
+ createReq.ValidUntil = int(time.Now().Add(time.Duration(expire)).Unix())
+ }
+
+ // https://developer.infomaniak.com/docs/api/put/2/drive/%7Bdrive_id%7D/files/%7Bfile_id%7D/link
+ opts := rest.Opts{
+ Method: "PUT",
+ Path: fmt.Sprintf("/2/drive/%s/files/%d/link", f.opt.DriveID, fileID),
+ }
+
+ var result api.PubLinkUpdateResult
+ err := f.pacer.Call(func() (bool, error) {
+ resp, err := f.srv.CallJSON(ctx, &opts, createReq, &result)
+ err = result.ResultStatus.Update(err)
+ return shouldRetry(ctx, resp, err)
+ })
+
+ if err != nil {
+ return fmt.Errorf("failed to update public link: %w", err)
+ }
+
+ return nil
+}
+
+// PublicLink adds a "readable by anyone with link" permission on the given file or folder.
+// If unlink is true, it removes the existing public link.
+func (f *Fs) PublicLink(ctx context.Context, remote string, expire fs.Duration, unlink bool) (string, error) {
+ item, err := f.findItemByPath(ctx, remote)
+ if err != nil {
+ return "", err
+ }
+
+ if unlink {
+ // Remove existing public link
+ err = f.deletePublicLink(ctx, item.ID)
+ return "", err
+ }
+
+ // Check if link exists
+ link, expired, _ := f.getPublicLink(ctx, item.ID)
+ if link != "" {
+ // link exist
+ if expire != fs.DurationOff {
+ // update valid until and return the same link
+ err = f.updatePublicLink(ctx, item.ID, expire)
+ if err != nil {
+ return "", err
+ }
+ return link, nil
+ } else if expired {
+ // delete and recreate after
+ _ = f.deletePublicLink(ctx, item.ID)
+ } else {
+ // return link
+ return link, nil
+ }
+ }
+
+ // Create or get existing public link
+ return f.createPublicLink(ctx, item.ID, expire)
+}
+
+// About gets quota information
+func (f *Fs) About(ctx context.Context) (usage *fs.Usage, err error) {
+ // https://developer.infomaniak.com/docs/api/get/2/drive/%7Bdrive_id%7D
+ opts := rest.Opts{
+ Method: "GET",
+ Path: fmt.Sprintf("/2/drive/%s", f.opt.DriveID),
+ Parameters: url.Values{},
+ }
+ opts.Parameters.Set("only", "used_size,size")
+ var resp *http.Response
+ var q api.QuotaInfo
+ err = f.pacer.Call(func() (bool, error) {
+ resp, err = f.srv.CallJSON(ctx, &opts, nil, &q)
+ err = q.ResultStatus.Update(err)
+ return shouldRetry(ctx, resp, err)
+ })
+ if err != nil {
+ return nil, err
+ }
+ free := max(q.Data.Size-q.Data.UsedSize, 0)
+ usage = &fs.Usage{
+ Total: fs.NewUsageValue(q.Data.Size), // quota of bytes that can be used
+ Used: fs.NewUsageValue(q.Data.UsedSize), // bytes in use
+ Free: fs.NewUsageValue(free), // bytes which can be uploaded before reaching the quota
+ }
+ return usage, nil
+}
+
+// Hashes returns the supported hash sets.
+func (f *Fs) Hashes() hash.Set {
+ return hash.NewHashSet(hash.XXH3)
+}
+
+// ------------------------------------------------------------
+
+// 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
+}
+
+// get file hash
+func (o *Object) retrieveHash(ctx context.Context) (hash string, err error) {
+ var resp *http.Response
+ var result api.ChecksumFileResult
+
+ // https://developer.infomaniak.com/docs/api/get/2/drive/%7Bdrive_id%7D/files/%7Bfile_id%7D/hash
+ opts := rest.Opts{
+ Method: "GET",
+ Path: fmt.Sprintf("/2/drive/%s/files/%s/hash", o.fs.opt.DriveID, o.id),
+ }
+ err = o.fs.pacer.Call(func() (bool, error) {
+ resp, err = o.fs.srv.CallJSON(ctx, &opts, nil, &result)
+ err = result.ResultStatus.Update(err)
+ return shouldRetry(ctx, resp, err)
+ })
+ if err != nil {
+ return "", err
+ }
+
+ return result.Data.Hash, nil
+}
+
+// Hash returns the XXH3 hash of an object as a lowercase hex string.
+//
+// Files which kDrive stores as a nested hash (files uploaded in chunks,
+// either by rclone or by the kDrive apps which use their own chunk
+// sizes) can't be compared with a plain XXH3 of the contents, so no
+// hash is returned for those.
+func (o *Object) Hash(ctx context.Context, t hash.Type) (string, error) {
+ if t != hash.XXH3 {
+ return "", hash.ErrUnsupported
+ }
+
+ if o.xxh3 == "" {
+ remoteHash, err := o.retrieveHash(ctx)
+ if err != nil {
+ return "", fmt.Errorf("failed to get hash: %w", err)
+ }
+ o.setHash(remoteHash)
+ }
+
+ if o.nestedHash {
+ return "", nil
+ }
+
+ return o.xxh3, nil
+}
+
+// Size returns the size of an object in bytes
+func (o *Object) Size() int64 {
+ err := o.readMetaData(context.Background())
+ if err != nil {
+ fs.Logf(o, "Failed to read metadata: %v", err)
+ return 0
+ }
+ return o.size
+}
+
+// setMetaData sets the metadata from info
+func (o *Object) setMetaData(info *api.Item) (err error) {
+ if info.Type == "dir" {
+ return fs.ErrorIsDir
+ }
+ o.hasMetaData = true
+ o.size = info.Size
+ o.modTime = info.ModTime()
+ o.id = strconv.Itoa(info.ID)
+ // The hash is always replaced: a response without one must not
+ // leave the previous version's hash in place
+ o.xxh3 = ""
+ o.nestedHash = false
+ o.setHash(info.Hash)
+ return nil
+}
+
+// setHash sets the hashes from that passed in.
+// Handles both simple format ("xxh3:...") and nested format ("N:xxh3:...")
+func (o *Object) setHash(hashStr string) {
+ // Use khash.ParseHash to handle both simple and nested formats
+ parsedHash, isNested, err := khash.ParseHash(hashStr)
+ if err == nil && parsedHash != "" {
+ o.xxh3 = parsedHash
+ o.nestedHash = isNested
+ }
+}
+
+// readMetaData gets the metadata if it hasn't already been fetched
+//
+// it also sets the info
+func (o *Object) readMetaData(ctx context.Context) (err error) {
+ if o.hasMetaData {
+ return nil
+ }
+ info, err := o.fs.findItemByPath(ctx, o.remote)
+ if err != nil {
+ return err
+ }
+ return o.setMetaData(info)
+}
+
+// ModTime returns the modification time of the object
+//
+// It attempts to read the objects mtime and if that isn't present the
+// LastModified returned in the http headers
+func (o *Object) ModTime(ctx context.Context) time.Time {
+ err := o.readMetaData(ctx)
+ if err != nil {
+ fs.Logf(o, "Failed to read metadata: %v", err)
+ return time.Now()
+ }
+ return o.modTime
+}
+
+// SetModTime sets the modification time of the object
+func (o *Object) SetModTime(ctx context.Context, modTime time.Time) error {
+ var result api.ResultStatus
+
+ modTimeReq := struct {
+ LastModifiedAt int64 `json:"last_modified_at"`
+ }{
+ LastModifiedAt: modTime.Unix(),
+ }
+
+ // https://developer.infomaniak.com/docs/api/post/3/drive/%7Bdrive_id%7D/files/%7Bfile_id%7D/last-modified
+ opts := rest.Opts{
+ Method: "POST",
+ Path: fmt.Sprintf("/3/drive/%s/files/%s/last-modified", o.fs.opt.DriveID, o.id),
+ }
+
+ err := o.fs.pacer.Call(func() (bool, error) {
+ resp, err := o.fs.srv.CallJSON(ctx, &opts, modTimeReq, &result)
+ err = result.Update(err)
+ return shouldRetry(ctx, resp, err)
+ })
+
+ if err != nil {
+ return err
+ }
+
+ // Update Object modTime: the server stores modtimes with second precision so truncate
+ // here too to keep the in-memory modtime identical to the one a
+ // fresh listing returns.
+ o.modTime = modTime.Truncate(time.Second)
+ return nil
+}
+
+// Storable returns a boolean showing whether this object storable
+func (o *Object) Storable() bool {
+ return true
+}
+
+// Open an object for read
+func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.ReadCloser, err error) {
+ fs.FixRangeOption(options, o.Size())
+ var resp *http.Response
+
+ // https://developer.infomaniak.com/docs/api/get/2/drive/%7Bdrive_id%7D/files/%7Bfile_id%7D/download
+ opts := rest.Opts{
+ Method: "GET",
+ Path: fmt.Sprintf("/2/drive/%s/files/%s/download", o.fs.opt.DriveID, o.id),
+ Options: options,
+ }
+ err = o.fs.pacer.Call(func() (bool, error) {
+ resp, err = o.fs.srv.Call(ctx, &opts)
+ return shouldRetry(ctx, resp, err)
+ })
+ if err != nil {
+ return nil, err
+ }
+ return resp.Body, err
+}
+
+// Update the object with the contents of the io.Reader, modTime and size
+//
+// If existing is set then it updates the object rather than creating a new one.
+//
+// The new object may have been created if an error is returned
+func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (err error) {
+ size := src.Size() // NB can upload without size
+ remote := o.Remote()
+
+ if size < 0 {
+ return errors.New("can't upload unknown sizes objects")
+ }
+
+ // Create the directory for the object if it doesn't exist
+ leaf, directoryID, err := o.fs.dirCache.FindPath(ctx, remote, true)
+ if err != nil {
+ return err
+ }
+
+ return o.update(ctx, in, src, directoryID, leaf, options...)
+}
+
+func (o *Object) update(ctx context.Context, in io.Reader, src fs.ObjectInfo, directoryID, leaf string, options ...fs.OpenOption) (err error) {
+ size := src.Size() // NB can upload without size
+
+ if size < 0 {
+ return errors.New("can't upload unknown sizes objects")
+ }
+
+ // if file size is less than the chunk size, upload direct
+ if size <= int64(o.fs.opt.ChunkSize) {
+ return o.updateDirect(ctx, in, directoryID, leaf, src, options...)
+ }
+ // else, use multipart upload with parallelism
+ return o.updateMultipart(ctx, in, src, options...)
+}
+
+func (o *Object) updateDirect(ctx context.Context, in io.Reader, directoryID, leaf string, src fs.ObjectInfo, options ...fs.OpenOption) (err error) {
+ size := src.Size()
+
+ // The body is not buffered: on transient failures the higher
+ // layers retry the whole transfer
+ opts := rest.Opts{
+ Method: "POST",
+ Path: fmt.Sprintf("/3/drive/%s/upload", o.fs.opt.DriveID),
+ Body: in,
+ ContentType: fs.MimeType(ctx, src),
+ ContentLength: &size,
+ Parameters: url.Values{},
+ TransferEncoding: []string{"identity"}, // kdrive doesn't like chunked encoding
+ Options: options,
+ }
+
+ leaf = o.fs.opt.Enc.FromStandardName(norm.NFC.String(leaf))
+ opts.Parameters.Set("file_name", leaf)
+ opts.Parameters.Set("directory_id", directoryID)
+ opts.Parameters.Set("total_size", fmt.Sprintf("%d", size))
+ opts.Parameters.Set("last_modified_at", formatModTime(src.ModTime(ctx)))
+ opts.Parameters.Set("conflict", "version")
+ opts.Parameters.Set("with", "hash")
+
+ // The server verifies the content against total_chunk_hash; it is
+ // optional so only sent when the source hash is known
+ if totalHash, hashErr := src.Hash(ctx, hash.XXH3); hashErr == nil && totalHash != "" {
+ opts.Parameters.Set("total_chunk_hash", "xxh3:"+totalHash)
+ }
+
+ // CallNoRetry: leave transient failures to the higher layers
+ var resp *http.Response
+ var result api.UploadFileResponse
+ err = o.fs.pacer.CallNoRetry(func() (bool, error) {
+ resp, err = o.fs.srv.CallJSON(ctx, &opts, nil, &result)
+ err = result.ResultStatus.Update(err)
+ return shouldRetry(ctx, resp, err)
+ })
+ if err != nil {
+ return err
+ }
+
+ return o.setMetaData(&result.Data)
+}
+
+// updateMultipart uploads large files using chunked upload with parallel streaming
+func (o *Object) updateMultipart(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) error {
+ chunkWriter, err := multipart.UploadMultipart(ctx, src, in, multipart.UploadMultipartOptions{
+ Open: o.fs,
+ OpenOptions: options,
+ })
+ if err != nil {
+ return err
+ }
+
+ // Extract the file info from the chunk writer
+ session := chunkWriter.(*uploadSession)
+ if session.fileInfo == nil {
+ return errors.New("upload failed: no file info returned")
+ }
+ return o.setMetaData(session.fileInfo)
+}
+
+// Remove an object
+func (o *Object) Remove(ctx context.Context) error {
+ // https://developer.infomaniak.com/docs/api/delete/2/drive/%7Bdrive_id%7D/files/%7Bfile_id%7D
+ opts := rest.Opts{
+ Method: "DELETE",
+ Path: fmt.Sprintf("/2/drive/%s/files/%s", o.fs.opt.DriveID, o.id),
+ }
+ var result api.CancellableResponse
+ return o.fs.pacer.Call(func() (bool, error) {
+ resp, err := o.fs.srv.CallJSON(ctx, &opts, nil, &result)
+ err = result.ResultStatus.Update(err)
+ return shouldRetry(ctx, resp, err)
+ })
+}
+
+// ID returns the ID of the Object if known, or "" if not
+func (o *Object) ID() string {
+ return o.id
+}
+
+// Check the interfaces are satisfied
+var (
+ _ fs.Fs = (*Fs)(nil)
+ _ fs.Purger = (*Fs)(nil)
+ _ fs.CleanUpper = (*Fs)(nil)
+ _ fs.Copier = (*Fs)(nil)
+ _ fs.Mover = (*Fs)(nil)
+ _ fs.DirMover = (*Fs)(nil)
+ _ fs.DirCacheFlusher = (*Fs)(nil)
+ _ fs.ListRer = (*Fs)(nil)
+ _ fs.ListPer = (*Fs)(nil)
+ _ fs.Abouter = (*Fs)(nil)
+ _ fs.PublicLinker = (*Fs)(nil)
+ _ fs.OpenChunkWriter = (*Fs)(nil)
+ _ fs.Object = (*Object)(nil)
+ _ fs.IDer = (*Object)(nil)
+)
diff --git a/backend/kdrive/kdrive_internal_test.go b/backend/kdrive/kdrive_internal_test.go
new file mode 100644
index 000000000..16dda6beb
--- /dev/null
+++ b/backend/kdrive/kdrive_internal_test.go
@@ -0,0 +1,551 @@
+// Unit tests for the kdrive backend
+package kdrive
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/rclone/rclone/backend/kdrive/api"
+ "github.com/rclone/rclone/fs"
+ "github.com/rclone/rclone/fs/config/configmap"
+ "github.com/rclone/rclone/fs/hash"
+ "github.com/rclone/rclone/lib/dircache"
+ "github.com/rclone/rclone/lib/pacer"
+ "github.com/rclone/rclone/lib/rest"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// TestCheckChunkSize checks chunk_size validation against the API limits
+func TestCheckChunkSize(t *testing.T) {
+ for _, test := range []struct {
+ in fs.SizeSuffix
+ wantErr string
+ }{
+ {in: 20 * fs.Mebi, wantErr: ""}, // default
+ {in: 1000 * 1000, wantErr: ""}, // API minimum
+ {in: 1000 * 1000 * 1000, wantErr: ""}, // API maximum
+ {in: 0, wantErr: "too small"}, // panics without validation
+ {in: 999 * 1000, wantErr: "too small"}, // below API minimum
+ {in: 1000*1000*1000 + 1, wantErr: "too large"}, // above API maximum
+ {in: 2 * 1000 * 1000 * 1000, wantErr: "too large"}, // way above API maximum
+ } {
+ t.Run(test.in.String(), func(t *testing.T) {
+ err := checkChunkSize(test.in)
+ if test.wantErr == "" {
+ assert.NoError(t, err)
+ } else {
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), test.wantErr)
+ }
+ })
+ }
+}
+
+// TestOpenChunkWriterClampsCallerChunkSize checks that a caller
+// supplied chunk size hint below the API minimum is raised to it
+func TestOpenChunkWriterClampsCallerChunkSize(t *testing.T) {
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = io.Copy(io.Discard, r.Body)
+ _, _ = fmt.Fprintln(w, `{"result":"success","data":{"token":"tok","upload_url":"http://unused"}}`)
+ }))
+ defer ts.Close()
+
+ f := newTestFs(t, ts.URL)
+ f.dirCache = dircache.New("", "1", f)
+ src := &mockObjectInfo{remote: "file.txt", size: 4, modTime: time.Unix(1700000000, 0)}
+
+ info, _, err := f.OpenChunkWriter(context.Background(), "file.txt", src, &fs.ChunkOption{ChunkSize: 512 * 1024})
+ require.NoError(t, err)
+ assert.Equal(t, int64(minChunkSize), info.ChunkSize, "a chunk size hint below the API minimum must be raised to it")
+}
+
+// TestObjectSetMetaDataResetsStaleHash checks that setMetaData always
+// replaces the hash (a chunked upload finish response carries none)
+func TestObjectSetMetaDataResetsStaleHash(t *testing.T) {
+ for _, test := range []struct {
+ name string
+ staleHash string
+ staleNested bool
+ newHash string
+ wantHash string
+ wantIsNested bool
+ wantHashKnown bool
+ }{
+ {
+ name: "empty hash clears stale plain hash",
+ staleHash: "deadbeef",
+ staleNested: false,
+ newHash: "",
+ wantHash: "",
+ wantIsNested: false,
+ wantHashKnown: false,
+ },
+ {
+ name: "empty hash clears stale nested hash",
+ staleHash: "deadbeef",
+ staleNested: true,
+ newHash: "",
+ wantHash: "",
+ wantIsNested: false,
+ wantHashKnown: false,
+ },
+ {
+ name: "plain hash is set",
+ staleHash: "deadbeef",
+ staleNested: false,
+ newHash: "xxh3:12345678",
+ wantHash: "12345678",
+ wantIsNested: false,
+ wantHashKnown: true,
+ },
+ {
+ name: "nested hash is set",
+ staleHash: "deadbeef",
+ staleNested: false,
+ newHash: "N:xxh3:87654321",
+ wantHash: "87654321",
+ wantIsNested: true,
+ wantHashKnown: true,
+ },
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ o := &Object{
+ remote: "file.txt",
+ hasMetaData: true,
+ xxh3: test.staleHash,
+ nestedHash: test.staleNested,
+ }
+ info := &api.Item{
+ ID: 42,
+ Name: "file.txt",
+ Type: "file",
+ Hash: test.newHash,
+ }
+
+ err := o.setMetaData(info)
+ require.NoError(t, err)
+ assert.Equal(t, test.wantHash, o.xxh3, "hash after setMetaData")
+ assert.Equal(t, test.wantIsNested, o.nestedHash, "nested flag after setMetaData")
+ assert.True(t, o.hasMetaData)
+
+ // Hash() must reflect the new state. Only checked when a
+ // hash is known: with no hash Hash() would query the API.
+ // Nested hashes are not comparable with plain XXH3, so
+ // Hash() returns "" for them.
+ if test.wantHashKnown {
+ got, gotErr := o.Hash(context.Background(), hash.XXH3)
+ require.NoError(t, gotErr)
+ if test.wantIsNested {
+ assert.Equal(t, "", got, "nested hash must not be returned as XXH3")
+ } else {
+ assert.Equal(t, test.wantHash, got)
+ }
+ }
+ })
+ }
+}
+
+// newTestFs creates an Fs wired to a test server with a plain client
+// (no OAuth) and a fast pacer
+func newTestFs(t *testing.T, endpoint string) *Fs {
+ t.Helper()
+ return &Fs{
+ name: "TestKdrive",
+ root: "",
+ opt: Options{DriveID: "1234", Endpoint: endpoint},
+ srv: rest.NewClient(&http.Client{}).SetRoot(endpoint),
+ pacer: fs.NewPacer(context.Background(),
+ pacer.NewDefault(pacer.MinSleep(time.Millisecond), pacer.MaxSleep(2*time.Millisecond), pacer.DecayConstant(2))),
+ }
+}
+
+// TestWriteChunkDetectsResultError checks that a 200 with result:error
+// is reported as an error
+func TestWriteChunkDetectsResultError(t *testing.T) {
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = io.Copy(io.Discard, r.Body)
+ _, _ = fmt.Fprintln(w, `{"result":"error","error":{"code":"chunk_error","description":"chunk upload failed"}}`)
+ }))
+ defer ts.Close()
+
+ f := newTestFs(t, ts.URL)
+ u := &uploadSession{
+ f: f,
+ token: "tok",
+ uploadURL: ts.URL,
+ fileSize: 4,
+ chunkSize: 4,
+ chunkHashes: make(map[int64]string),
+ }
+
+ _, err := u.WriteChunk(context.Background(), 0, bytes.NewReader([]byte("test")))
+ require.Error(t, err, "result:error with HTTP 200 must not be treated as success")
+ assert.Contains(t, err.Error(), "chunk upload failed")
+}
+
+// TestWriteChunkRetriesAndRewinds checks that transient failures are
+// retried with the chunk re-sent from the start of the reader
+func TestWriteChunkRetriesAndRewinds(t *testing.T) {
+ var mu sync.Mutex
+ var attempts int
+ var bodies []string
+
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ body, _ := io.ReadAll(r.Body)
+ mu.Lock()
+ attempts++
+ bodies = append(bodies, string(body))
+ current := attempts
+ mu.Unlock()
+
+ w.Header().Set("Content-Type", "application/json")
+ if current == 1 {
+ w.WriteHeader(http.StatusInternalServerError)
+ _, _ = fmt.Fprintln(w, `{"result":"error","error":{"code":"internal_error","description":"transient"}}`)
+ return
+ }
+ _, _ = fmt.Fprintln(w, `{"result":"success","data":{"chunk_number":1,"status":"OK"}}`)
+ }))
+ defer ts.Close()
+
+ f := newTestFs(t, ts.URL)
+ u := &uploadSession{
+ f: f,
+ token: "tok",
+ uploadURL: ts.URL,
+ fileSize: 4,
+ chunkSize: 4,
+ chunkHashes: make(map[int64]string),
+ }
+
+ written, err := u.WriteChunk(context.Background(), 0, bytes.NewReader([]byte("test")))
+ require.NoError(t, err)
+ assert.Equal(t, int64(4), written)
+
+ mu.Lock()
+ defer mu.Unlock()
+ require.Len(t, bodies, 2, "chunk upload must be retried once after a 5xx")
+ assert.Equal(t, "test", bodies[0], "first attempt sends the chunk")
+ assert.Equal(t, "test", bodies[1], "retry must re-send the chunk from the start of the reader")
+}
+
+// kdriveMockItem returns a JSON body for a single item result
+func kdriveMockItem(id int, name string) string {
+ return fmt.Sprintf(`{"result":"success","data":{"id":%d,"name":%q,"type":"file","path":%q,"last_modified_at":1700000000}}`, id, name, "/"+name)
+}
+
+// mockObjectInfo is a minimal fs.ObjectInfo for testing
+type mockObjectInfo struct {
+ remote string
+ size int64
+ modTime time.Time
+ hash string
+}
+
+func (m *mockObjectInfo) Fs() fs.Info { return nil }
+func (m *mockObjectInfo) String() string { return m.remote }
+func (m *mockObjectInfo) Remote() string { return m.remote }
+func (m *mockObjectInfo) Size() int64 { return m.size }
+func (m *mockObjectInfo) ModTime(_ context.Context) time.Time { return m.modTime }
+func (m *mockObjectInfo) Storable() bool { return true }
+func (m *mockObjectInfo) MimeType(_ context.Context) string { return "application/octet-stream" }
+
+func (m *mockObjectInfo) Hash(_ context.Context, t hash.Type) (string, error) {
+ if m.hash == "" || t != hash.XXH3 {
+ return "", hash.ErrUnsupported
+ }
+ return m.hash, nil
+}
+
+// TestUpdateDirectNoRetryOnServerError checks that a failed single
+// part upload is not retried here: the input must not be buffered, the
+// higher layers retry the whole transfer
+func TestUpdateDirectNoRetryOnServerError(t *testing.T) {
+ var attempts int32
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ atomic.AddInt32(&attempts, 1)
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = io.Copy(io.Discard, r.Body)
+ w.WriteHeader(http.StatusInternalServerError)
+ _, _ = fmt.Fprintln(w, `{"result":"error","error":{"code":"internal_error","description":"transient"}}`)
+ }))
+ defer ts.Close()
+
+ f := newTestFs(t, ts.URL)
+ o := &Object{fs: f, remote: "file.txt"}
+ src := &mockObjectInfo{remote: "file.txt", size: 4, modTime: time.Unix(1700000000, 0), hash: "12345678"}
+
+ err := o.updateDirect(context.Background(), bytes.NewReader([]byte("test")), "1", "file.txt", src)
+ require.Error(t, err)
+ assert.Equal(t, int32(1), atomic.LoadInt32(&attempts), "single part uploads must not be retried here")
+}
+
+// TestUpdateDirect checks the upload parameters and metadata of a
+// successful single part upload, and that total_chunk_hash is only
+// sent when the source hash is known
+func TestUpdateDirect(t *testing.T) {
+ for _, test := range []struct {
+ name string
+ srcHash string
+ wantTotalHash string
+ }{
+ {name: "hash known", srcHash: "12345678", wantTotalHash: "xxh3:12345678"},
+ {name: "hash unknown", srcHash: "", wantTotalHash: ""},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ var gotTotalHash, gotBody string
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ gotTotalHash = r.URL.Query().Get("total_chunk_hash")
+ body, _ := io.ReadAll(r.Body)
+ gotBody = string(body)
+ _, _ = fmt.Fprintln(w, `{"result":"success","data":{"id":55,"name":"file.txt","type":"file","path":"/file.txt","hash":"xxh3:99998888","last_modified_at":1700000000}}`)
+ }))
+ defer ts.Close()
+
+ f := newTestFs(t, ts.URL)
+ o := &Object{fs: f, remote: "file.txt"}
+ src := &mockObjectInfo{remote: "file.txt", size: 4, modTime: time.Unix(1700000000, 0), hash: test.srcHash}
+
+ err := o.updateDirect(context.Background(), bytes.NewReader([]byte("test")), "1", "file.txt", src)
+ require.NoError(t, err)
+ assert.Equal(t, "test", gotBody, "the content must be streamed as-is")
+ assert.Equal(t, test.wantTotalHash, gotTotalHash, "total_chunk_hash")
+ assert.Equal(t, "55", o.id)
+ gotHash, hashErr := o.Hash(context.Background(), hash.XXH3)
+ require.NoError(t, hashErr)
+ assert.Equal(t, "99998888", gotHash)
+ })
+ }
+}
+
+// TestNewFsRequiresDriveID checks that NewFs fails fast when drive_id
+// is missing
+func TestNewFsRequiresDriveID(t *testing.T) {
+ m := configmap.Simple{"chunk_size": "20Mi"}
+ _, err := NewFs(context.Background(), "kdrive", "", m)
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "drive_id")
+}
+
+// TestUploadSessionStringMasksToken checks that the upload session
+// String does not leak the session token in debug logs
+func TestUploadSessionStringMasksToken(t *testing.T) {
+ u := &uploadSession{token: "very-secret-uuid"}
+ assert.NotContains(t, u.String(), "very-secret-uuid")
+}
+
+// TestListNonRecursiveSingleRoundTrip checks that a non recursive
+// listing needs a single API request: without depth=unlimited the API
+// returns direct children only, so neither the parent item lookup nor
+// a child filter is needed
+func TestListNonRecursiveSingleRoundTrip(t *testing.T) {
+ var requests int32
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ atomic.AddInt32(&requests, 1)
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = io.Copy(io.Discard, r.Body)
+ switch {
+ case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/files/1/files"):
+ // Direct children only, as returned without depth=unlimited
+ _, _ = fmt.Fprintln(w, `{"result":"success","data":[`+
+ `{"id":10,"name":"sub","type":"dir","path":"/sub"},`+
+ `{"id":11,"name":"file.txt","type":"file","path":"/file.txt","hash":"xxh3:12345678","last_modified_at":1700000000}],"has_more":false}`)
+ default:
+ t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
+ _, _ = fmt.Fprintln(w, `{"result":"error","error":{"code":"unexpected","description":"unexpected request"}}`)
+ }
+ }))
+ defer ts.Close()
+
+ f := newTestFs(t, ts.URL)
+ f.dirCache = dircache.New("", "1", f)
+
+ entries, err := f.List(context.Background(), "")
+ require.NoError(t, err)
+ assert.Equal(t, int32(1), atomic.LoadInt32(&requests), "non recursive listing must make a single API request")
+
+ names := make([]string, 0, len(entries))
+ for _, entry := range entries {
+ names = append(names, entry.Remote())
+ }
+ assert.ElementsMatch(t, []string{"sub", "file.txt"}, names)
+}
+
+// TestMoveConflictReturnsError checks that moving onto an occupied
+// destination reports the API conflict instead of resolving it: rclone
+// removes the destination itself before calling Move
+func TestMoveConflictReturnsError(t *testing.T) {
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = io.Copy(io.Discard, r.Body)
+ switch {
+ case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/files/111/move/1"):
+ _, _ = fmt.Fprintln(w, `{"result":"error","error":{"code":"conflict_error","description":"destination already exists"}}`)
+ default:
+ t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
+ _, _ = fmt.Fprintln(w, `{"result":"error","error":{"code":"unexpected","description":"unexpected request"}}`)
+ }
+ }))
+ defer ts.Close()
+
+ f := newTestFs(t, ts.URL)
+ f.dirCache = dircache.New("", "1", f)
+ srcObj := &Object{fs: f, remote: "src.txt", id: "111", hasMetaData: true}
+
+ _, err := f.Move(context.Background(), srcObj, "file2")
+ require.Error(t, err, "a move onto an occupied destination must fail")
+ assert.Contains(t, err.Error(), "conflict", "the API conflict must be reported")
+}
+
+// TestMoveDetectsForeignObjectAtDestination checks that Move does not
+// return a file re-created by another writer at the destination
+func TestMoveDetectsForeignObjectAtDestination(t *testing.T) {
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = io.Copy(io.Discard, r.Body)
+ switch {
+ case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/files/111/move/1"):
+ // The move API reports success...
+ _, _ = fmt.Fprintln(w, `{"result":"success","data":{"cancel_id":"abc","valid_until":1700000000}}`)
+ case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/files/1/name"):
+ // ...but the file at the destination is not the moved
+ // file: another writer re-created it
+ _, _ = fmt.Fprintln(w, kdriveMockItem(999, "file2"))
+ default:
+ t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
+ _, _ = fmt.Fprintln(w, `{"result":"error","error":{"code":"unexpected","description":"unexpected request"}}`)
+ }
+ }))
+ defer ts.Close()
+
+ f := newTestFs(t, ts.URL)
+ f.dirCache = dircache.New("", "1", f)
+ srcObj := &Object{fs: f, remote: "src.txt", id: "111", hasMetaData: true}
+
+ _, err := f.Move(context.Background(), srcObj, "file2")
+ require.Error(t, err, "Move must not report success when the destination is not the moved file")
+}
+
+// TestMoveSuccess checks the nominal move: the object returned is the
+// moved file (same ID as the source).
+func TestMoveSuccess(t *testing.T) {
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = io.Copy(io.Discard, r.Body)
+ switch {
+ case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/files/111/move/1"):
+ _, _ = fmt.Fprintln(w, `{"result":"success","data":{"cancel_id":"abc","valid_until":1700000000}}`)
+ case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/files/1/name"):
+ // After the move, the moved file is at the destination
+ _, _ = fmt.Fprintln(w, kdriveMockItem(111, "file2"))
+ default:
+ t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
+ _, _ = fmt.Fprintln(w, `{"result":"error","error":{"code":"unexpected","description":"unexpected request"}}`)
+ }
+ }))
+ defer ts.Close()
+
+ f := newTestFs(t, ts.URL)
+ f.dirCache = dircache.New("", "1", f)
+ srcObj := &Object{fs: f, remote: "src.txt", id: "111", hasMetaData: true}
+
+ dstObj, err := f.Move(context.Background(), srcObj, "file2")
+ require.NoError(t, err)
+ moved, ok := dstObj.(*Object)
+ require.True(t, ok)
+ assert.Equal(t, "111", moved.id, "the returned object must be the moved file")
+}
+
+// TestFormatModTime checks that pre-1970 times format as negative
+// unix timestamps instead of wrapping through a uint64 cast
+func TestFormatModTime(t *testing.T) {
+ for _, test := range []struct {
+ in time.Time
+ want string
+ }{
+ {in: time.Unix(1700000000, 0), want: "1700000000"},
+ {in: time.Unix(0, 0), want: "0"},
+ {in: time.Unix(-1577923200, 0), want: "-1577923200"}, // Sat Jan 2 1965
+ } {
+ t.Run(test.want, func(t *testing.T) {
+ assert.Equal(t, test.want, formatModTime(test.in))
+ })
+ }
+}
+
+// TestObjectSetMetaDataIsDir checks that directories are rejected
+func TestObjectSetMetaDataIsDir(t *testing.T) {
+ o := &Object{remote: "dir"}
+ info := &api.Item{ID: 42, Name: "dir", Type: "dir"}
+ err := o.setMetaData(info)
+ assert.Equal(t, fs.ErrorIsDir, err)
+}
+
+// TestShouldRetryLockError checks that transient locks held by server
+// side copies are retried while locks held by applications and other
+// errors are not
+func TestShouldRetryLockError(t *testing.T) {
+ for _, test := range []struct {
+ name string
+ body string
+ status int
+ wantRetry bool
+ }{
+ {
+ name: "lock held by internal copy",
+ body: `{"result":"error","error":{"code":"lock_error","description":"There is a lock on this file, locked by internal_copy","context":{"values":["internal_copy"]}}}`,
+ status: http.StatusForbidden,
+ wantRetry: true,
+ },
+ {
+ name: "lock held by an application",
+ body: `{"result":"error","error":{"code":"lock_error","description":"There is a lock on this file, locked by onlyoffice","context":{"values":["onlyoffice"]}}}`,
+ status: http.StatusForbidden,
+ wantRetry: false,
+ },
+ {
+ name: "lock without context",
+ body: `{"result":"error","error":{"code":"lock_error","description":"There is a lock on this file, locked by internal_copy"}}`,
+ status: http.StatusForbidden,
+ wantRetry: false,
+ },
+ {
+ name: "other api error",
+ body: `{"result":"error","error":{"code":"object_not_found","description":"File not found"}}`,
+ status: http.StatusNotFound,
+ wantRetry: false,
+ },
+ {
+ name: "server error",
+ status: http.StatusServiceUnavailable,
+ wantRetry: true,
+ },
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ var apiErr error
+ if test.body != "" {
+ e := new(api.ResultStatus)
+ require.NoError(t, json.Unmarshal([]byte(test.body), e))
+ apiErr = e
+ }
+ resp := &http.Response{StatusCode: test.status, Header: http.Header{}}
+ got, gotErr := shouldRetry(context.Background(), resp, apiErr)
+ assert.Equal(t, test.wantRetry, got)
+ assert.Equal(t, apiErr, gotErr)
+ })
+ }
+}
diff --git a/backend/kdrive/kdrive_test.go b/backend/kdrive/kdrive_test.go
new file mode 100644
index 000000000..fe717f8c9
--- /dev/null
+++ b/backend/kdrive/kdrive_test.go
@@ -0,0 +1,25 @@
+// Test kdrive filesystem interface
+package kdrive
+
+import (
+ "testing"
+
+ "github.com/rclone/rclone/fs"
+ "github.com/rclone/rclone/fstest/fstests"
+)
+
+// TestIntegration runs integration tests against the remote
+func TestIntegration(t *testing.T) {
+ fstests.Run(t, &fstests.Opt{
+ RemoteName: "TestKdrive:",
+ NilObject: (*Object)(nil),
+ ChunkedUpload: fstests.ChunkedUploadConfig{
+ MinChunkSize: minChunkSize,
+ MaxChunkSize: maxChunkSize,
+ },
+ })
+}
+
+func (f *Fs) SetUploadChunkSize(cs fs.SizeSuffix) (fs.SizeSuffix, error) {
+ return f.setChunkSize(cs)
+}
diff --git a/backend/kdrive/khash/khash.go b/backend/kdrive/khash/khash.go
new file mode 100644
index 000000000..c1658068c
--- /dev/null
+++ b/backend/kdrive/khash/khash.go
@@ -0,0 +1,67 @@
+// Package khash provides the kDrive specific hash handling.
+//
+// kDrive uses XXH3-64 for file hashing. Files uploaded in chunks (by
+// rclone, or by the kDrive apps which each use their own chunk size)
+// get a "nested" hash: the XXH3 of the concatenated lowercase hex
+// strings of the individual chunk hashes. Such a nested hash can't be
+// compared with a plain XXH3 of the file contents.
+//
+// Hash formats returned by the kDrive API:
+// - "xxh3:HASH" for a plain XXH3 of the file contents
+// - "N:xxh3:HASH" for the nested hash of a chunked upload
+package khash
+
+import (
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "strings"
+
+ "github.com/zeebo/xxh3"
+)
+
+// ParseHash parses a kDrive hash string from the API and returns the hex hash value
+// along with whether it is a nested (chunked) hash.
+func ParseHash(hashStr string) (hexHash string, isNested bool, err error) {
+ if hashStr == "" {
+ return "", false, nil
+ }
+
+ // Check for nested hash format: "N:xxh3:HASH"
+ if strings.HasPrefix(hashStr, "N:xxh3:") {
+ hashStr = strings.TrimPrefix(hashStr, "N:xxh3:")
+ isNested = true
+ } else {
+ hashStr = strings.TrimPrefix(hashStr, "xxh3:")
+ }
+
+ // Validate hex string
+ if _, decodeErr := hex.DecodeString(hashStr); decodeErr != nil {
+ return "", false, fmt.Errorf("invalid hash format: %w", decodeErr)
+ }
+
+ return hashStr, isNested, nil
+}
+
+// NestedChunkHash computes the kDrive nested hash from the hashes of the
+// file chunks, in order.
+//
+// kDrive stores the nested hash of a chunked file as the XXH3 of the
+// concatenated lowercase hex strings of the individual chunk hashes.
+// Each chunk hash may be passed with or without the "xxh3:" prefix.
+func NestedChunkHash(chunkHashes []string) (string, error) {
+ if len(chunkHashes) == 0 {
+ return "", errors.New("no chunk hashes to nest")
+ }
+ hexHashes := make([]string, len(chunkHashes))
+ for i, chunkHash := range chunkHashes {
+ hexHash, _, err := ParseHash(chunkHash)
+ if err != nil {
+ return "", fmt.Errorf("invalid chunk hash %q: %w", chunkHash, err)
+ }
+ hexHashes[i] = hexHash
+ }
+ hasher := xxh3.New()
+ _, _ = hasher.Write([]byte(strings.Join(hexHashes, "")))
+ return hex.EncodeToString(hasher.Sum(nil)), nil
+}
diff --git a/backend/kdrive/khash/khash_test.go b/backend/kdrive/khash/khash_test.go
new file mode 100644
index 000000000..7b7e421c8
--- /dev/null
+++ b/backend/kdrive/khash/khash_test.go
@@ -0,0 +1,150 @@
+package khash
+
+import "testing"
+
+func TestParseHash(t *testing.T) {
+ tests := []struct {
+ name string
+ input string
+ expectedHash string
+ isNested bool
+ expectError bool
+ }{
+ {
+ name: "simple hash with prefix",
+ input: "xxh3:1db797b96febd334",
+ expectedHash: "1db797b96febd334",
+ isNested: false,
+ },
+ {
+ name: "nested hash",
+ input: "N:xxh3:877abf3579f0a5c0",
+ expectedHash: "877abf3579f0a5c0",
+ isNested: true,
+ },
+ {
+ name: "plain hex",
+ input: "1db797b96febd334",
+ expectedHash: "1db797b96febd334",
+ isNested: false,
+ },
+ {
+ name: "empty string",
+ input: "",
+ expectedHash: "",
+ isNested: false,
+ },
+ {
+ name: "invalid hex",
+ input: "xxh3:notahexvalue",
+ expectError: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ hash, isNested, err := ParseHash(tt.input)
+
+ if tt.expectError {
+ if err == nil {
+ t.Error("Expected error but got none")
+ }
+ return
+ }
+
+ if err != nil {
+ t.Fatalf("Unexpected error: %v", err)
+ }
+
+ if hash != tt.expectedHash {
+ t.Errorf("Hash: got %q, expected %q", hash, tt.expectedHash)
+ }
+ if isNested != tt.isNested {
+ t.Errorf("IsNested: got %t, expected %t", isNested, tt.isNested)
+ }
+ })
+ }
+}
+
+func TestNestedChunkHash(t *testing.T) {
+ // Golden values: the nested hash is the XXH3 of the concatenated
+ // lowercase hex strings of the chunk hashes, in order
+ chunk1 := "xxh3:d447b1ea40e6988b" // XXH3 of "hello world"
+ chunk2 := "2d06800538d394c2" // XXH3 of ""
+
+ tests := []struct {
+ name string
+ chunkHashes []string
+ expected string
+ expectError bool
+ }{
+ {
+ name: "two chunks in order",
+ chunkHashes: []string{chunk1, chunk2},
+ expected: "6d51edccc9c05a8b",
+ },
+ {
+ name: "order matters",
+ chunkHashes: []string{chunk2, chunk1},
+ expected: "596c127c7bcc8820",
+ },
+ {
+ name: "single chunk",
+ chunkHashes: []string{chunk1},
+ expected: "b73081dff8fe443c",
+ },
+ {
+ name: "mixed prefixes",
+ chunkHashes: []string{chunk1, "xxh3:" + chunk2, chunk1},
+ expected: "ca0b13abcdcd1661",
+ },
+ {
+ name: "no chunks",
+ chunkHashes: []string{},
+ expectError: true,
+ },
+ {
+ name: "invalid chunk hash",
+ chunkHashes: []string{chunk1, "notahexvalue"},
+ expectError: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ nested, err := NestedChunkHash(tt.chunkHashes)
+
+ if tt.expectError {
+ if err == nil {
+ t.Error("Expected error but got none")
+ }
+ return
+ }
+
+ if err != nil {
+ t.Fatalf("Unexpected error: %v", err)
+ }
+
+ if nested != tt.expected {
+ t.Errorf("NestedChunkHash: got %q, expected %q", nested, tt.expected)
+ }
+ })
+ }
+}
+
+func TestNestedChunkHashAcceptsPrefixedHashes(t *testing.T) {
+ plain := []string{"d447b1ea40e6988b", "2d06800538d394c2"}
+ prefixed := []string{"xxh3:d447b1ea40e6988b", "N:xxh3:2d06800538d394c2"}
+
+ gotPlain, err := NestedChunkHash(plain)
+ if err != nil {
+ t.Fatalf("Unexpected error: %v", err)
+ }
+ gotPrefixed, err := NestedChunkHash(prefixed)
+ if err != nil {
+ t.Fatalf("Unexpected error: %v", err)
+ }
+ if gotPlain != gotPrefixed {
+ t.Errorf("Prefixed hashes should give the same nested hash: %q != %q", gotPlain, gotPrefixed)
+ }
+}
diff --git a/backend/kdrive/multipart.go b/backend/kdrive/multipart.go
new file mode 100644
index 000000000..f94420b57
--- /dev/null
+++ b/backend/kdrive/multipart.go
@@ -0,0 +1,383 @@
+package kdrive
+
+import (
+ "context"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "path"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/rclone/rclone/backend/kdrive/api"
+ "github.com/rclone/rclone/backend/kdrive/khash"
+ "github.com/rclone/rclone/fs"
+ "github.com/rclone/rclone/fs/chunksize"
+ "github.com/rclone/rclone/lib/rest"
+ "github.com/zeebo/xxh3"
+ "golang.org/x/text/unicode/norm"
+)
+
+const (
+ // maxUploadParts is the maximum number of chunks the kDrive API accepts per file
+ maxUploadParts = 10000
+
+ // maxChunkSize is the largest chunk size the kDrive API accepts
+ maxChunkSize = 1 * 1000 * 1000 * 1000
+
+ // minChunkSize is the smallest chunk size the kDrive API accepts
+ minChunkSize = 1 * 1000 * 1000
+)
+
+// checkChunkSize checks the user supplied chunk_size against the
+// limits the kDrive API accepts
+func checkChunkSize(chunkSize fs.SizeSuffix) error {
+ if chunkSize < minChunkSize {
+ return fmt.Errorf("chunk_size %s is too small: the kDrive API requires chunks of at least 1 MB", chunkSize)
+ }
+ if chunkSize > maxChunkSize {
+ return fmt.Errorf("chunk_size %s is too large: the kDrive API accepts chunks of at most 1 GB (1000000000 bytes)", chunkSize)
+ }
+ return nil
+}
+
+// setChunkSize sets the chunk size, returning the old value
+func (f *Fs) setChunkSize(cs fs.SizeSuffix) (old fs.SizeSuffix, err error) {
+ err = checkChunkSize(cs)
+ if err == nil {
+ old, f.opt.ChunkSize = f.opt.ChunkSize, cs
+ }
+ return
+}
+
+// formatModTime formats the modification time of an upload as the
+// unix timestamp string the kDrive API expects
+func formatModTime(modTime time.Time) string {
+ return fmt.Sprintf("%d", modTime.Unix())
+}
+
+// uploadSession implements fs.ChunkWriter for kdrive multipart uploads
+type uploadSession struct {
+ f *Fs
+ token string
+ uploadURL string
+ fileInfo *api.Item
+ fileSize int64 // total size of the file being uploaded
+ chunkSize int64 // size of the chunks of this session
+
+ mu sync.Mutex
+ chunkHashes map[int64]string // chunk number -> hash of the chunk contents
+}
+
+// OpenChunkWriter returns the chunk size and a ChunkWriter
+//
+// Pass in the remote and the src object
+// You can also use options to hint at the desired chunk size
+// @see https://developer.infomaniak.com/docs/api/post/3/drive/%7Bdrive_id%7D/upload/session/start
+func (f *Fs) OpenChunkWriter(ctx context.Context, remote string, src fs.ObjectInfo, options ...fs.OpenOption) (info fs.ChunkWriterInfo, writer fs.ChunkWriter, err error) {
+ fileSize := src.Size()
+ if fileSize < 0 {
+ return info, nil, errors.New("kdrive can't upload files with unknown size")
+ }
+
+ dir, leaf := path.Split(remote)
+ dir = strings.TrimSuffix(dir, "/")
+
+ // Create parent directories if they don't exist
+ parentID, err := f.dirCache.FindDir(ctx, dir, true)
+ if err != nil {
+ return info, nil, fmt.Errorf("failed to find parent directory: %w", err)
+ }
+
+ // Calculate the chunk size, honouring any fs.ChunkOption hint
+ chunkSize := f.opt.ChunkSize
+ for _, opt := range options {
+ if chunkOpt, ok := opt.(*fs.ChunkOption); ok && chunkOpt.ChunkSize > 0 {
+ chunkSize = fs.SizeSuffix(chunkOpt.ChunkSize)
+ }
+ }
+ chunkSize = chunksize.Calculator(src, fileSize, maxUploadParts, chunkSize)
+ if chunkSize < minChunkSize {
+ chunkSize = minChunkSize
+ }
+ if chunkSize > maxChunkSize {
+ chunkSize = maxChunkSize
+ }
+
+ // Calculate the total number of chunks
+ totalChunks := max((fileSize+int64(chunkSize)-1)/int64(chunkSize), 1)
+
+ sessionReq := struct {
+ Conflict string `json:"conflict"`
+ DirectoryID string `json:"directory_id"`
+ FileName string `json:"file_name"`
+ LastModifiedAt string `json:"last_modified_at"`
+ TotalChunks int64 `json:"total_chunks"`
+ TotalSize int64 `json:"total_size"`
+ }{
+ Conflict: "version",
+ DirectoryID: parentID,
+ FileName: f.opt.Enc.FromStandardName(norm.NFC.String(leaf)),
+ LastModifiedAt: formatModTime(src.ModTime(ctx)),
+ TotalChunks: totalChunks,
+ TotalSize: fileSize,
+ }
+
+ // https://developer.infomaniak.com/docs/api/post/3/drive/%7Bdrive_id%7D/upload/session/start
+ opts := rest.Opts{
+ Method: "POST",
+ Path: fmt.Sprintf("/3/drive/%s/upload/session/start", f.opt.DriveID),
+ }
+ var sessionResp api.SessionStartResponse
+ var resp *http.Response
+ err = f.pacer.Call(func() (bool, error) {
+ var callErr error
+ resp, callErr = f.srv.CallJSON(ctx, &opts, &sessionReq, &sessionResp)
+ callErr = sessionResp.ResultStatus.Update(callErr)
+ return shouldRetry(ctx, resp, callErr)
+ })
+ if err != nil {
+ return info, nil, fmt.Errorf("failed to start upload session: %w", err)
+ }
+
+ info = fs.ChunkWriterInfo{
+ ChunkSize: int64(chunkSize),
+ Concurrency: f.opt.UploadConcurrency,
+ }
+
+ writer = &uploadSession{
+ f: f,
+ token: sessionResp.Data.Token,
+ uploadURL: sessionResp.Data.UploadURL,
+ fileSize: fileSize,
+ chunkSize: int64(chunkSize),
+ chunkHashes: make(map[int64]string),
+ }
+
+ fs.Debugf(f, "open chunk writer: started upload session for %d chunks of %v", totalChunks, chunkSize)
+ return info, writer, nil
+}
+
+// WriteChunk uploads a single chunk
+// @see https://developer.infomaniak.com/docs/api/post/3/drive/%7Bdrive_id%7D/upload/session/%7Bsession_token%7D/chunk
+func (u *uploadSession) WriteChunk(ctx context.Context, chunkNumber int, reader io.ReadSeeker) (bytesWritten int64, err error) {
+ if chunkNumber < 0 {
+ return -1, fmt.Errorf("invalid chunk number provided: %v", chunkNumber)
+ }
+
+ // Calculate the size of this chunk from the session parameters so
+ // the chunk can be streamed to the API in a single pass
+ chunkLen := u.chunkSize
+ if remaining := u.fileSize - int64(chunkNumber)*u.chunkSize; remaining < chunkLen {
+ chunkLen = remaining
+ }
+ if chunkLen <= 0 {
+ return 0, nil
+ }
+
+ sourceChunkNumber := chunkNumber + 1 // kDrive API uses 1-based numbering
+
+ // The chunk_hash parameter is optional, so the chunk is streamed
+ // in a single pass, hashing the contents on the way with a
+ // TeeReader. The server returns the hash of the chunk it received,
+ // which is checked below. Retries seek back to the chunk start
+ // and hash with a fresh hasher.
+ var chunkHash string
+ err = u.f.pacer.Call(func() (bool, error) {
+ if _, seekErr := reader.Seek(0, io.SeekStart); seekErr != nil {
+ return false, fmt.Errorf("failed to rewind chunk %d: %w", sourceChunkNumber, seekErr)
+ }
+ chunkHasher := xxh3.New()
+
+ // https://developer.infomaniak.com/docs/api/post/3/drive/%7Bdrive_id%7D/upload/session/%7Bsession_token%7D/chunk
+ chunkOpts := rest.Opts{
+ Method: "POST",
+ RootURL: u.uploadURL,
+ Path: fmt.Sprintf("/3/drive/%s/upload/session/%s/chunk", u.f.opt.DriveID, u.token),
+ Parameters: url.Values{
+ "chunk_number": {fmt.Sprintf("%d", sourceChunkNumber)},
+ "chunk_size": {fmt.Sprintf("%d", chunkLen)},
+ "with": {"hash"},
+ },
+ Body: io.TeeReader(reader, chunkHasher),
+ ContentLength: &chunkLen,
+ }
+
+ var chunkResp api.ChunkUploadResponse
+ resp, callErr := u.f.srv.CallJSON(ctx, &chunkOpts, nil, &chunkResp)
+ callErr = chunkResp.ResultStatus.Update(callErr)
+ if callErr != nil {
+ return shouldRetry(ctx, resp, callErr)
+ }
+
+ chunkHash = hex.EncodeToString(chunkHasher.Sum(nil))
+
+ // The server hashed the chunk it received, so compare with what we
+ // sent to detect any corruption immediately
+ if chunkResp.Data.Hash != "" {
+ if serverHash, _, parseErr := khash.ParseHash(chunkResp.Data.Hash); parseErr == nil {
+ if !strings.EqualFold(chunkHash, serverHash) {
+ return false, fmt.Errorf("chunk %d hash mismatch: client=%s, server=%s", sourceChunkNumber, chunkHash, serverHash)
+ }
+ } else {
+ fs.Debugf(u, "Failed to parse server chunk hash %q: %v", chunkResp.Data.Hash, parseErr)
+ }
+ }
+ return false, nil
+ })
+ if err != nil {
+ return -1, err
+ }
+
+ u.mu.Lock()
+ u.chunkHashes[int64(chunkNumber)] = chunkHash
+ u.mu.Unlock()
+
+ fs.Debugf(u, "uploaded chunk %d (size: %d, hash: %s)", sourceChunkNumber, chunkLen, chunkHash)
+ return chunkLen, nil
+}
+
+// Close finalizes the upload session, verifies the hash of the uploaded
+// file and returns the created file info
+// @see https://developer.infomaniak.com/docs/api/post/3/drive/%7Bdrive_id%7D/upload/session/%7Bsession_token%7D/finish
+func (u *uploadSession) Close(ctx context.Context) error {
+ // https://developer.infomaniak.com/docs/api/post/3/drive/%7Bdrive_id%7D/upload/session/%7Bsession_token%7D/finish
+ opts := rest.Opts{
+ Method: "POST",
+ Path: fmt.Sprintf("/3/drive/%s/upload/session/%s/finish", u.f.opt.DriveID, u.token),
+ }
+ var resp *http.Response
+ var finishResp api.SessionFinishResponse
+ err := u.f.pacer.Call(func() (bool, error) {
+ var callErr error
+ resp, callErr = u.f.srv.CallJSON(ctx, &opts, nil, &finishResp)
+ callErr = finishResp.ResultStatus.Update(callErr)
+ return shouldRetry(ctx, resp, callErr)
+ })
+ if err != nil {
+ return fmt.Errorf("failed to finish upload session: %w", err)
+ }
+
+ u.fileInfo = &finishResp.Data.File
+ fs.Debugf(u, "multipart upload completed: file id %d", finishResp.Data.File.ID)
+
+ return u.verifyHash(ctx)
+}
+
+// verifyHash checks the hash of the uploaded file against the hashes of
+// the chunks we uploaded, deleting the file if it is corrupted
+func (u *uploadSession) verifyHash(ctx context.Context) (err error) {
+ remoteHash := u.fileInfo.Hash
+ if remoteHash == "" {
+ // Hash might be missing in the finish response, try to fetch it
+ obj := &Object{
+ fs: u.f,
+ id: strconv.Itoa(u.fileInfo.ID),
+ }
+ var hashErr error
+ if remoteHash, hashErr = obj.retrieveHash(ctx); hashErr != nil {
+ // skip verification
+ fs.Debugf(u, "Failed to retrieve hash for verification: %v", hashErr)
+ return nil
+ }
+ }
+ parsedRemoteHash, isNested, err := khash.ParseHash(remoteHash)
+ if err != nil {
+ fs.Debugf(u, "Failed to parse server hash %q: %v", remoteHash, err)
+ return nil
+ }
+
+ u.mu.Lock()
+ defer u.mu.Unlock()
+
+ // Rebuild the hash the server should have stored from the chunk
+ // hashes we uploaded, in order
+ chunkCount := int64(len(u.chunkHashes))
+ if chunkCount == 0 {
+ return nil
+ }
+ chunkHashes := make([]string, 0, chunkCount)
+ for i := int64(0); i < chunkCount; i++ {
+ chunkHash, ok := u.chunkHashes[i]
+ if !ok {
+ fs.Debugf(u, "Chunk %d hash missing, skipping hash verification", i)
+ return nil
+ }
+ chunkHashes = append(chunkHashes, chunkHash)
+ }
+
+ var localHash string
+ if isNested {
+ if localHash, err = khash.NestedChunkHash(chunkHashes); err != nil {
+ fs.Debugf(u, "Failed to compute nested hash: %v", err)
+ return nil
+ }
+ } else if chunkCount == 1 {
+ localHash, _, _ = khash.ParseHash(chunkHashes[0])
+ } else {
+ // The server returned a simple hash for a multi chunk upload,
+ // nothing to compare it against
+ fs.Debugf(u, "Server returned a simple hash for a %d chunk upload, skipping hash verification", chunkCount)
+ return nil
+ }
+
+ if !strings.EqualFold(localHash, parsedRemoteHash) {
+ err = fmt.Errorf(
+ "multipart upload hash mismatch: local=%s, remote=%s",
+ localHash, parsedRemoteHash,
+ )
+
+ // Remove the corrupted file
+ obj := &Object{
+ fs: u.f,
+ id: strconv.Itoa(u.fileInfo.ID),
+ }
+ if delErr := obj.Remove(ctx); delErr != nil {
+ fs.Errorf(nil, "Failed to remove corrupted file after hash mismatch: %v", delErr)
+ } else {
+ fs.Debugf(nil, "Removed corrupted file after hash mismatch")
+ }
+
+ return err
+ }
+ fs.Debugf(u, "Multipart upload hash verified: %s", localHash)
+
+ return nil
+}
+
+// Abort the upload session
+// @see https://developer.infomaniak.com/docs/api/delete/2/drive/%7Bdrive_id%7D/upload/session/%7Bsession_token%7D
+func (u *uploadSession) Abort(ctx context.Context) error {
+ // https://developer.infomaniak.com/docs/api/delete/2/drive/%7Bdrive_id%7D/upload/session/%7Bsession_token%7D
+ opts := rest.Opts{
+ Method: "DELETE",
+ Path: fmt.Sprintf("/2/drive/%s/upload/session/%s", u.f.opt.DriveID, u.token),
+ }
+ var resp *http.Response
+ var cancelResp api.SessionCancelResponse
+ err := u.f.pacer.Call(func() (bool, error) {
+ var callErr error
+ resp, callErr = u.f.srv.CallJSON(ctx, &opts, nil, &cancelResp)
+ callErr = cancelResp.ResultStatus.Update(callErr)
+ return shouldRetry(ctx, resp, callErr)
+ })
+ if err != nil {
+ return fmt.Errorf("failed to cancel upload session: %w", err)
+ }
+
+ fs.Debugf(u, "upload session cancelled")
+ return nil
+}
+
+// String implements fmt.Stringer
+func (u *uploadSession) String() string {
+ return "kdrive upload session"
+}
+
+// Verify interface compliance
+var _ fs.ChunkWriter = (*uploadSession)(nil)
diff --git a/bin/make_manual.py b/bin/make_manual.py
index 5e514cbbe..ae99ad3e7 100755
--- a/bin/make_manual.py
+++ b/bin/make_manual.py
@@ -66,6 +66,7 @@ docs = [
"internetarchive.md",
"internxt.md",
"jottacloud.md",
+ "kdrive.md",
"koofr.md",
"linkbox.md",
"mailru.md",
diff --git a/docs/content/_index.md b/docs/content/_index.md
index 6bffa04a4..679f6f80e 100644
--- a/docs/content/_index.md
+++ b/docs/content/_index.md
@@ -166,6 +166,7 @@ WebDAV or S3, that work out of the box.)
{{< provider name="Impossible Cloud" home="https://www.impossiblecloud.com/" config="/s3/#impossible-cloud" >}}
{{< provider name="Intercolo Object Storage" home="https://intercolo.de/object-storage" config="/s3/#intercolo" >}}
{{< provider name="IONOS Cloud" home="https://cloud.ionos.com/storage/object-storage" config="/s3/#ionos" >}}
+{{< provider name="kDrive" home="https://www.infomaniak.com/en/ksuite/kdrive" config="/kdrive/" >}}
{{< provider name="Koofr" home="https://koofr.eu/" config="/koofr/" >}}
{{< provider name="Leviia Object Storage" home="https://www.leviia.com/object-storage" config="/s3/#leviia" >}}
{{< provider name="Liara Object Storage" home="https://liara.ir/landing/object-storage" config="/s3/#liara-cloud" >}}
diff --git a/docs/content/docs.md b/docs/content/docs.md
index 6d5321fc5..a2b681be9 100644
--- a/docs/content/docs.md
+++ b/docs/content/docs.md
@@ -65,6 +65,7 @@ See the following for detailed instructions for
- [Internet Archive](/internetarchive/)
- [Internxt](/internxt/)
- [Jottacloud](/jottacloud/)
+- [kDrive](/kdrive/)
- [Koofr](/koofr/)
- [Linkbox](/linkbox/)
- [Mail.ru Cloud](/mailru/)
diff --git a/docs/content/kdrive.md b/docs/content/kdrive.md
new file mode 100644
index 000000000..8bc4ea789
--- /dev/null
+++ b/docs/content/kdrive.md
@@ -0,0 +1,333 @@
+---
+title: "kDrive"
+description: "Rclone docs for kDrive"
+versionIntroduced: "v1.76"
+---
+
+# kDrive
+
+Paths are specified as `remote:path`
+
+Paths may be as deep as required, e.g. `remote:directory/subdirectory`.
+
+## Configuration
+
+The initial setup for kDrive involves getting an OAuth2 token which you
+need to do in your browser. `rclone config` walks you through it.
+
+kDrive uses the PKCE OAuth2 flow (RFC 7636), which means no
+`client_secret` is required. The `client_id` is optional and defaults
+to rclone's built-in application credentials.
+
+Here is an example of how to make a remote called `remote`. First run:
+
+```sh
+rclone config
+```
+
+This will guide you through an interactive setup process:
+
+```text
+No remotes found, make a new one?
+n) New remote
+s) Set configuration password
+q) Quit config
+n/s/q> n
+name> remote
+Type of storage to configure.
+Choose a number from below, or type in your own value
+[snip]
+XX / Infomaniak kDrive
+ \ "kdrive"
+[snip]
+Storage> kdrive
+
+Option client_id.
+OAuth Client Id.
+Leave blank normally.
+Enter a value. Press Enter to leave empty.
+client_id>
+
+Option drive_id.
+ID of the kDrive to use.
+When showing a folder on kdrive, you can find the drive_id here:
+https://ksuite.infomaniak.com/{account_id}/kdrive/app/drive/{drive_id}/files/...
+Enter a value. Press Enter to leave empty.
+drive_id> 0654321
+
+Use web browser to automatically authenticate rclone with remote?
+ * Say Y if the machine running rclone has a web browser you can use
+ * Say N if running rclone on a (remote) machine without web browser access
+If not sure try Y. If Y failed, try N.
+y/n> y
+
+Waiting for code...
+Got code
+
+Configuration complete.
+Options:
+- type: kdrive
+- drive_id: 0654321
+
+Keep this "remote" remote?
+y) Yes this is OK
+e) Edit this remote
+d) Delete this remote
+y/e/d> y
+```
+
+Once configured you can then use `rclone` like this (replace `remote` with the name you gave your remote):
+
+List directories in top level of your rclone
+
+```sh
+rclone lsd remote:
+```
+
+**Note** that by default the top level directory of a private kDrive
+storage is your "Private" folder. When used with a Pro account, a second
+folder "Common documents" is also available, which can be used as the
+root by setting `root_folder_id` to `common`.
+*These top-level folders cannot be modified*.
+
+List all the files in your kDrive
+
+```sh
+rclone ls remote:
+```
+
+To copy a local directory to a kDrive directory called backup
+
+```sh
+rclone copy /home/source remote:backup
+```
+
+### Modification times and hashes
+
+kDrive allows modification times to be set on objects accurate to 1
+second. These will be used to detect whether objects need syncing or
+not.
+
+kDrive supports the XXH3 checksum hash, so you can use the `--checksum`
+flag. XXH3 is only available for files uploaded as a single chunk:
+files uploaded in chunks (by rclone when larger than
+`--kdrive-chunk-size`, or by the kDrive apps which chunk files at their
+own sizes) have a "nested" hash which can't be compared with a plain
+XXH3, and rclone reports no hash for those files.
+
+### Restricted filename characters
+
+In addition to the [default restricted characters set](/overview/#restricted-characters)
+the following characters are also replaced:
+
+| Character | Value | Replacement |
+| ---------- |:-----:|:-----------:|
+| LeftSpace | 0x20 | ␠ |
+| RightSpace | 0x20 | ␠ |
+
+Invalid UTF-8 bytes will also be [replaced](/overview/#invalid-utf8),
+as they can't be used in JSON strings.
+
+### Overwriting files
+
+When rclone overwrites an existing file, kDrive keeps the replaced
+content as a new version of the file. Old versions count against the
+drive quota, so repeatedly overwriting large files grows the storage
+usage. Manage old versions from the kDrive web app.
+
+### Uploading files of unknown size
+
+kDrive can't upload files of unknown size, so `rclone rcat` and
+streaming uploads are not supported.
+
+### Deleting files
+
+Deleted files will be moved to the trash. Your subscription level
+will determine how long items stay in the trash. `rclone cleanup` can
+be used to empty the trash.
+
+### Root folder ID
+
+You can set the `root_folder_id` for rclone. This is the directory
+(identified by its numeric `Folder ID`) that rclone considers to be the
+root of your kDrive drive.
+
+Normally you will leave this blank and rclone will use your private
+directory. You can also use one of the convenience shortcuts:
+
+- `private`: your user private directory (default)
+- `common`: the kDrive common directory, shared among users
+
+Or the numeric `Folder ID` of any directory in your drive. The root of
+the drive only contains the `Private` and `Common documents` folders,
+so a numeric ID is needed to use any other directory as root. In order
+to find the `Folder ID`, list the parent directory of the folder you
+wish rclone to use with `rclone lsf`; the first column of the output is
+the folder ID:
+
+Example:
+```
+$ rclone lsf --dirs-only -Fip --csv remote:Documents
+456,Sub folder/
+789,Photos/
+```
+
+So if the folder you want rclone to use is "Photos/", then use the
+returned id from ```rclone lsf``` command (ex. `789`) as the
+`root_folder_id` variable value in the config file.
+
+<!-- autogenerated options start - DO NOT EDIT - instead edit fs.RegInfo in backend/kdrive/kdrive.go and run make backenddocs to verify --> <!-- markdownlint-disable-line line-length -->
+### Standard options
+
+Here are the Standard options specific to kdrive (Infomaniak kDrive).
+
+#### --kdrive-client-id
+
+OAuth Client Id.
+
+Leave blank normally.
+
+Properties:
+
+- Config: client_id
+- Env Var: RCLONE_KDRIVE_CLIENT_ID
+- Type: string
+- Required: false
+
+#### --kdrive-drive-id
+
+ID of the kDrive to use.
+
+When showing a folder on kdrive, you can find the drive_id here:
+https://ksuite.infomaniak.com/{account_id}/kdrive/app/drive/{drive_id}/files/...
+
+Properties:
+
+- Config: drive_id
+- Env Var: RCLONE_KDRIVE_DRIVE_ID
+- Type: string
+- Required: false
+
+### Advanced options
+
+Here are the Advanced options specific to kdrive (Infomaniak kDrive).
+
+#### --kdrive-token
+
+OAuth Access Token as a JSON blob.
+
+Properties:
+
+- Config: token
+- Env Var: RCLONE_KDRIVE_TOKEN
+- Type: string
+- Required: false
+
+#### --kdrive-auth-url
+
+Auth server URL.
+
+Leave blank to use the provider defaults.
+
+Properties:
+
+- Config: auth_url
+- Env Var: RCLONE_KDRIVE_AUTH_URL
+- Type: string
+- Required: false
+
+#### --kdrive-token-url
+
+Token server url.
+
+Leave blank to use the provider defaults.
+
+Properties:
+
+- Config: token_url
+- Env Var: RCLONE_KDRIVE_TOKEN_URL
+- Type: string
+- Required: false
+
+#### --kdrive-encoding
+
+The encoding for the backend.
+
+See the [encoding section in the overview](/overview/#encoding) for more info.
+
+Properties:
+
+- Config: encoding
+- Env Var: RCLONE_KDRIVE_ENCODING
+- Type: Encoding
+- Default: Slash,Del,Ctl,LeftSpace,RightSpace,InvalidUtf8,Dot
+
+#### --kdrive-root-folder-id
+
+The folder to use as root.
+
+You may use either one of the convenience shortcuts [private or common]
+or an explicit folder ID.
+
+- private: your user private directory
+- common: the kDrive common directory, shared among users
+
+Properties:
+
+- Config: root_folder_id
+- Env Var: RCLONE_KDRIVE_ROOT_FOLDER_ID
+- Type: string
+- Required: false
+
+#### --kdrive-chunk-size
+
+Files above this size are uploaded in chunks of this size.
+
+The kDrive API accepts chunks between 1 MB and 1 GB, up to 10,000
+chunks per file and a total file size of 1 TiB. The chunk size is
+raised automatically for very large files to stay within the 10,000
+chunks limit.
+
+Properties:
+
+- Config: chunk_size
+- Env Var: RCLONE_KDRIVE_CHUNK_SIZE
+- Type: SizeSuffix
+- Default: 20Mi
+
+#### --kdrive-upload-concurrency
+
+Concurrency for chunked uploads.
+
+Properties:
+
+- Config: upload_concurrency
+- Env Var: RCLONE_KDRIVE_UPLOAD_CONCURRENCY
+- Type: int
+- Default: 4
+
+#### --kdrive-endpoint
+
+The API endpoint to use.
+
+Leave blank normally. There is no reason to change the endpoint except for internal use or beta-testing.
+
+Properties:
+
+- Config: endpoint
+- Env Var: RCLONE_KDRIVE_ENDPOINT
+- Type: string
+- Required: false
+
+#### --kdrive-description
+
+Description of the remote.
+
+Properties:
+
+- Config: description
+- Env Var: RCLONE_KDRIVE_DESCRIPTION
+- Type: string
+- Required: false
+
+<!-- autogenerated options stop -->
diff --git a/docs/data/backends/kdrive.yaml b/docs/data/backends/kdrive.yaml
new file mode 100644
index 000000000..0e42fa940
--- /dev/null
+++ b/docs/data/backends/kdrive.yaml
@@ -0,0 +1,29 @@
+backend: kdrive
+name: kdrive
+tier: Tier 2
+maintainers: Community
+features_score: 5
+integration_tests: Unknown
+data_integrity: Unknown
+performance: Unknown
+adoption: Rare
+docs: Basic
+security: Unknown
+virtual: false
+remote: 'TestKdrive:'
+features:
+- About
+- CanHaveEmptyDirectories
+- CleanUp
+- Copy
+- DirCacheFlush
+- DirMove
+- ListP
+- ListR
+- Move
+- OpenChunkWriter
+- PublicLink
+- Purge
+hashes:
+- xxh3
+precision: 1000000000
diff --git a/docs/layouts/chrome/navbar.html b/docs/layouts/chrome/navbar.html
index cff6fa02d..4ff5727b4 100644
--- a/docs/layouts/chrome/navbar.html
+++ b/docs/layouts/chrome/navbar.html
@@ -95,6 +95,7 @@
<a class="dropdown-item" href="/internxt/">Internxt</a>
<span class="dropdown-letter-heading">J &ndash; M</span>
<a class="dropdown-item" href="/jottacloud/">Jottacloud</a>
+ <a class="dropdown-item" href="/kdrive/">kDrive</a>
<a class="dropdown-item" href="/koofr/">Koofr</a>
<a class="dropdown-item" href="/linkbox/">Linkbox</a>
<a class="dropdown-item" href="/mailru/">Mail.ru Cloud</a>
diff --git a/fstest/fstests/fstests.go b/fstest/fstests/fstests.go
index 48d21561d..189f5e971 100644
--- a/fstest/fstests/fstests.go
+++ b/fstest/fstests/fstests.go
@@ -2181,6 +2181,11 @@ func Run(t *testing.T, opt *Opt) {
t.Log("treating accountUpgradeRequired as success for PublicLink")
link, err = "bogus link to "+remote, nil
}
+ // For Kdrive, link expiry is a premium feature
+ if fsInfo.Name == "kdrive" && strings.Contains(err.Error(), "forbidden_error") && strings.Contains(err.Error(), "expiration date") {
+ t.Log("treating forbidden on expiration date as success for PublicLink")
+ link, err = "bogus link to "+remote, nil
+ }
return
}
}
diff --git a/fstest/test_all/config.yaml b/fstest/test_all/config.yaml
index 5d468ba8a..0b7c08c9b 100644
--- a/fstest/test_all/config.yaml
+++ b/fstest/test_all/config.yaml
@@ -762,3 +762,12 @@ backends:
fastlist: false
extratime: 2.0
listretries: 5
+ - backend: "kdrive"
+ remote: "TestKdrive:"
+ ignore:
+ # The bisync normalization test fails as the kDrive server normalizes file names to NFC
+ - TestBisyncRemoteRemote/normalization
+ # the dates used in TestIndexChangedDirTime are far away in the future, this isn't handled by kdrive
+ - TestIndexChangedDirTime
+ fastlist: true
+ extratime: 2.0