|
| 1 | +package common |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "files/pkg/errors" |
| 6 | + "files/pkg/files" |
| 7 | + "files/pkg/fileutils" |
| 8 | + "files/pkg/preview" |
| 9 | + "fmt" |
| 10 | + "github.com/spf13/afero" |
| 11 | + "path" |
| 12 | + "path/filepath" |
| 13 | + "strings" |
| 14 | +) |
| 15 | + |
| 16 | +func CheckParent(src, dst string) error { |
| 17 | + rel, err := filepath.Rel(src, dst) |
| 18 | + if err != nil { |
| 19 | + return err |
| 20 | + } |
| 21 | + |
| 22 | + rel = filepath.ToSlash(rel) |
| 23 | + if !strings.HasPrefix(rel, "../") && rel != ".." && rel != "." { |
| 24 | + return errors.ErrSourceIsParent |
| 25 | + } |
| 26 | + |
| 27 | + return nil |
| 28 | +} |
| 29 | + |
| 30 | +func AddVersionSuffix(source string, fs afero.Fs, isDir bool) string { |
| 31 | + counter := 1 |
| 32 | + dir, name := path.Split(source) |
| 33 | + ext := "" |
| 34 | + base := name |
| 35 | + if !isDir { |
| 36 | + ext = filepath.Ext(name) |
| 37 | + base = strings.TrimSuffix(name, ext) |
| 38 | + } |
| 39 | + |
| 40 | + for { |
| 41 | + if _, err := fs.Stat(source); err != nil { |
| 42 | + break |
| 43 | + } |
| 44 | + renamed := fmt.Sprintf("%s(%d)%s", base, counter, ext) |
| 45 | + source = path.Join(dir, renamed) |
| 46 | + counter++ |
| 47 | + } |
| 48 | + |
| 49 | + return source |
| 50 | +} |
| 51 | + |
| 52 | +func PatchAction(ctx context.Context, action, src, dst string, fileCache fileutils.FileCache) error { |
| 53 | + switch action { |
| 54 | + case "copy": |
| 55 | + return fileutils.Copy(files.DefaultFs, src, dst) |
| 56 | + case "rename": |
| 57 | + src = path.Clean("/" + src) |
| 58 | + dst = path.Clean("/" + dst) |
| 59 | + |
| 60 | + file, err := files.NewFileInfo(files.FileOptions{ |
| 61 | + Fs: files.DefaultFs, |
| 62 | + Path: src, |
| 63 | + Modify: true, |
| 64 | + Expand: false, |
| 65 | + ReadHeader: false, |
| 66 | + }) |
| 67 | + if err != nil { |
| 68 | + return err |
| 69 | + } |
| 70 | + |
| 71 | + // delete thumbnails |
| 72 | + err = preview.DelThumbs(ctx, fileCache, file) |
| 73 | + if err != nil { |
| 74 | + return err |
| 75 | + } |
| 76 | + |
| 77 | + return fileutils.MoveFile(files.DefaultFs, src, dst) |
| 78 | + default: |
| 79 | + return fmt.Errorf("unsupported action %s: %w", action, errors.ErrInvalidRequestParams) |
| 80 | + } |
| 81 | +} |
0 commit comments