Port code base to new fs version

This commit is contained in:
cyber-dream 2023-05-07 04:00:22 +03:00
parent 6c3bc32b59
commit 0ceae10530
17 changed files with 404 additions and 1036 deletions

View File

@ -33,15 +33,19 @@ func (b *BlogViewerApplication) GetId() string {
} }
func (b *BlogViewerApplication) Route(route *gin.RouterGroup) { func (b *BlogViewerApplication) Route(route *gin.RouterGroup) {
// route.GET("writeMockBlog", func(ctx *gin.Context) { route.GET("writeMockBlog", func(ctx *gin.Context) {
// path := ctx.Query("path") path := ctx.Query("path")
// if path == "" { if path == "" {
// ctx.JSON(http.StatusBadRequest, "no path provided") ctx.JSON(http.StatusBadRequest, "no path provided")
// return return
// } }
// b.WriteMock(path) err := b.WriteMock(path)
// ctx.JSON(http.StatusOK, "OK") if err != nil {
// }) ctx.Status(http.StatusInternalServerError)
return
}
ctx.JSON(http.StatusOK, "OK")
})
route.GET("render", func(ctx *gin.Context) { route.GET("render", func(ctx *gin.Context) {
isMobileParam := ctx.Query("isMobile") isMobileParam := ctx.Query("isMobile")
@ -67,56 +71,46 @@ func (b *BlogViewerApplication) Route(route *gin.RouterGroup) {
}) })
} }
// func (b *BlogViewerApplication) WriteMock(path string) { func (b *BlogViewerApplication) WriteMock(path string) error {
// blogFile := webfilesystem.WebFSFile{ blogFileHeader := webfilesystem.FileHeader{
// MongoId: primitive.NewObjectID(), MongoId: primitive.NewObjectID(),
// Name: "test-1.blog", Name: "blog1.blog",
// Type: "blog-page", Type: "",
// Data: BlogFileData{ Icon: "",
// Header: "OMG THIS IS BLOG", Data: [12]byte{},
// Blocks: []Block{ }
// { blogFileData := BlogFileData{
// Type: "plain-text", Header: "OMG THIS IS BLOG",
// Data: []string{ Blocks: []Block{
// "Apoqiwepoqiwepo", {
// ".,mas;dakls;d", Type: "plain-text",
// "q[poqwieqpipoi]", Data: []string{
// }, "Apoqiwepoqiwepo",
// }, ".,mas;dakls;d",
// }, "q[poqwieqpipoi]",
// }, },
// } },
// err := b.fs.CreateFile(&blogFile, path) },
// if err != nil { }
// println(err.Error())
// }
// }
func (b *BlogViewerApplication) Render(path string, isMobile bool) (gin.H, error) { _, _, err := b.fs.Write("/home/user/blog1.blog", &blogFileHeader, blogFileData)
file, err := b.fs.NewReadDeprecated(path)
if err != nil { if err != nil {
println(err.Error()) println(err.Error())
return nil, err return err
} }
blogDataRaw := file.Data.(primitive.D).Map() return nil
header := blogDataRaw["header"] }
blocks := []Block{}
for _, rawBlock := range blogDataRaw["blocks"].(primitive.A) { func (b *BlogViewerApplication) Render(filePath string, isMobile bool) (gin.H, error) {
lel := rawBlock.(primitive.D).Map() data := BlogFileData{}
block := Block{ _, err := b.fs.Read(filePath, &data)
Type: lel["type"].(string), if err != nil {
Data: []string{}, return nil, err
}
for _, v := range lel["data"].(primitive.A) {
block.Data = append(block.Data, v.(string))
}
blocks = append(blocks, block)
} }
return gin.H{ return gin.H{
"header": header, "header": data.Header,
"blocks": blocks, "blocks": data.Blocks,
}, nil }, nil
} }

View File

@ -66,13 +66,13 @@ func (f *FinderApplication) RenderContextMenu(context string, data string) gin.H
} }
func (f *FinderApplication) RenderProps(filePath string) gin.H { func (f *FinderApplication) RenderProps(filePath string) gin.H {
file, err := f.fs.NewReadDeprecated(filePath) // file, err := f.fs.NewReadDeprecated(filePath)
if err != nil { // if err != nil {
return nil // return nil
} // }
return gin.H{ return gin.H{
"file": file, // "file": file,
} }
} }

View File

