personal-website/webfilesystem/directory.go

85 lines
1.9 KiB
Go
Raw Normal View History

2023-05-05 14:44:03 +00:00
package webfilesystem
import (
2023-05-05 18:32:41 +00:00
"context"
"strconv"
2023-05-05 14:44:03 +00:00
"github.com/mitchellh/mapstructure"
2023-05-05 18:32:41 +00:00
"go.mongodb.org/mongo-driver/bson"
2023-05-05 14:44:03 +00:00
"go.mongodb.org/mongo-driver/bson/primitive"
)
type DirectoryData struct {
Parent primitive.ObjectID `bson:"parent"`
Children []primitive.ObjectID `bson:"children"`
}
2023-05-05 18:32:41 +00:00
func (fs *WebFileSystem) NewCreateDirectory(dirPath string) (primitive.ObjectID, error) {
splittedPath := fs.SplitPath(dirPath)
parentPath := fs.GetParentPath(dirPath)
parentDirRaw, err := fs.NewRead(parentPath)
if err != nil {
return primitive.NilObjectID, err
}
newDir := WebFSFile{
MongoId: primitive.NewObjectID(),
Name: splittedPath[len(splittedPath)-1],
Type: "directory",
Data: DirectoryData{
Parent: parentDirRaw.MongoId,
Children: []primitive.ObjectID{},
},
Icon: "",
}
objectId, err := fs.writeMongo(newDir, parentPath)
if err != nil {
return primitive.NilObjectID, err
}
2023-05-05 14:44:03 +00:00
2023-05-05 18:32:41 +00:00
return objectId, nil
}
func (fs *WebFileSystem) validateDir(dir *WebFSFile) error {
kek := dir.Data.(primitive.D).Map()["children"].(primitive.A)
_ = kek
children := []primitive.ObjectID{}
counter := 0
for _, v := range kek {
_, err := fs.ReadByObjectID(v.(primitive.ObjectID))
if err != nil {
counter++
} else {
children = append(children, v.(primitive.ObjectID))
}
}
if counter > 0 {
println(dir.Name + " broken iDs: " + strconv.Itoa(counter))
_, err := fs.webfsCollection.UpdateByID(context.Background(), dir.MongoId, bson.M{"$set": bson.M{"data.children": children}})
if err != nil {
println(err.Error())
return err
}
}
return nil
}
2023-05-05 14:44:03 +00:00
func castToFile(raw *interface{}) *WebFSFile {
var dirPtr interface{} = *raw
return dirPtr.(*WebFSFile)
}
2023-05-05 18:32:41 +00:00
func castToDirectoryData(data interface{}) (*DirectoryData, error) {
dirData := DirectoryData{}
2023-05-05 14:44:03 +00:00
err := mapstructure.Decode(data.(primitive.D).Map(), &dirData)
if err != nil {
return nil, err
}
return &dirData, nil
}
// func List()