aboutsummaryrefslogtreecommitdiff
path: root/storage/storage_wd.go
blob: b16699215d39941747d05865fb8adec99b039c81 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
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
}