Improved filebrowser (#52)

* file archive refactor, list dir perf optimization

* code refactoring
This commit is contained in:
Marco
2023-05-26 11:10:10 +02:00
committed by GitHub
parent 8cf130ec23
commit 5b70d25bef
7 changed files with 120 additions and 96 deletions

View File

@@ -12,49 +12,67 @@ import (
"github.com/gofiber/fiber/v2"
"github.com/marcopeocchi/yt-dlp-web-ui/server/config"
"golang.org/x/exp/slices"
)
type DirectoryEntry struct {
Name string `json:"name"`
Path string `json:"path"`
SHASum string `json:"shaSum"`
Name string `json:"name"`
Path string `json:"path"`
SHASum string `json:"shaSum"`
IsDirectory bool `json:"isDirectory"`
}
func isValidEntry(d fs.DirEntry) bool {
return !d.IsDir() &&
!strings.HasPrefix(d.Name(), ".") &&
return !strings.HasPrefix(d.Name(), ".") &&
!strings.HasSuffix(d.Name(), ".part") &&
!strings.HasSuffix(d.Name(), ".ytdl")
}
func shaSumString(path string) string {
h := sha256.New()
h.Write([]byte(path))
return hex.EncodeToString(h.Sum(nil))
}
func walkDir(root string) (*[]DirectoryEntry, error) {
files := []DirectoryEntry{}
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if isValidEntry(d) {
h := sha256.New()
h.Write([]byte(path))
dirs, err := os.ReadDir(root)
if err != nil {
return nil, err
}
files = append(files, DirectoryEntry{
Path: path,
Name: d.Name(),
SHASum: hex.EncodeToString(h.Sum(nil)),
})
for _, d := range dirs {
if !isValidEntry(d) {
continue
}
return nil
})
path := filepath.Join(root, d.Name())
files = append(files, DirectoryEntry{
Path: path,
Name: d.Name(),
SHASum: shaSumString(path),
IsDirectory: d.IsDir(),
})
}
return &files, err
}
type ListRequest struct {
SubDir string `json:"subdir"`
}
func ListDownloaded(ctx *fiber.Ctx) error {
root := config.Instance().GetConfig().DownloadPath
req := new(ListRequest)
files, err := walkDir(root)
err := ctx.BodyParser(req)
if err != nil {
return err
}
files, err := walkDir(filepath.Join(root, req.SubDir))
if err != nil {
return err
}
@@ -73,30 +91,18 @@ func DeleteFile(ctx *fiber.Ctx) error {
return err
}
root := config.Instance().GetConfig().DownloadPath
sum := shaSumString(req.Path)
if sum != req.SHASum {
return errors.New("shasum mismatch")
}
files, err := walkDir(root)
err = os.Remove(req.Path)
if err != nil {
return err
}
index := slices.IndexFunc(*files, func(e DirectoryEntry) bool {
return e.Path == req.Path && e.SHASum == req.SHASum
})
if index == -1 {
ctx.SendString("shasum doesn't match")
}
if index >= 0 {
err := os.Remove(req.Path)
if err != nil {
return err
}
}
ctx.Status(fiber.StatusOK)
return ctx.JSON(index)
return ctx.JSON("ok")
}
type PlayRequest struct {