67 lines
1.5 KiB
Go
67 lines
1.5 KiB
Go
package libraries
|
|
|
|
import (
|
|
"errors"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"ddc/internal/diskspace"
|
|
)
|
|
|
|
var ErrUnknownDestination = errors.New("destination is not a first level folder of a library root")
|
|
|
|
type Destination struct {
|
|
Name string `json:"name"`
|
|
Root string `json:"root"`
|
|
Path string `json:"path"`
|
|
FreeBytes int64 `json:"freeBytes"`
|
|
}
|
|
|
|
func Discover(roots []string) []Destination {
|
|
destinations := []Destination{}
|
|
for _, root := range roots {
|
|
entries, err := os.ReadDir(root)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
for _, entry := range entries {
|
|
if !entry.IsDir() || strings.HasPrefix(entry.Name(), ".") {
|
|
continue
|
|
}
|
|
path := filepath.Join(root, entry.Name())
|
|
freeBytes, err := diskspace.Available(path)
|
|
if err != nil {
|
|
freeBytes = -1
|
|
}
|
|
destinations = append(destinations, Destination{
|
|
Name: entry.Name(),
|
|
Root: root,
|
|
Path: path,
|
|
FreeBytes: freeBytes,
|
|
})
|
|
}
|
|
}
|
|
return destinations
|
|
}
|
|
|
|
func Resolve(roots []string, requested string) (Destination, error) {
|
|
cleaned := filepath.Clean(requested)
|
|
name := filepath.Base(cleaned)
|
|
if strings.HasPrefix(name, ".") {
|
|
return Destination{}, ErrUnknownDestination
|
|
}
|
|
|
|
for _, root := range roots {
|
|
if filepath.Dir(cleaned) != root {
|
|
continue
|
|
}
|
|
info, err := os.Lstat(cleaned)
|
|
if err != nil || !info.IsDir() {
|
|
return Destination{}, ErrUnknownDestination
|
|
}
|
|
return Destination{Name: name, Root: root, Path: cleaned}, nil
|
|
}
|
|
return Destination{}, ErrUnknownDestination
|
|
}
|