diff options
author | Gabriel Arakaki Giovanini <mail@gabrielgio.me> | 2022-10-16 19:13:41 +0200 |
---|---|---|
committer | Gabriel Arakaki Giovanini <mail@gabrielgio.me> | 2022-10-16 19:16:35 +0200 |
commit | eb1b7d7d9149114eb6b4287b7cb40c49dccfb26e (patch) | |
tree | 12f797651abeda9512d56d8922199ae9edb2a293 /storage/storage_wd.go | |
parent | 98844247a424558939228b82e9b5f28d723c4fe0 (diff) | |
download | porg-master.tar.gz porg-master.tar.bz2 porg-master.zip |
With this is easier to interact with storage layers.
Diffstat (limited to 'storage/storage_wd.go')
-rw-r--r-- | storage/storage_wd.go | 114 |
1 files changed, 114 insertions, 0 deletions
diff --git a/storage/storage_wd.go b/storage/storage_wd.go new file mode 100644 index 0000000..b166992 --- /dev/null +++ b/storage/storage_wd.go @@ -0,0 +1,114 @@ +package storage + +import ( + "errors" + "io" + "os" + + "github.com/studio-b12/gowebdav" +) + +type WebDav struct { + client *gowebdav.Client +} + +func NewWebDavStorage(root string, username string, password string) *WebDav { + c := gowebdav.NewClient(root, username, password) + return &WebDav{client: c} +} + +func (wd *WebDav) Mkdir(path string) error { + if err := wd.client.MkdirAll(path, 0644); err != nil { + return err + } + return nil +} + +func (wd *WebDav) Put(path string, f io.Reader) error { + return wd.client.WriteStream(path, f, 0644) +} + +func (wd *WebDav) Move(src string, dest string) error { + if src != dest { + if err := wd.client.Rename(src, dest, true); err != nil { + return nil + } + } + return nil +} + +func (wd *WebDav) Exists(path string) (bool, error) { + _, err := wd.client.Stat(path) + if err == nil { + return true, nil + } + if errors.Is(err, os.ErrNotExist) { + return false, nil + } + return false, err +} + +func (wd *WebDav) Copy(src string, dest string) error { + if src != dest { + if err := wd.client.Copy(src, dest, true); err != nil { + return nil + } + } + return nil +} + +func (wd *WebDav) Get(path string) (io.Reader, error) { + return wd.client.ReadStream(path) +} + +func (wd *WebDav) List(path string) ([]string, error) { + files, err := wd.client.ReadDir(path) + if err != nil { + return nil, err + } + + r := make([]string, len(files)) + + for i, v := range files { + r[i] = v.Name() + } + + return r, nil +} + +func (wd *WebDav) Walk(folder string, walkMode WalkMode) <-chan string { + c := make(chan string) + + go func(string, chan string) { + var queue []string + queue = append(queue, folder) + + for len(queue) > 0 { + f := queue[0] + queue = queue[1:] + + files, _ := wd.client.ReadDir(f) + for _, fileInfo := range files { + if fileInfo.IsDir() { + queue = append(queue, f+"/"+fileInfo.Name()) + } + + switch walkMode { + case Folder: + if fileInfo.IsDir() { + c <- f + "/" + fileInfo.Name() + } + case File: + if !fileInfo.IsDir() { + c <- f + "/" + fileInfo.Name() + } + case FileFolder: + c <- f + "/" + fileInfo.Name() + } + } + } + close(c) + }(folder, c) + + return c +} |