zrok/util/sync/webdav.go

79 lines
1.6 KiB
Go
Raw Normal View History

2023-11-27 21:44:38 +01:00
package sync
import (
"context"
2023-12-14 20:25:24 +01:00
"github.com/openziti/zrok/environment/env_core"
"github.com/openziti/zrok/util/sync/driveClient"
2023-11-27 23:31:13 +01:00
"io"
"net/http"
2023-12-14 20:25:24 +01:00
"net/url"
2023-11-27 23:31:13 +01:00
"os"
2023-11-28 03:11:19 +01:00
"time"
2023-11-27 21:44:38 +01:00
)
type WebDAVTargetConfig struct {
2023-12-14 20:25:24 +01:00
URL *url.URL
2023-11-27 21:44:38 +01:00
Username string
Password string
2023-12-14 20:25:24 +01:00
Root env_core.Root
2023-11-27 21:44:38 +01:00
}
type WebDAVTarget struct {
cfg *WebDAVTargetConfig
dc *driveClient.Client
isDir bool
2023-11-27 21:44:38 +01:00
}
func NewWebDAVTarget(cfg *WebDAVTargetConfig) (*WebDAVTarget, error) {
dc, err := driveClient.NewClient(http.DefaultClient, cfg.URL.String())
2023-12-14 20:25:24 +01:00
if err != nil {
return nil, err
}
return &WebDAVTarget{cfg: cfg, dc: dc}, nil
2023-11-27 21:44:38 +01:00
}
func (t *WebDAVTarget) Inventory() ([]*Object, error) {
fis, err := t.dc.Readdir(context.Background(), "", true)
2023-11-27 21:44:38 +01:00
if err != nil {
return nil, err
}
var objects []*Object
for _, fi := range fis {
if fi.Path != "/" {
objects = append(objects, &Object{
Path: fi.Path,
IsDir: fi.IsDir,
Size: fi.Size,
Modified: fi.ModTime,
ETag: fi.ETag,
})
2023-11-27 21:44:38 +01:00
}
}
return objects, nil
2023-11-27 21:44:38 +01:00
}
2023-11-27 23:31:13 +01:00
func (t *WebDAVTarget) Mkdir(path string) error {
return t.dc.Mkdir(context.Background(), path)
}
2023-11-27 23:31:13 +01:00
func (t *WebDAVTarget) ReadStream(path string) (io.ReadCloser, error) {
return t.dc.Open(context.Background(), path)
2023-11-27 23:31:13 +01:00
}
2023-11-28 03:11:19 +01:00
func (t *WebDAVTarget) WriteStream(path string, rs io.Reader, _ os.FileMode) error {
ws, err := t.dc.Create(context.Background(), path)
if err != nil {
return err
}
defer func() { _ = ws.Close() }()
_, err = io.Copy(ws, rs)
if err != nil {
return err
}
2023-11-28 03:11:19 +01:00
return nil
}
func (t *WebDAVTarget) SetModificationTime(path string, mtime time.Time) error {
return t.dc.Touch(context.Background(), path, mtime)
}