103 lines
2 KiB
Go
103 lines
2 KiB
Go
package file
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"fmt"
|
|
"math"
|
|
"math/big"
|
|
"os"
|
|
|
|
"github.com/gabriel-vasile/mimetype"
|
|
)
|
|
|
|
type File struct {
|
|
Id string `json:"id"`
|
|
Name string `json:"name"`
|
|
Path string `json:"path"`
|
|
Size int64 `json:"size"`
|
|
Type string `json:"type"`
|
|
Extension string `json:"extension"`
|
|
}
|
|
|
|
type Tree struct {
|
|
Name string `json:"name"`
|
|
Directories []Tree `json:"directories"`
|
|
Path string `json:"path"`
|
|
Files []File `json:"files"`
|
|
IsRoot bool `json:"is_root"`
|
|
}
|
|
|
|
func getFileId(path string) string {
|
|
hash := sha256.New()
|
|
hash.Write([]byte(path))
|
|
hashBytes := hash.Sum(nil)
|
|
bInt := new(big.Int).SetBytes(hashBytes)
|
|
|
|
return fmt.Sprintf("%d", int(math.Abs(float64(bInt.Int64()))))
|
|
}
|
|
|
|
func GetTree(name, path string) Tree {
|
|
tree := Tree{
|
|
Name: name,
|
|
Directories: []Tree{},
|
|
Path: path,
|
|
Files: []File{},
|
|
IsRoot: name == "",
|
|
}
|
|
entries, err := os.ReadDir(path)
|
|
|
|
if err != nil {
|
|
return tree
|
|
}
|
|
|
|
for _, e := range entries {
|
|
if e.IsDir() {
|
|
tree.Directories = append(tree.Directories, GetTree(e.Name(), path+"/"+e.Name()))
|
|
} else {
|
|
p := path + "/" + e.Name()
|
|
fi, _ := os.Stat(p)
|
|
mtype, _ := mimetype.DetectFile(p)
|
|
|
|
tree.Files = append(tree.Files, File{
|
|
Id: getFileId(p),
|
|
Name: e.Name(),
|
|
Path: p,
|
|
Size: fi.Size(),
|
|
Type: mtype.Extension(),
|
|
Extension: mtype.Extension(),
|
|
})
|
|
}
|
|
}
|
|
|
|
return tree
|
|
}
|
|
|
|
func GetFiles(files *[]File, path string) *[]File {
|
|
entries, err := os.ReadDir(path)
|
|
|
|
if err != nil {
|
|
return files
|
|
}
|
|
|
|
for _, e := range entries {
|
|
p := path + "/" + e.Name()
|
|
|
|
if e.IsDir() {
|
|
GetFiles(files, p)
|
|
} else {
|
|
fi, _ := os.Stat(p)
|
|
mtype, _ := mimetype.DetectFile(p)
|
|
|
|
*files = append(*files, File{
|
|
Id: getFileId(p),
|
|
Name: e.Name(),
|
|
Path: p,
|
|
Size: fi.Size(),
|
|
Type: mtype.Extension(),
|
|
Extension: mtype.Extension(),
|
|
})
|
|
}
|
|
}
|
|
|
|
return files
|
|
}
|