github.com/cs3org/reva/v2@v2.27.7/internal/http/services/owncloud/ocdav/filedrop.go (about)

     1  package ocdav
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"path/filepath"
     7  	"strconv"
     8  	"strings"
     9  
    10  	gatewayv1beta1 "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
    11  	rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
    12  	provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
    13  )
    14  
    15  // FindName returns the next filename available when the current
    16  func FindName(ctx context.Context, client gatewayv1beta1.GatewayAPIClient, name string, parentid *provider.ResourceId) (string, *rpc.Status, error) {
    17  	lReq := &provider.ListContainerRequest{
    18  		Ref: &provider.Reference{
    19  			ResourceId: parentid,
    20  		},
    21  	}
    22  	lRes, err := client.ListContainer(ctx, lReq)
    23  	if err != nil {
    24  		return "", nil, err
    25  	}
    26  	if lRes.Status.Code != rpc.Code_CODE_OK {
    27  		return "", lRes.Status, nil
    28  	}
    29  	// iterate over the listing to determine next suffix
    30  	var itemMap = make(map[string]struct{})
    31  	for _, fi := range lRes.Infos {
    32  		itemMap[fi.GetName()] = struct{}{}
    33  	}
    34  	ext := filepath.Ext(name)
    35  	fileName := strings.TrimSuffix(name, ext)
    36  	if strings.HasSuffix(fileName, ".tar") {
    37  		fileName = strings.TrimSuffix(fileName, ".tar")
    38  		ext = filepath.Ext(fileName) + "." + ext
    39  	}
    40  	// starts with two because "normal" humans begin counting with 1 and we say the existing file is the first one
    41  	for i := 2; i < len(itemMap)+3; i++ {
    42  		if _, ok := itemMap[fileName+" ("+strconv.Itoa(i)+")"+ext]; !ok {
    43  			return fileName + " (" + strconv.Itoa(i) + ")" + ext, lRes.GetStatus(), nil
    44  		}
    45  	}
    46  	return "", nil, errors.New("could not determine new filename")
    47  }