@ -1,13 +1,11 @@
package personalprops package personalprops
import ( import (
"errors"
"net/http" "net/http"
websiteapp "personalwebsite/apps" websiteapp "personalwebsite/apps"
"personalwebsite/webfilesystem" "personalwebsite/webfilesystem"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/mitchellh/mapstructure"
"go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/bson/primitive"
) )
@ -28,10 +26,22 @@ func NewPersPropsApp(webFs *webfilesystem.WebFileSystem) PersonalPropertiesApp {
} }
func (p *PersonalPropertiesApp) Route(route *gin.RouterGroup) { func (p *PersonalPropertiesApp) Route(route *gin.RouterGroup) {
route.GET("writeMock", func(ctx *gin.Context) {
err := p.WriteMock()
if err != nil {
ctx.Status(http.StatusInternalServerError)
}
ctx.Status(http.StatusOK)
})
route.GET("render", func(ctx *gin.Context) { route.GET("render", func(ctx *gin.Context) {
isMobileParam := ctx.Query("isMobile") isMobileParam := ctx.Query("isMobile")
isMobile := isMobileParam == "true" isMobile := isMobileParam == "true"
ginH, err := p.Render() filePath := ctx.Query("path")
if filePath == "" {
ctx.Status(http.StatusBadRequest)
return
}
ginH, err := p.Render(filePath)
if err != nil { if err != nil {
ctx.JSON(http.StatusInternalServerError, "TODO") //TODO ctx.JSON(http.StatusInternalServerError, "TODO") //TODO
return return
@ -51,56 +61,58 @@ func (p *PersonalPropertiesApp) GetId() string {
return p.manifest.AppId return p.manifest.AppId
} }
func (p *PersonalPropertiesApp) Render() (gin.H, error) { func (p *PersonalPropertiesApp) WriteMock() error {
propsFile, err := p.fs.NewReadDeprecated("/home/user/About Me.props") fileHeader := webfilesystem.FileHeader{
if err != nil { MongoId: primitive.NewObjectID(),
println(err.Error()) Name: "aboutme.props",
return nil, err Type: "personal-properties",
Icon: "",
} }
fileData := PropertiesFileData{
if propsFile.Type != "pers-props" { Header: HeaderIsland{
return nil, errors.New("file is not a directory") Name: "Test Name",
IconPath: "test icon path",
Info1: "Info1",
Info2: "Info2",
},
Props: []PropIsland{
{
Header: "Test Prop Header",
Props: []PropElement{
{
Key: "Test key",
KeyComments: []string{"Test key comment 1", "Test key comment 1"},
Values: []string{"test value1", "test value2"},
},
},
},
{
Header: "Test Prop Header 2",
Props: []PropElement{
{
Key: "Test key",
KeyComments: []string{"Test key comment 1", "Test key comment 1"},
Values: []string{"test value1", "test value2"},
},
},
},
},
} }
_, _, err := p.fs.Write("/home/user/aboutme.props", &fileHeader, fileData)
fileData, err := castToPersPropsData(propsFile.Data) return err
if err != nil {
println(err.Error())
return nil, err
}
_ = fileData
// file := castToFile(fileRaw)
// return file, nil
// if propsFile.Data == nil || propsFile.Type != "pers-props" {
// return nil, errors.New("bad file")
// }
// props, err := castToPersPropsData(propsFileRaw)
// _ = props
// if err != nil {
// return nil, err
// }
return gin.H{
// "headerProps": props.Header,
// "allprops": props.Props,
}, nil
} }
func castToPersPropsData(fileData interface{}) (*PropertiesFileData, error) { func (p *PersonalPropertiesApp) Render(filePath string) (gin.H, error) {
// kek := fileData.(primitive.D).Map()["name"] propsData := PropertiesFileData{}
propsData := PropertiesFileData{ _, err := p.fs.Read(filePath, &propsData)
// Header.Name: ,
}
err := mapstructure.Decode(fileData.(primitive.D).Map(), &propsData)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &propsData, nil
return gin.H{
"headerProps": propsData.Header,
"allprops": propsData.Props,
}, nil
} }
type HeaderIsland struct { type HeaderIsland struct {
@ -121,10 +133,6 @@ type PropIsland struct {
Props []PropElement Props []PropElement
} }
type PropertiesFile struct {
Props []PropIsland `bson:"props"`
}
type PropertiesFileData struct { type PropertiesFileData struct {
Header HeaderIsland `bson:"header"` Header HeaderIsland `bson:"header"`
Props []PropIsland `bson:"props"` Props []PropIsland `bson:"props"`

View File

@ -25,16 +25,16 @@ func (l *ImagLib) Route(route *gin.RouterGroup) {
return return
} }
fileId, err := l.fs.V3FindFile(path) imgData := Img{}
_, err := l.fs.Read(path, &imgData)
if err != nil { if err != nil {
ctx.Status(http.StatusInternalServerError) ctx.Status(http.StatusInternalServerError)
return return
} }
imgData := Img{} // _, err = l.fs.readFSDocs(fileId, &imgData)
_, err = l.fs.V3Read(fileId, &imgData) // if err != nil {
if err != nil { // ctx.Status(http.StatusInternalServerError)
ctx.Status(http.StatusInternalServerError) // }
}
ctx.Data(http.StatusOK, "image/jpeg", imgData.Bin) ctx.Data(http.StatusOK, "image/jpeg", imgData.Bin)
}) })

View File

@ -13,6 +13,7 @@ class PersonalProperties{
NewWindow(path){ NewWindow(path){
fetch(`${window.location.origin}/application/personal-properties/render?`+ new URLSearchParams({ fetch(`${window.location.origin}/application/personal-properties/render?`+ new URLSearchParams({
isMobile: WebDesktopEnvironment.isMobile, isMobile: WebDesktopEnvironment.isMobile,
path: path
})) }))
.then((response) => response.text()) .then((response) => response.text())
.then((html) => { .then((html) => {

View File

@ -4,9 +4,9 @@ document.addEventListener('DOMContentLoaded', function() {
// console.log(window.screen.width) // console.log(window.screen.width)
wde = new WebDesktopEnvironment wde = new WebDesktopEnvironment
if (!WebDesktopEnvironment.isMobile){ if (!WebDesktopEnvironment.isMobile){
WebDesktopEnvironment.Open("finder", ["/home/user"]) // WebDesktopEnvironment.Open("finder", ["/home/user"])
// WebDesktopEnvironment.Open("blog-viewer", ["/home/user/blog/test-1.blog"]) // WebDesktopEnvironment.Open("blog-viewer", ["/home/user/blog1.blog"])
// WebDesktopEnvironment.Open("personal-properties", ["kek"]) WebDesktopEnvironment.Open("personal-properties", ["/home/user/aboutme.props"])
} else { } else {
WebDesktopEnvironment.Open("blog-viewer", ["/home/user/blog/test-1.blog"]) WebDesktopEnvironment.Open("blog-viewer", ["/home/user/blog/test-1.blog"])
} }

View File

@ -22,13 +22,13 @@ type FilesWidget struct {
} }
func (w *WDE) Render(path string) (gin.H, error) { func (w *WDE) Render(path string) (gin.H, error) {
list, err := w.fs.NewListDeprecated(path) // list, err := w.fs.NewListDeprecated(path)
if err != nil { // if err != nil {
return nil, err // return nil, err
} // }
return gin.H{ return gin.H{
"Name": "Greg Brzezinski", "Name": "Greg Brzezinski",
"Files": list, // "Files": list,
}, nil }, nil
} }
@ -44,7 +44,7 @@ func (w *WDE) RenderContextMenu() (gin.H, error) {
} }
func (w *WDE) RenderFileTileView(directory string, host string) (gin.H, error) { func (w *WDE) RenderFileTileView(directory string, host string) (gin.H, error) {
list, err := w.fs.V3List(directory) list, err := w.fs.ListDir(directory)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -1,140 +0,0 @@
package webfilesystem
import (
"errors"
"go.mongodb.org/mongo-driver/bson/primitive"
)
type V3DirectoryData struct {
MongoId primitive.ObjectID `bson:"_id"`
Parent primitive.ObjectID `bson:"parent_id"`
Children []primitive.ObjectID `bson:"children_id"`
}
func (fs *WebFileSystem) V3CreateDirectory(dirPath string) (primitive.ObjectID, primitive.ObjectID, error) {
splittedPath := fs.SplitPath(dirPath)
parentPath := fs.GetParentPath(dirPath)
parentDirId, err := fs.V3FindFile(parentPath)
if err != nil {
return primitive.NilObjectID, primitive.NilObjectID, err
}
parentDirHeader, err := fs.V3Read(parentDirId, nil)
if err != nil {
return primitive.NilObjectID, primitive.NilObjectID, err
}
newDir := V3FileHeader{
MongoId: primitive.NewObjectID(),
Name: splittedPath[len(splittedPath)-1],
Type: "directory",
Icon: "",
}
newDirData := V3DirectoryData{
MongoId: primitive.NewObjectID(),
Parent: parentDirHeader.MongoId,
Children: []primitive.ObjectID{},
}
headerId, dataId, err := fs.v3WriteFileToMongo(&newDir, &newDirData)
if err != nil {
return primitive.NilObjectID, primitive.NilObjectID, err
}
err = fs.V3AppendChildToDirectory(headerId, parentDirId)
if err != nil {
return primitive.NilObjectID, primitive.NilObjectID, err
}
return headerId, dataId, nil
}
func (fs *WebFileSystem) V3AppendChildToDirectory(childId primitive.ObjectID, parentId primitive.ObjectID) error {
parentDirData := V3DirectoryData{}
parentDir, err := fs.V3Read(parentId, &parentDirData)
if err != nil {
return err
}
//TODO Check for duplicates?
parentDirData.Children = append(parentDirData.Children, childId)
err = fs.V3WriteUpdateData(parentDir, parentDirData)
if err != nil {
return err
}
return nil
}
func (fs *WebFileSystem) V3List(dirPath string) ([]*V3FileHeader, error) {
dirId, err := fs.V3FindFile(dirPath)
if err != nil {
return nil, err
}
dirData := V3DirectoryData{}
_, err = fs.V3Read(dirId, &dirData)
if err != nil {
return nil, err
}
// println(dirId.String())
// println(dirData.MongoId.String())
children := []*V3FileHeader{}
for _, childID := range dirData.Children {
childFile, err := fs.V3Read(childID, nil)
if err != nil {
// println(err.Error())
continue
}
children = append(children, childFile)
}
return children, nil
}
func (fs *WebFileSystem) V3FindFile(filePath string) (primitive.ObjectID, error) {
splittedPath := fs.SplitPath(filePath)
rootDir, _, err := fs.V3GetRootDir()
if err != nil {
return primitive.NilObjectID, err
}
// println(rootDir.Name)
lastFileID := rootDir.MongoId
for _, pathPart := range splittedPath[1:] {
// println(pathPart)
id, err := fs.v3findInChildren(pathPart, lastFileID)
if err != nil {
return primitive.NilObjectID, err
}
lastFileID = id
}
return lastFileID, nil
}
// func (fs *WebFileSystem) v3updateChildrenList(directoryID primitive.ObjectID, childrenList []primitive.ObjectID) (primitive.ObjectID, error) {
// }
func (fs *WebFileSystem) v3findInChildren(fileName string, parentDirId primitive.ObjectID) (primitive.ObjectID, error) {
parentDirData := V3DirectoryData{}
_, err := fs.V3Read(parentDirId, &parentDirData)
if err != nil {
return primitive.NilObjectID, err
}
for _, childId := range parentDirData.Children {
childFileHeader, err := fs.V3Read(childId, nil)
if err != nil {
return primitive.NilObjectID, err
}
if childFileHeader.Name == fileName {
return childId, nil
}
}
return primitive.NilObjectID, errors.New("file not found")
}

View File

@ -1,67 +1,109 @@
package webfilesystem package webfilesystem
import ( import (
"context"
"errors" "errors"
"strconv"
"github.com/mitchellh/mapstructure"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/bson/primitive"
) )
type DirectoryData struct { type DirectoryData struct {
Parent primitive.ObjectID `bson:"parent"` MongoId primitive.ObjectID `bson:"_id"`
Children []primitive.ObjectID `bson:"children"` Parent primitive.ObjectID `bson:"parent_id"`
Children []primitive.ObjectID `bson:"children_id"`
} }
//Deprecated func (fs *WebFileSystem) CreateDirectory(dirPath string) (primitive.ObjectID, primitive.ObjectID, error) {
func (fs *WebFileSystem) List(dirPath string) ([]*OnlyHeaderFile, error) { splittedPath := fs.SplitPath(dirPath)
fileId, err := fs.FindFile(dirPath) parentPath := fs.GetParentPath(dirPath)
parentDirId, err := fs.FindFile(parentPath)
if err != nil {
return primitive.NilObjectID, primitive.NilObjectID, err
}
parentDirHeader, err := fs.readFSDocs(parentDirId, nil)
if err != nil {
return primitive.NilObjectID, primitive.NilObjectID, err
}
newDir := FileHeader{
MongoId: primitive.NewObjectID(),
Name: splittedPath[len(splittedPath)-1],
Type: "directory",
Icon: "",
}
newDirData := DirectoryData{
MongoId: primitive.NewObjectID(),
Parent: parentDirHeader.MongoId,
Children: []primitive.ObjectID{},
}
headerId, dataId, err := fs.writeFileToMongo(&newDir, &newDirData)
if err != nil {
return primitive.NilObjectID, primitive.NilObjectID, err
}
err = fs.AppendChildToDirectory(headerId, parentDirId)
if err != nil {
return primitive.NilObjectID, primitive.NilObjectID, err
}
return headerId, dataId, nil
}
func (fs *WebFileSystem) AppendChildToDirectory(childId primitive.ObjectID, parentId primitive.ObjectID) error {
parentDirData := DirectoryData{}
parentDir, err := fs.readFSDocs(parentId, &parentDirData)
if err != nil {
return err
}
//TODO Check for duplicates?
parentDirData.Children = append(parentDirData.Children, childId)
err = fs.UpdateFileData(parentDir, parentDirData)
if err != nil {
return err
}
return nil
}
func (fs *WebFileSystem) ListDir(dirPath string) ([]*FileHeader, error) {
dirId, err := fs.FindFile(dirPath)
if err != nil { if err != nil {
return nil, err return nil, err
} }
read := ReadStruct2{ dirData := DirectoryData{}
File: &DirectoryFile{}, _, err = fs.readFSDocs(dirId, &dirData)
Id: fileId,
}
fileRaw, err := fs.Read(read)
if err != nil { if err != nil {
return nil, err return nil, err
} }
var dirPtr interface{} = *fileRaw // println(dirId.String())
dir := dirPtr.(*DirectoryFile) // println(dirData.MongoId.String())
children := []*OnlyHeaderFile{} children := []*FileHeader{}
for _, childID := range dir.Data.Children { for _, childID := range dirData.Children {
read := ReadStruct2{ childFile, err := fs.readFSDocs(childID, nil)
File: &OnlyHeaderFile{},
Id: childID,
}
childFile, err := fs.Read(read)
if err != nil { if err != nil {
// println(err.Error()) // println(err.Error())
continue continue
} }
var dirPtr interface{} = *childFile children = append(children, childFile)
children = append(children, dirPtr.(*OnlyHeaderFile))
} }
return children, nil return children, nil
} }
//Deprecated
func (fs *WebFileSystem) FindFile(filePath string) (primitive.ObjectID, error) { func (fs *WebFileSystem) FindFile(filePath string) (primitive.ObjectID, error) {
splittedPath := fs.SplitPath(filePath) splittedPath := fs.SplitPath(filePath)
_, rootDirID, err := fs.GetRootDir() rootDir, _, err := fs.GetRootDir()
if err != nil { if err != nil {
return primitive.NilObjectID, err return primitive.NilObjectID, err
} }
// println(rootDir.Name) // println(rootDir.Name)
lastFileID := rootDirID lastFileID := rootDir.MongoId
for _, pathPart := range splittedPath[1:] { for _, pathPart := range splittedPath[1:] {
// println(pathPart) // println(pathPart)
id, err := fs.findInChildren(pathPart, lastFileID) id, err := fs.findInChildren(pathPart, lastFileID)
@ -73,35 +115,18 @@ func (fs *WebFileSystem) FindFile(filePath string) (primitive.ObjectID, error) {
return lastFileID, nil return lastFileID, nil
} }
//Deprecated
func (fs *WebFileSystem) findInChildren(fileName string, parentDirId primitive.ObjectID) (primitive.ObjectID, error) { func (fs *WebFileSystem) findInChildren(fileName string, parentDirId primitive.ObjectID) (primitive.ObjectID, error) {
read := ReadStruct2{ parentDirData := DirectoryData{}
File: &DirectoryFile{ _, err := fs.readFSDocs(parentDirId, &parentDirData)
FileHeader: FileHeader{},
Data: DirectoryData{},
},
Id: parentDirId,
}
parentDirRaw, err := fs.Read(read)
if err != nil { if err != nil {
return primitive.NilObjectID, err return primitive.NilObjectID, err
} }
var dirPtr interface{} = *parentDirRaw
dir := dirPtr.(*DirectoryFile)
for _, childId := range dir.Data.Children { for _, childId := range parentDirData.Children {
read := ReadStruct2{ childFileHeader, err := fs.readFSDocs(childId, nil)
File: OnlyHeaderFile{},
Id: childId,
}
childRaw, err := fs.Read(read)
if err != nil { if err != nil {
return primitive.NilObjectID, err return primitive.NilObjectID, err
} }
var dirPtr interface{} = *childRaw
childFileHeader := dirPtr.(*OnlyHeaderFile)
if childFileHeader.Name == fileName { if childFileHeader.Name == fileName {
return childId, nil return childId, nil
} }
@ -109,160 +134,3 @@ func (fs *WebFileSystem) findInChildren(fileName string, parentDirId primitive.O
return primitive.NilObjectID, errors.New("file not found") return primitive.NilObjectID, errors.New("file not found")
} }
//Deprecated
func (fs *WebFileSystem) IsChild(childID primitive.ObjectID, parent primitive.ObjectID) (bool, error) {
read := ReadStruct{
File: DirectoryFile{}, //TODO May be a possible problem, if parent file would be not a directory type
}
dirRaw, err := fs.ReadMongo(read)
if err != nil {
return false, err
}
var dirPtr interface{} = *dirRaw
dir := dirPtr.(*DirectoryFile)
for _, cID := range dir.Data.Children {
if cID == childID {
return true, nil
}
}
return false, nil
}
//Deprecated
func (fs *WebFileSystem) GetRootDir() (*DirectoryFile, primitive.ObjectID, error) {
filter := primitive.M{
"header.name": "/",
}
res := fs.webfsCollection.FindOne(fs.ctx, filter)
if res == nil {
return nil, primitive.NilObjectID, errors.New("TODO") //TODO
}
rootDirID := FileId{}
rootDir := DirectoryFile{}
err := res.Decode(&rootDir)
if res == nil {
return nil, primitive.NilObjectID, err
}
err = res.Decode(&rootDirID)
if res == nil {
return nil, primitive.NilObjectID, err
}
return &rootDir, rootDirID.Id, err
}
//Deprecated
func (fs *WebFileSystem) NewCreateDirectory(dirPath string) (primitive.ObjectID, error) {
splittedPath := fs.SplitPath(dirPath)
parentPath := fs.GetParentPath(dirPath)
parentDirRaw, err := fs.NewReadDeprecated(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
}
return objectId, nil
}
func (fs *WebFileSystem) CreateDirectory(dirPath string) (primitive.ObjectID, error) {
splittedPath := fs.SplitPath(dirPath)
parentPath := fs.GetParentPath(dirPath)
parentDirID, err := fs.FindFile(parentPath)
if err != nil {
return primitive.NilObjectID, err
}
read := ReadStruct2{
File: nil,
Id: parentDirID,
}
parentDirRaw, err := fs.Read(read)
if err != nil {
return primitive.NilObjectID, err
}
var dirPtr interface{} = *parentDirRaw
parentDir := dirPtr.(*OnlyHeaderFile)
if parentDir.Type != "directory" {
return primitive.NilObjectID, errors.New("path is bad")
}
newDir := DirectoryFile{
FileHeader: FileHeader{
Name: splittedPath[len(splittedPath)-1],
Type: "",
Icon: "",
},
Data: DirectoryData{
Parent: parentDirID,
Children: []primitive.ObjectID{},
},
}
resID, err := fs.Write(newDir, dirPath, false)
if err != nil {
return primitive.NilObjectID, err
}
fs.insertFileToDirectory(resID, parentDirID)
return resID, 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
}
func castToFile(raw *interface{}) *WebFSFile {
var dirPtr interface{} = *raw
return dirPtr.(*WebFSFile)
}
func castToDirectoryData(data interface{}) (*DirectoryData, error) {
dirData := DirectoryData{}
err := mapstructure.Decode(data.(primitive.D).Map(), &dirData)
if err != nil {
return nil, err
}
return &dirData, nil
}
// func List()

View File

@ -20,7 +20,7 @@ func (fs *WebFileSystem) UploadFile(realFilepath string, parentPath string) erro
fileName := splittedPath[len(splittedPath)-1] fileName := splittedPath[len(splittedPath)-1]
extension := fs.GetExtension(fileName) extension := fs.GetExtension(fileName)
newFile2 := V3FileHeader{ newFile2 := FileHeader{
MongoId: primitive.NewObjectID(), MongoId: primitive.NewObjectID(),
Name: fileName, Name: fileName,
Type: "", Type: "",
@ -28,7 +28,7 @@ func (fs *WebFileSystem) UploadFile(realFilepath string, parentPath string) erro
Data: primitive.NilObjectID, Data: primitive.NilObjectID,
} }
newFileData := V3FileBinaryData{ newFileData := BinaryFileData{
MongoId: primitive.NewObjectID(), MongoId: primitive.NewObjectID(),
Bin: file, Bin: file,
} }
@ -40,11 +40,11 @@ func (fs *WebFileSystem) UploadFile(realFilepath string, parentPath string) erro
fallthrough fallthrough
case "jpeg": case "jpeg":
newFile2.Type = "jpeg" newFile2.Type = "jpeg"
_, _, err := fs.V3Write(filePath, &newFile2, &newFileData) _, _, err := fs.Write(filePath, &newFile2, &newFileData)
return err return err
case "png": case "png":
newFile2.Type = "png" newFile2.Type = "png"
_, _, err := fs.V3Write(filePath, &newFile2, &newFileData) _, _, err := fs.Write(filePath, &newFile2, &newFileData)
if err != nil { if err != nil {
println(err.Error()) println(err.Error())
return err return err
@ -56,37 +56,6 @@ func (fs *WebFileSystem) UploadFile(realFilepath string, parentPath string) erro
} }
// Deprecated
func (fs *WebFileSystem) UploadBinaryFile(file []byte, fileName string, path string) error {
extension := fs.GetExtension(fileName)
switch extension {
case "jpg":
fallthrough
case "jpeg":
newFile := WebFSFile{
MongoId: primitive.NewObjectID(),
Name: fileName,
Type: "jpeg",
Data: file,
Icon: "",
}
err := fs.WriteFile(&newFile, path)
return err
case "png":
newFile := WebFSFile{
MongoId: primitive.NewObjectID(),
Name: fileName,
Type: "png",
Data: file,
}
err := fs.WriteFile(&newFile, path)
return err
default:
return errors.New("this filetype not allowed")
}
}
// func (fs *WebFileSystem) CreateMiniatures(parentDir string, file string) error { // func (fs *WebFileSystem) CreateMiniatures(parentDir string, file string) error {
// src, err := imaging.Open(path.Join(parentDir, file)) // src, err := imaging.Open(path.Join(parentDir, file))
// if err != nil { // if err != nil {

View File

@ -1,98 +1,77 @@
package webfilesystem package webfilesystem
import ( import (
"context"
"errors" "errors"
"go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/bson/primitive"
) )
type ReadStruct struct { func (fs *WebFileSystem) readFSDocs(fileID primitive.ObjectID, fileData interface{}) (*FileHeader, error) {
File interface{} fileHeader := &FileHeader{}
Filter interface{} filter := primitive.M{
} "_id": fileID,
}
//TODO: Read files only by objectId, before reading file, search path by reading all parent folders err := fs.webfsFilesTable.FindOne(fs.ctx, filter).Decode(fileHeader)
// Deprecated
func (fs *WebFileSystem) ReadMongo(read ReadStruct) (*interface{}, error) {
err := fs.webfsCollection.FindOne(fs.ctx, read.Filter).Decode(read.File)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &read.File, nil if fileData != nil {
filter := primitive.M{
"_id": fileHeader.Data,
}
err := fs.webfsFilesData.FindOne(fs.ctx, filter).Decode(fileData)
if err != nil {
return nil, err
}
}
return fileHeader, nil
} }
// Deprecated func (fs *WebFileSystem) writeFileToMongo(file *FileHeader, data interface{}) (primitive.ObjectID, primitive.ObjectID, error) {
func (fs *WebFileSystem) writeMongo(file WebFSFile, parentPath string) (primitive.ObjectID, error) { resData, err := fs.webfsFilesData.InsertOne(fs.ctx, data)
//TODO Check file existance
parentDir, err := fs.NewReadDeprecated(parentPath)
if err != nil { if err != nil {
return primitive.NilObjectID, err return primitive.NilObjectID, primitive.NilObjectID, err
} }
res, err := fs.webfsCollection.InsertOne(context.Background(), &file) file.Data = resData.InsertedID.(primitive.ObjectID)
resHeader, err := fs.webfsFilesTable.InsertOne(fs.ctx, file)
if err != nil { if err != nil {
return primitive.NilObjectID, err return primitive.NilObjectID, primitive.NilObjectID, err
} }
return resHeader.InsertedID.(primitive.ObjectID), resData.InsertedID.(primitive.ObjectID), err
fileId := fs.castInsertId(res)
fs.insertFileToDirectory(fileId, parentDir.MongoId)
return fileId, nil
} }
func (fs *WebFileSystem) removeMongo(filePath string) error { func (fs *WebFileSystem) removeFromMongo(fileId primitive.ObjectID) error {
file, err := fs.NewReadDeprecated(filePath) return errors.New("todo not implemented yet")
if err != nil {
return err
}
if file.MongoId == primitive.NilObjectID {
return errors.New("TODO") //TODO
}
filter := primitive.M{
"_id": file.MongoId,
}
res, err := fs.webfsCollection.DeleteOne(fs.ctx, filter)
if err != nil {
return err
}
if res.DeletedCount < 1 {
return errors.New("no file removed")
}
return nil
} }
func (fs *WebFileSystem) Validate() error { func (fs *WebFileSystem) Validate() error {
filter := primitive.D{ // filter := primitive.D{
{ // {
Key: "type", // Key: "type",
Value: "directory", // Value: "directory",
}, // },
} // }
cur, err := fs.webfsCollection.Find(context.Background(), filter) // cur, err := fs.webfsCollection.Find(context.Background(), filter)
if err != nil { // if err != nil {
return err // return err
} // }
defer cur.Close(context.Background()) // defer cur.Close(context.Background())
directories := []*WebFSFile{} // directories := []*WebFSFile{}
for cur.Next(context.Background()) { // for cur.Next(context.Background()) {
dir := &WebFSFile{} // dir := &WebFSFile{}
err = cur.Decode(dir) // err = cur.Decode(dir)
if err != nil { // if err != nil {
println(err.Error()) // println(err.Error())
return err // return err
} // }
directories = append(directories, dir) // directories = append(directories, dir)
} // }
for _, d := range directories { // for _, d := range directories {
fs.validateDir(d) // fs.validateDir(d)
} // }
return nil return nil
} }

View File

@ -1,58 +0,0 @@
package webfilesystem
import (
"errors"
"go.mongodb.org/mongo-driver/bson/primitive"
)
// Deprecated
func (fs *WebFileSystem) NewReadDeprecated(filePath string) (*WebFSFile, error) {
splittedPath := fs.SplitPath(filePath)
read := ReadStruct{
File: &WebFSFile{},
Filter: primitive.M{
"name": splittedPath[len(splittedPath)-1],
},
}
fileRaw, err := fs.ReadMongo(read)
if err != nil {
return nil, err
}
file := castToFile(fileRaw)
return file, nil
}
// Deprecated
func (fs *WebFileSystem) NewListDeprecated(dirPath string) ([]*WebFSFile, error) {
dirFile, err := fs.NewReadDeprecated(dirPath)
if err != nil {
return nil, err
}
if dirFile.Type != "directory" {
return nil, errors.New("file is not a directory")
}
fileData, err := castToDirectoryData(dirFile.Data)
if err != nil {
return nil, err
}
files := []*WebFSFile{}
for _, child := range fileData.Children {
file, err := fs.ReadByObjectID(child)
if err != nil {
println(err.Error())
continue
}
files = append(files, file)
}
return files, nil
}
func (fs *WebFileSystem) WriteFile(file *WebFSFile, parentPath string) error {
fs.writeMongo(*file, parentPath)
return errors.New("Not ready yet")
}

View File

@ -1,82 +0,0 @@
package webfilesystem
import (
"context"
"errors"
"go.mongodb.org/mongo-driver/bson/primitive"
)
// Deprecated
type ReadStruct2 struct {
File interface{}
Id primitive.ObjectID
}
// Deprecated
func (fs *WebFileSystem) Read(read ReadStruct2) (*interface{}, error) {
//TODO Check nil Id
filter := primitive.M{
"_id": read.Id,
}
err := fs.webfsCollection.FindOne(fs.ctx, filter).Decode(&read.File)
return &read.File, err
}
// Deprecated
func (fs *WebFileSystem) Write(file interface{}, filePath string, force bool) (primitive.ObjectID, error) {
foundedFile, err := fs.FindFile(filePath)
if err == nil { //FIXME
return primitive.NilObjectID, errors.New("file already exists")
}
_ = foundedFile
res, err := fs.webfsCollection.InsertOne(fs.ctx, file)
if err != nil {
return primitive.NilObjectID, err
}
_ = res.InsertedID
return primitive.NilObjectID, nil //FIXME
}
// Deprecated
func (fs *WebFileSystem) InitFS() error {
rootDir := DirectoryFile{
FileHeader: FileHeader{
Name: "/",
Type: "directory",
Icon: "",
},
Data: DirectoryData{
// Parent: id, //FIXME don't work
Children: []primitive.ObjectID{},
},
}
_, err := fs.webfsCollection.InsertOne(context.Background(), &rootDir)
return err
}
// Deprecated
type FileId struct {
Id primitive.ObjectID `bson:"_id"`
}
// Deprecated
type FileHeader struct {
Name string `bson:"name" json:"name"`
Type string `bson:"type" json:"type"`
Icon string `bson:"-" json:"icon"`
}
// Deprecated
type DirectoryFile struct {
FileHeader `bson:"header"`
Data DirectoryData `bson:"data" json:"-"`
}
// Deprecated
type OnlyHeaderFile struct {
FileHeader `bson:"header"`
// Data DirectoryData `bson:"data" json:"-"`
}

15
webfilesystem/public.go Normal file
View File

@ -0,0 +1,15 @@
package webfilesystem
func (fs *WebFileSystem) Read(filePath string, fileData interface{}) (*FileHeader, error) {
fileId, err := fs.FindFile(filePath)
if err != nil {
return nil, err
}
fileHeader, err := fs.readFSDocs(fileId, fileData)
if err != nil {
return nil, err
}
return fileHeader, nil
}

View File

@ -66,7 +66,7 @@ func (fs *WebFileSystem) Route(route *gin.RouterGroup) {
// }) // })
route.GET("init", func(ctx *gin.Context) { route.GET("init", func(ctx *gin.Context) {
err := fs.V3InitFS() err := fs.InitFS()
if err != nil { if err != nil {
ctx.JSON(http.StatusInternalServerError, err.Error()) //TODO json error struct ctx.JSON(http.StatusInternalServerError, err.Error()) //TODO json error struct
return return
@ -81,7 +81,7 @@ func (fs *WebFileSystem) Route(route *gin.RouterGroup) {
return return
} }
_, _, err := fs.V3CreateDirectory(path) _, _, err := fs.CreateDirectory(path)
if err != nil { if err != nil {
ctx.JSON(http.StatusInternalServerError, err.Error()) //TODO json error struct ctx.JSON(http.StatusInternalServerError, err.Error()) //TODO json error struct
return return
@ -97,7 +97,7 @@ func (fs *WebFileSystem) Route(route *gin.RouterGroup) {
return return
} }
files, err := fs.V3List(path) files, err := fs.ListDir(path)
if err != nil { if err != nil {
ctx.String(http.StatusInternalServerError, err.Error()) //TODO json error struct ctx.String(http.StatusInternalServerError, err.Error()) //TODO json error struct
return return
@ -106,21 +106,21 @@ func (fs *WebFileSystem) Route(route *gin.RouterGroup) {
ctx.JSON(http.StatusOK, &files) ctx.JSON(http.StatusOK, &files)
}) })
route.GET("read", func(ctx *gin.Context) { // route.GET("read", func(ctx *gin.Context) {
path := ctx.Query("path") // path := ctx.Query("path")
if path == "" { // if path == "" {
ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct // ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct
return // return
} // }
file, err := fs.NewReadDeprecated(path) // file, err := fs.NewReadDeprecated(path)
if err != nil { // if err != nil {
ctx.JSON(http.StatusInternalServerError, "TODO") //TODO json error struct // ctx.JSON(http.StatusInternalServerError, "TODO") //TODO json error struct
return // return
} // }
ctx.JSON(http.StatusOK, &file) // ctx.JSON(http.StatusOK, &file)
}) // })
route.GET("validate", func(ctx *gin.Context) { route.GET("validate", func(ctx *gin.Context) {
err := fs.Validate() err := fs.Validate()
@ -138,7 +138,7 @@ func (fs *WebFileSystem) Route(route *gin.RouterGroup) {
ctx.Status(http.StatusBadRequest) //TODO ctx.Status(http.StatusBadRequest) //TODO
return return
} }
err := fs.V3Remove(path) err := fs.Remove(path)
if err != nil { if err != nil {
ctx.Status(http.StatusInternalServerError) ctx.Status(http.StatusInternalServerError)
return return

View File

@ -26,54 +26,140 @@ func NewWebFileSystem(mongoClient *mongo.Client, dBName string, fsCollectionName
} }
} }
type FileHeader struct {
MongoId primitive.ObjectID `bson:"_id" json:"-"`
Name string `bson:"name" json:"name"`
Type string `bson:"type" json:"type"`
Icon string `bson:"-" json:"icon"`
Data primitive.ObjectID `bson:"data_id" json:"-"`
}
type BinaryFileData struct {
MongoId primitive.ObjectID `bson:"_id" json:"-"`
Bin []byte `bson:"bin" json:"-"`
}
// Deprecated // Deprecated
func (fs *WebFileSystem) ReadByObjectID(objectId primitive.ObjectID) (*WebFSFile, error) { func (fs *WebFileSystem) ReadHeader(fileID primitive.ObjectID) (*FileHeader, error) {
filter := primitive.D{ file := &FileHeader{}
{ filter := primitive.M{
Key: "_id", "_id": fileID,
Value: objectId,
},
} }
//TODO to readMongo() err := fs.webfsFilesTable.FindOne(fs.ctx, filter).Decode(file)
file, err := fs.findFileInMongo(filter)
return file, err return file, err
} }
// Deprecated //TODO To private, get name from path and set it to file struct, force set newObjectID
func (fs *WebFileSystem) findFileInMongo(filter primitive.D) (*WebFSFile, error) { func (fs *WebFileSystem) Write(filePath string, file *FileHeader, data interface{}) (primitive.ObjectID, primitive.ObjectID, error) {
res := fs.webfsCollection.FindOne(context.Background(), &filter) headerId, dataId, err := fs.writeFileToMongo(file, data)
file := WebFSFile{}
err := res.Decode(&file)
if err != nil { if err != nil {
return nil, err return primitive.NilObjectID, primitive.NilObjectID, err
} }
return &file, nil parentPath := fs.GetParentPath(filePath)
parentDir, err := fs.FindFile(parentPath)
if err != nil {
return primitive.NilObjectID, primitive.NilObjectID, err
}
if parentDir.IsZero() {
return primitive.NilObjectID, primitive.NilObjectID, errors.New("parent dir not found")
}
err = fs.AppendChildToDirectory(headerId, parentDir)
if err != nil {
return primitive.NilObjectID, primitive.NilObjectID, err
}
return headerId, dataId, nil
} }
func (fs *WebFileSystem) castInsertId(res *mongo.InsertOneResult) primitive.ObjectID { func (fs *WebFileSystem) UpdateFileData(file *FileHeader, data interface{}) error {
return res.InsertedID.(primitive.ObjectID) update := bson.M{"$set": data}
} // println("updating data file: " + file.MongoId.String())
res, err := fs.webfsFilesData.UpdateByID(fs.ctx, file.Data, update)
func (fs *WebFileSystem) insertFileToDirectory(fileId primitive.ObjectID, directoryId primitive.ObjectID) error {
read := ReadStruct2{
File: DirectoryFile{},
Id: directoryId,
}
parentDirRaw, err := fs.Read(read)
if err != nil {
return err
}
var dirPtr interface{} = *parentDirRaw
parentDir := dirPtr.(*DirectoryFile)
parentDir.Data.Children = append(parentDir.Data.Children, fileId)
res, err := fs.webfsCollection.UpdateByID(context.Background(), directoryId, bson.M{"$set": bson.M{"data.children": parentDir.Data.Children}})
if err != nil { if err != nil {
return err return err
} }
if res.ModifiedCount < 1 { if res.ModifiedCount < 1 {
return errors.New("no parent folders edited") return errors.New("no data updated")
}
return err
}
func (fs *WebFileSystem) InitFS() error { //FIXME Can't set parent_id to itself
rootData := DirectoryData{
MongoId: primitive.NewObjectID(),
Parent: primitive.NewObjectID(),
Children: []primitive.ObjectID{},
}
rootHeader := FileHeader{
MongoId: primitive.NewObjectID(),
Name: "/",
Type: "directory",
Icon: "",
}
_, _, err := fs.writeFileToMongo(&rootHeader, &rootData)
if err != nil {
return err
}
return nil
}
//TODO get on boot and safe to struct
func (fs *WebFileSystem) GetRootDir() (*FileHeader, *DirectoryData, error) {
filter := primitive.M{
"name": "/",
}
res := fs.webfsFilesTable.FindOne(fs.ctx, filter)
if res == nil {
return nil, nil, errors.New("TODO") //TODO
}
rootDir := FileHeader{}
err := res.Decode(&rootDir)
if res == nil {
return nil, nil, err
}
filterData := primitive.M{
"_id": rootDir.Data,
}
resData := fs.webfsFilesData.FindOne(fs.ctx, filterData)
if resData.Err() != nil {
return nil, nil, err
}
rootDirData := DirectoryData{}
err = resData.Decode(&rootDirData)
if err != nil {
return nil, nil, err
}
return &rootDir, &rootDirData, nil
}
func (fs *WebFileSystem) Remove(filePath string) error {
parentPath := fs.GetParentPath(filePath)
parentDirId, err := fs.FindFile(parentPath)
if err != nil {
return err
}
//TODO: Check, if parent file is dir
parentDirData := DirectoryData{}
parentDir, err := fs.readFSDocs(parentDirId, &parentDirData)
if err != nil {
return err
}
fileId, err := fs.FindFile(filePath)
if err != nil {
return err
}
newChildren := []primitive.ObjectID{}
for _, childId := range parentDirData.Children {
if childId != fileId {
newChildren = append(newChildren, childId)
}
}
parentDirData.Children = newChildren
err = fs.UpdateFileData(parentDir, parentDirData)
if err != nil {
return err
} }
return nil return nil
} }
@ -103,94 +189,3 @@ func (fs *WebFileSystem) GetParentPath(path string) string {
} }
return "/" return "/"
} }
// Deprecated
func (fs *WebFileSystem) Delete(filePath string) error {
// splittedPath := fs.SplitPath(filePath)
// parentPath := fs.GetParentPath(filePath)
_, err := fs.NewReadDeprecated(filePath)
if err != nil {
return err
}
err = fs.removeMongo(filePath)
if err != nil {
return err
}
err = fs.Validate() //FIXME
if err != nil {
return err
}
//Delete from parent folder
// parentDir, err := fs.NewRead(parentPath)
// if err != nil {
// return err
// }
// parentDirData, err := castToDirectoryData(parentDir.Data)
// if err != nil {
// return err
// }
// newChildrenSlice := []primitive.ObjectID{}
// for i := 0; i < len(parentDirData.Children); i++ {
// if parentDirData.Children[i] != file.MongoId {
// newChildrenSlice = append(newChildrenSlice, parentDirData.Children[i])
// }
// }
// parentDirData.Children = newChildrenSlice
// parentDir.Data = parentDirData
// parentParentDir := fs.GetParentPath(parentPath)
// _, err = fs.writeMongo(*parentDir, parentParentDir)
// if err != nil {
// return err
// }
return nil
// for _, childId := range parentDirData.Children {
// // read := readStruct{
// // File: filePath,
// // Filter: primitive.M{
// // "_id": childId,
// // },
// // }
// // childFile, err := fs.ReadByObjectID(childId)
// // if err != nil {
// // println(err.Error())
// // continue
// // }
// // println(childFile.Name + " " + chil)
// if file.MongoId == childId {
// println(file.Name)
// parentDirData.Children.
// }
// }
// update:= primitive.M{
// "data.children":
// }
// filter := primitive.M{}
// res, err := fs.webfsCollection.UpdateByID(context.Background(), parentDir.MongoId, primitive.M{"$unset": bson.M{"data.children." + file.MongoId.String(): ""}})
// res, err := fs.webfsCollection.UpdateOne(context.Background(), filter, primitive.M{"$unset": bson.M{"data.children." + file.MongoId.String(): ""}})
// if err != nil {
// return err
// }
// if res.MatchedCount < 1 {
// return errors.New("no documents found")
// }
// return nil
}
type WebFSFile struct {
MongoId primitive.ObjectID `bson:"_id" json:"-"`
Name string `bson:"name" json:"name"`
Type string `bson:"type" json:"type"`
Icon string `bson:"-" json:"icon"`
Data interface{} `bson:"data" json:"-"`
}

View File

@ -1,181 +0,0 @@
package webfilesystem
import (
"errors"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
type V3FileHeader struct {
MongoId primitive.ObjectID `bson:"_id" json:"-"`
Name string `bson:"name" json:"name"`
Type string `bson:"type" json:"type"`
Icon string `bson:"-" json:"icon"`
Data primitive.ObjectID `bson:"data_id" json:"-"`
}
type V3FileBinaryData struct {
MongoId primitive.ObjectID `bson:"_id" json:"-"`
Bin []byte `bson:"bin" json:"-"`
}
func (fs *WebFileSystem) V3ReadHeader(fileID primitive.ObjectID) (*V3FileHeader, error) {
file := &V3FileHeader{}
filter := primitive.M{
"_id": fileID,
}
err := fs.webfsFilesTable.FindOne(fs.ctx, filter).Decode(file)
return file, err
}
func (fs *WebFileSystem) V3Read(fileID primitive.ObjectID, fileData interface{}) (*V3FileHeader, error) {
fileHeader := &V3FileHeader{}
filter := primitive.M{
"_id": fileID,
}
err := fs.webfsFilesTable.FindOne(fs.ctx, filter).Decode(fileHeader)
if err != nil {
return nil, err
}
if fileData != nil {
filter := primitive.M{
"_id": fileHeader.Data,
}
err := fs.webfsFilesData.FindOne(fs.ctx, filter).Decode(fileData)
if err != nil {
return nil, err
}
}
return fileHeader, nil
}
func (fs *WebFileSystem) V3Write(filePath string, file *V3FileHeader, data interface{}) (primitive.ObjectID, primitive.ObjectID, error) {
headerId, dataId, err := fs.v3WriteFileToMongo(file, data)
if err != nil {
return primitive.NilObjectID, primitive.NilObjectID, err
}
parentPath := fs.GetParentPath(filePath)
parentDir, err := fs.V3FindFile(parentPath)
if err != nil {
return primitive.NilObjectID, primitive.NilObjectID, err
}
if parentDir.IsZero() {
return primitive.NilObjectID, primitive.NilObjectID, errors.New("parent dir not found")
}
err = fs.V3AppendChildToDirectory(headerId, parentDir)
if err != nil {
return primitive.NilObjectID, primitive.NilObjectID, err
}
return headerId, dataId, nil
}
func (fs *WebFileSystem) v3WriteFileToMongo(file *V3FileHeader, data interface{}) (primitive.ObjectID, primitive.ObjectID, error) {
resData, err := fs.webfsFilesData.InsertOne(fs.ctx, data)
if err != nil {
return primitive.NilObjectID, primitive.NilObjectID, err
}
file.Data = resData.InsertedID.(primitive.ObjectID)
resHeader, err := fs.webfsFilesTable.InsertOne(fs.ctx, file)
if err != nil {
return primitive.NilObjectID, primitive.NilObjectID, err
}
return resHeader.InsertedID.(primitive.ObjectID), resData.InsertedID.(primitive.ObjectID), err
}
func (fs *WebFileSystem) V3WriteUpdateData(file *V3FileHeader, data interface{}) error {
update := bson.M{"$set": data}
// println("updating data file: " + file.MongoId.String())
res, err := fs.webfsFilesData.UpdateByID(fs.ctx, file.Data, update)
if err != nil {
return err
}
if res.ModifiedCount < 1 {
return errors.New("no data updated")
}
return err
}
func (fs *WebFileSystem) V3InitFS() error { //FIXME Can't set parent_id to itself
rootData := V3DirectoryData{
MongoId: primitive.NewObjectID(),
Parent: primitive.NewObjectID(),
Children: []primitive.ObjectID{},
}
rootHeader := V3FileHeader{
MongoId: primitive.NewObjectID(),
Name: "/",
Type: "directory",
Icon: "",
}
_, _, err := fs.v3WriteFileToMongo(&rootHeader, &rootData)
if err != nil {
return err
}
return nil
}
func (fs *WebFileSystem) V3GetRootDir() (*V3FileHeader, *V3DirectoryData, error) {
filter := primitive.M{
"name": "/",
}
res := fs.webfsFilesTable.FindOne(fs.ctx, filter)
if res == nil {
return nil, nil, errors.New("TODO") //TODO
}
rootDir := V3FileHeader{}
err := res.Decode(&rootDir)
if res == nil {
return nil, nil, err
}
filterData := primitive.M{
"_id": rootDir.Data,
}
resData := fs.webfsFilesData.FindOne(fs.ctx, filterData)
if resData.Err() != nil {
return nil, nil, err
}
rootDirData := V3DirectoryData{}
err = resData.Decode(&rootDirData)
if err != nil {
return nil, nil, err
}
return &rootDir, &rootDirData, nil
}
func (fs *WebFileSystem) V3Remove(filePath string) error {
parentPath := fs.GetParentPath(filePath)
parentDirId, err := fs.V3FindFile(parentPath)
if err != nil {
return err
}
//TODO: Check, if parent file is dir
parentDirData := V3DirectoryData{}
parentDir, err := fs.V3Read(parentDirId, &parentDirData)
if err != nil {
return err
}
fileId, err := fs.V3FindFile(filePath)
if err != nil {
return err
}
newChildren := []primitive.ObjectID{}
for _, childId := range parentDirData.Children {
if childId != fileId {
newChildren = append(newChildren, childId)
}
}
parentDirData.Children = newChildren
err = fs.V3WriteUpdateData(parentDir, parentDirData)
if err != nil {
return err
}
return nil
}
func (fs *WebFileSystem) removeFromMongo(fileId primitive.ObjectID) error {
return errors.New("todo not implemented yet")
}