golang-snippets/webdav2archive/main.go

95 lines
2.1 KiB
Go

package main
import (
"flag"
"fmt"
"io"
"os"
"path"
"strconv"
"sync"
"github.com/bdlm/log"
"github.com/studio-b12/gowebdav"
)
var (
root = "https://cloud.sum7.eu/remote.php/webdav/"
user = "genofire"
password = os.Getenv("WEBDAV_PASSWORD")
fromDir = "AutoUpload"
exportDir = "download"
deleteOnDownload = false
client *gowebdav.Client
wg = &sync.WaitGroup{}
)
func handleFile(file os.FileInfo) {
defer wg.Done()
filepath := path.Join(fromDir, file.Name())
logger := log.WithField("from", filepath)
mtime := file.ModTime()
exportpathDir := path.Join(exportDir, strconv.Itoa(mtime.Year()), fmt.Sprintf("%.2d", mtime.Month()))
os.MkdirAll(exportpathDir, os.ModePerm)
exportpath := path.Join(exportpathDir, file.Name())
logger = logger.WithField("to", exportpath)
reader, _ := client.ReadStream(filepath)
f, err := os.Create(exportpath)
if err != nil {
logger.Warnf("unable to create dest: %s", err)
return
}
defer f.Close()
if _, err = io.Copy(f, reader); err != nil {
logger.Warnf("unable to download: %s", err)
return
}
if deleteOnDownload {
if err = client.Remove(filepath); err != nil {
logger.Warnf("unable to remove: %s", err)
return
}
logger = logger.WithField("deleted", true)
}
logger.Info("downloaded")
}
func main() {
flag.StringVar(&user, "u", user, "username to auth at webdav server")
flag.StringVar(&password, "p", password, "password to auth at webdav server (use environment variable WEBDAV_PASSWORD for security reasen)")
flag.StringVar(&root, "h", root, "address of webdav server")
flag.StringVar(&fromDir, "i", fromDir, "import path from webdave")
flag.StringVar(&exportDir, "e", exportDir, "export path on local")
flag.BoolVar(&deleteOnDownload, "f", deleteOnDownload, "delete on download")
flag.Parse()
client = gowebdav.NewClient(root, user, password)
if client == nil {
log.Panic("cloud not connect to webdav client")
}
files, _ := client.ReadDir(fromDir)
for _, file := range files {
if file.IsDir() {
continue
}
wg.Add(1)
go handleFile(file)
}
wg.Wait()
log.Info("done")
}