From 313be711a9bf1e07e6f74bfcc5bc6e47eca96c18 Mon Sep 17 00:00:00 2001 From: cyber-dream Date: Thu, 4 May 2023 18:55:08 +0300 Subject: [PATCH] Mongo directories validation --- webfilesystem/webfilesystem.go | 75 ++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/webfilesystem/webfilesystem.go b/webfilesystem/webfilesystem.go index 1fc56ab..6dfdbc0 100644 --- a/webfilesystem/webfilesystem.go +++ b/webfilesystem/webfilesystem.go @@ -4,6 +4,7 @@ import ( "context" "errors" "net/http" + "strconv" "strings" "github.com/gin-gonic/gin" @@ -242,6 +243,80 @@ func (fs *WebFileSystem) Route(route *gin.RouterGroup) { ctx.JSON(http.StatusOK, &file) }) + + route.GET("validate", func(ctx *gin.Context) { + err := fs.Validate() + if err != nil { + ctx.Status(http.StatusInternalServerError) + return + } + + ctx.Status(http.StatusOK) + }) +} + +func (fs *WebFileSystem) Validate() error { + filter := primitive.D{ + { + Key: "type", + Value: "directory", + }, + } + cur, err := fs.webfsCollection.Find(context.Background(), filter) + defer cur.Close(context.Background()) + if err != nil { + return err + } + + directories := []*WebFSFile{} + // err = cur.All(context.Background(), directories) + // if err != nil { + // fmt.Println(err.Error()) + // } + for cur.Next(context.Background()) { + dir := &WebFSFile{} + + err = cur.Decode(dir) + if err != nil { + println(err.Error()) + return err + } + directories = append(directories, dir) + } + + for _, d := range directories { + // println(d.Name) + fs.validateDir(d) + } + return nil +} + +func (fs *WebFileSystem) validateDir(dir *WebFSFile) error { + kek := dir.Data.(primitive.D).Map()["children"].(primitive.A) + _ = kek + + // FolderData + children := []primitive.ObjectID{} + counter := 0 + for _, v := range kek { + // println(v.(primitive.ObjectID).String()) + _, 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 } type WebFSFile struct {