From 56038cc284d8d5bff9685dec64c58a9c743f57a3 Mon Sep 17 00:00:00 2001 From: cyber-dream Date: Wed, 17 May 2023 16:09:22 +0300 Subject: [PATCH] Fixes --- apps/websiteapp.go | 2 +- errormessage/errormessage.go | 5 ++ resources/dev-fs/apps/finder/finder.js | 19 ++++--- resources/wde.js | 38 ++++++++++++-- routes/private.go | 27 +++++++--- test-img/myphoto.jpg | 3 -- webfilesystem/directory.go | 30 ++++++++++-- webfilesystem/fileuploading.go | 6 +-- webfilesystem/mongo.go | 28 ++++++++++- webfilesystem/routes.go | 49 ++++++++++--------- webfilesystem/validate.go | 68 ++++++++++++++++++++++++++ webfilesystem/webfilesystem.go | 52 ++++++++++++++++++-- 12 files changed, 269 insertions(+), 58 deletions(-) create mode 100644 errormessage/errormessage.go delete mode 100644 test-img/myphoto.jpg diff --git a/apps/websiteapp.go b/apps/websiteapp.go index 69447f7..5d3dc24 100644 --- a/apps/websiteapp.go +++ b/apps/websiteapp.go @@ -61,7 +61,7 @@ func (as *ApplicationsStorage) createApp(appName string, appId string, appPath s return nil } -func (aStorage *ApplicationsStorage) Route(route *gin.RouterGroup) { +func (aStorage *ApplicationsStorage) PrivateRoute(route *gin.RouterGroup) { route.GET("/get", func(ctx *gin.Context) { appId := ctx.Query("appid") if appId == "" { diff --git a/errormessage/errormessage.go b/errormessage/errormessage.go new file mode 100644 index 0000000..35c91dc --- /dev/null +++ b/errormessage/errormessage.go @@ -0,0 +1,5 @@ +package errormessage + +type ErrorMessage struct { + Message string `json:"message"` +} diff --git a/resources/dev-fs/apps/finder/finder.js b/resources/dev-fs/apps/finder/finder.js index 61467a1..f27fc0a 100644 --- a/resources/dev-fs/apps/finder/finder.js +++ b/resources/dev-fs/apps/finder/finder.js @@ -131,15 +131,18 @@ class FinderWindow{ WebDesktopEnvironment.Alert("UWAGA TODO MOVE FILE ERROR") //TODO } } else { - WebDesktopEnvironment.Alert("Not fixed yet") - return - let formData = new FormData() + console.log(event) let files = event.dataTransfer.files for (let i = 0; i < files.length; i++) { - const element = files[i]; - console.log(element) - formData.append("file", element) //FIXME Conn reset + const file = files[i]; + console.log("file:" + file) + + const res = await WebFS.UploadFile(file, this.curPath) + if (res){ + this.ReRenderDir() + } } + return const params = new URLSearchParams({ parentPath: this.curPath, }) @@ -168,7 +171,7 @@ class FinderWindow{ * @param {string} filePath */ async OpenFile(parentPath, fileName, fileType){ - console.log(parentPath, fileName, fileType) + // console.log(parentPath, fileName, fileType) // const splittedPath = filePath.split("/") // const fileName = splittedPath[splittedPath.length - 1] const fileExtension = fileName.split(".")[fileName.split(".").length - 1] //FIXME @@ -258,7 +261,7 @@ class FinderWindow{ let res = false switch (event.target.children[0].getAttribute("action")) { case "createPathLink": - res = await WebFS.CreatePathLink(`${this.curPath}/${fileName}`, `${this.curPath}/Link ${fileName}` ) + res = await WebFS.CreatePathLink(`${this.curPath}/${fileName}`, `${this.curPath}/Link to ${fileName}` ) if (res){ this.ReRenderDir() } diff --git a/resources/wde.js b/resources/wde.js index 1046102..42d76d7 100644 --- a/resources/wde.js +++ b/resources/wde.js @@ -16,6 +16,10 @@ document.addEventListener('DOMContentLoaded', function() { // WebDesktopEnvironment.Open("personal-properties") }, false); +// const ErrorObject = { +// message string +// } + class WebDesktopEnvironment{ static Applications = {}; static isMobile = false @@ -31,8 +35,8 @@ class WebDesktopEnvironment{ async loadWDE(){ // await WebDesktopEnvironment.load2('/Applications/Finder.app', [ "desktop", document.querySelector('#desktop-layer')]) - WebDesktopEnvironment.Open('/Applications/Finder.app', ["/home/user/.Desktop", "-desktop", document.querySelector('#desktop-layer')]) - // WebDesktopEnvironment.Open('/Applications/Finder.app', ["/home/user",]) + await WebDesktopEnvironment.Open('/Applications/Finder.app', ["/home/user/.desktop", "-desktop", document.querySelector('#desktop-layer')]) + WebDesktopEnvironment.Open('/Applications/Finder.app', ["/",]) } /** @@ -82,10 +86,12 @@ class WebDesktopEnvironment{ * @returns {Object | undefined} //FIXME */ static async fetchApp(path){ - console.log("path: " + path ) + // console.log("path: " + path ) const params = new URLSearchParams({path: path, mode: "json"}) const response = await fetch(`/system/loadApp?` + params) if (response.status != 200){ + const error = await response.json() + WebDesktopEnvironment.Alert(error.message) return undefined } //TODO Validate manifest @@ -363,4 +369,30 @@ class WebFS{ //TODO Validate return file } + + /** + * @param {File} file + * @param {string} filePath + * @returns {boolean} + */ + static async UploadFile(file, filePath){ + console.log('here') + let formData = new FormData() + formData.append("file", file) //FIXME Conn reset + const params = new URLSearchParams({ + filePath: filePath, + }) + const response = await fetch(`/system/fs/upload?` + params, + { + method: "POST", //TODO Change to PUT? + body: formData + }) + console.log(response.status) + if (response.status != 201){ + const error = await response.json() + WebDesktopEnvironment.Alert(error.message) + return false + } + return true + } } \ No newline at end of file diff --git a/routes/private.go b/routes/private.go index 90566bd..a4fff29 100644 --- a/routes/private.go +++ b/routes/private.go @@ -5,6 +5,7 @@ import ( "net/http" "path" "personalwebsite/apps" + "personalwebsite/errormessage" "personalwebsite/libs" "personalwebsite/routewde" "personalwebsite/wde" @@ -45,7 +46,7 @@ func PrivateRoutes(webfs *webfilesystem.WebFileSystem, webde *wde.WDE, appsStora appsStorageGroup := libsGroup.Group("apps") { - appsStorage.Route(appsStorageGroup) + appsStorage.PrivateRoute(appsStorageGroup) } } @@ -53,42 +54,52 @@ func PrivateRoutes(webfs *webfilesystem.WebFileSystem, webde *wde.WDE, appsStora { routewde.PublicRoutes(wdeGroup, webde) } + fsGroup := systemGroup.Group("fs") { webfs.PrivateRoutes(fsGroup) } + systemGroup.GET("/loadApp", func(ctx *gin.Context) { appPath := ctx.Query("path") if appPath == "" { - ctx.Status(http.StatusBadRequest) + ctx.JSON(http.StatusBadRequest, errormessage.ErrorMessage{ + Message: "Path for the App not provided in request", + }) return } appBundleData := webfilesystem.DirectoryData{} appBundle, err := webfs.Read(appPath, &appBundleData) if err != nil { - ctx.Status(http.StatusInternalServerError) + ctx.JSON(http.StatusInternalServerError, errormessage.ErrorMessage{ + Message: "Error in read App bundle", + }) return } if appBundle.Type != "directory" { - ctx.Status(http.StatusBadRequest) + ctx.JSON(http.StatusBadRequest, errormessage.ErrorMessage{ + Message: "App bundle file is bad", + }) return } appManifestData := apps.ApplicationManifest{} appManifestHeader, err := webfs.Read(path.Join(appPath, ".appmanifest"), &appManifestData) if err != nil { - ctx.Status(http.StatusInternalServerError) + ctx.JSON(http.StatusInternalServerError, errormessage.ErrorMessage{ + Message: "Error in read App manifest", + }) return } if appManifestHeader.Type != "application-manifest" { - ctx.Status(http.StatusBadRequest) + ctx.JSON(http.StatusInternalServerError, errormessage.ErrorMessage{ + Message: "Error in read App manifest", + }) return } - ctx.JSON(http.StatusOK, appManifestData) - }) } diff --git a/test-img/myphoto.jpg b/test-img/myphoto.jpg deleted file mode 100644 index dfd3454..0000000 --- a/test-img/myphoto.jpg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:86e19fd69b67e673a398e550e4b56d9e9a2b56f1390b46b0d0df0f1996bd3c34 -size 80021 diff --git a/webfilesystem/directory.go b/webfilesystem/directory.go index b9c2894..095a429 100644 --- a/webfilesystem/directory.go +++ b/webfilesystem/directory.go @@ -96,15 +96,37 @@ func (fs *WebFileSystem) ListDir(dirPath string) ([]*FileHeader, error) { return nil, err } + children, err := fs.listDirByObjectID(dirId) + // dirData := DirectoryData{} + // _, err = fs.readFSDocs(dirId, &dirData) + // if err != nil { + // return nil, err + // } + + // // println(dirId.String()) + // // println(dirData.MongoId.String()) + + // children := []*FileHeader{} + // for _, childID := range dirData.Children { + // childFile, err := fs.readFSDocs(childID, nil) + // if err != nil { + // // println(err.Error()) + // continue + // } + + // children = append(children, childFile) + + // } + return children, nil +} + +func (fs *WebFileSystem) listDirByObjectID(dirId primitive.ObjectID) ([]*FileHeader, error) { dirData := DirectoryData{} - _, err = fs.readFSDocs(dirId, &dirData) + _, err := fs.readFSDocs(dirId, &dirData) if err != nil { return nil, err } - // println(dirId.String()) - // println(dirData.MongoId.String()) - children := []*FileHeader{} for _, childID := range dirData.Children { childFile, err := fs.readFSDocs(childID, nil) diff --git a/webfilesystem/fileuploading.go b/webfilesystem/fileuploading.go index ee565ff..b73ff7b 100644 --- a/webfilesystem/fileuploading.go +++ b/webfilesystem/fileuploading.go @@ -5,13 +5,13 @@ package webfilesystem import ( "errors" "os" - "path" "go.mongodb.org/mongo-driver/bson/primitive" ) -func (fs *WebFileSystem) UploadFile(realFilepath string, parentPath string) error { +func (fs *WebFileSystem) UploadFile(realFilepath string, filePath string) error { //TODO check is file exists + // parentPath := fs.GetParentPath(filePath) file, err := os.ReadFile(realFilepath) if err != nil { return err @@ -33,7 +33,7 @@ func (fs *WebFileSystem) UploadFile(realFilepath string, parentPath string) erro Bin: file, } - filePath := path.Join(parentPath, fileName) + // filePath := path.Join(parentPath, fileName) switch extension { case "jpg": diff --git a/webfilesystem/mongo.go b/webfilesystem/mongo.go index 2a1a23d..1c6da1f 100644 --- a/webfilesystem/mongo.go +++ b/webfilesystem/mongo.go @@ -42,7 +42,33 @@ func (fs *WebFileSystem) writeFileToMongo(file *FileHeader, data interface{}) (p } func (fs *WebFileSystem) removeFromMongo(fileId primitive.ObjectID) error { - return errors.New("todo not implemented yet") + fileHeader, err := fs.readFSDocs(fileId, nil) + if err != nil { + return err + } + + filterHeader := primitive.M{ + "_id": fileHeader.MongoId, + } + res, err := fs.webfsFilesTable.DeleteOne(fs.ctx, filterHeader) + if err != nil { + return err + } + if res.DeletedCount < 1 { + return errors.New("no file header deleted") + } + + filterData := primitive.M{ + "_id": fileHeader.Data, + } + res, err = fs.webfsFilesData.DeleteOne(fs.ctx, filterData) + if err != nil { + return err + } + if res.DeletedCount < 1 { + return errors.New("no file data deleted") + } + return nil } //Deprecated diff --git a/webfilesystem/routes.go b/webfilesystem/routes.go index d88b679..f09a6e1 100644 --- a/webfilesystem/routes.go +++ b/webfilesystem/routes.go @@ -2,6 +2,7 @@ package webfilesystem import ( "net/http" + "personalwebsite/errormessage" "github.com/gin-gonic/gin" ) @@ -14,8 +15,8 @@ func (fs *WebFileSystem) PrivateRoutes(route *gin.RouterGroup) { // ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct // return // } - parentPath := ctx.Query("parentPath") - if parentPath == "" { + filePath := ctx.Query("filePath") + if filePath == "" { ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct return } @@ -33,9 +34,11 @@ func (fs *WebFileSystem) PrivateRoutes(route *gin.RouterGroup) { ctx.SaveUploadedFile(file, dst) //TODO: Not Save to disk - err := fs.UploadFile(dst, parentPath) + err := fs.UploadFile(dst, filePath) if err != nil { - ctx.String(http.StatusInternalServerError, "TODO") //TODO + ctx.JSON(http.StatusInternalServerError, errormessage.ErrorMessage{ + Message: err.Error(), + }) return } @@ -46,27 +49,27 @@ func (fs *WebFileSystem) PrivateRoutes(route *gin.RouterGroup) { ctx.Status(http.StatusCreated) }) - //TODO Support links - route.POST("/createlink", func(ctx *gin.Context) { //TODO To PUT request - sourcePath := ctx.Query("sourcePath") - if sourcePath == "" { - ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct - return - } - targetPath := ctx.Query("targetPath") - if sourcePath == "" { - ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct - return - } + //TODO Support Object links + // route.POST("/createlink", func(ctx *gin.Context) { //TODO To PUT request + // sourcePath := ctx.Query("sourcePath") + // if sourcePath == "" { + // ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct + // return + // } + // targetPath := ctx.Query("targetPath") + // if sourcePath == "" { + // ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct + // return + // } - err := fs.CreateObjectLink(sourcePath, targetPath) - if err != nil { - ctx.String(http.StatusInternalServerError, err.Error()) //TODO - return - } + // err := fs.CreateObjectLink(sourcePath, targetPath) + // if err != nil { + // ctx.String(http.StatusInternalServerError, err.Error()) //TODO + // return + // } - ctx.Status(http.StatusCreated) - }) + // ctx.Status(http.StatusCreated) + // }) // route.GET("writeFile", func(ctx *gin.Context) { // parentPath := ctx.Query("parentPath") diff --git a/webfilesystem/validate.go b/webfilesystem/validate.go index 67d015a..42ffb40 100644 --- a/webfilesystem/validate.go +++ b/webfilesystem/validate.go @@ -1,6 +1,45 @@ package webfilesystem +import ( + "go.mongodb.org/mongo-driver/bson/primitive" +) + func (fs *WebFileSystem) validate() error { + filter := primitive.M{ + // "type": "directory", + } + cur, err := fs.webfsFilesTable.Find(fs.ctx, filter) + if err != nil { + return err + } + + orfanedDir, err := fs.Read("/orfaned", nil) + if err != nil { + return err + } + _ = orfanedDir + for cur.Next(fs.ctx) { + fileHeader := FileHeader{} + cur.Decode(&fileHeader) + if fileHeader.Name == "/" { + continue + } + + res, err := fs.checkFileParent(&fileHeader) + if err != nil { + return err + } + if !res { + println(fileHeader.Name) + err := fs.moveByID(fileHeader.MongoId, primitive.NilObjectID, orfanedDir.MongoId, true) + if err != nil { + println(err.Error()) + println() + continue + } + } + // println() + } // rootHeader, rootData, err := fs.GetRootDir() // if err != nil { // return err @@ -53,6 +92,35 @@ func (fs *WebFileSystem) validate() error { return nil } +func (fs *WebFileSystem) checkFileParent(checkFileHeader *FileHeader) (bool, error) { + filter := primitive.M{ + "type": "directory", + } + cur, err := fs.webfsFilesTable.Find(fs.ctx, filter) + if err != nil { + return false, err + } + + // parentFounded := false + for cur.Next(fs.ctx) { + dirHeader := FileHeader{} + // dirData := DirectoryData{} + cur.Decode(&dirHeader) + _, err := fs.readFSDocs(dirHeader.MongoId, nil) + if err != nil { + return false, err + } + children, err := fs.listDirByObjectID(dirHeader.MongoId) + for _, child := range children { + if child.MongoId == checkFileHeader.MongoId { + return true, nil + } + // println(child.Name) + } + } + return false, nil +} + // func (fs *WebFileSystem) GetChildrenHeaders(directoryID primitive.ObjectID) ([]FileHeader, error) { // fs.ReadByObjectID(directoryID, nil) // } diff --git a/webfilesystem/webfilesystem.go b/webfilesystem/webfilesystem.go index 4efcb6f..6136bcd 100644 --- a/webfilesystem/webfilesystem.go +++ b/webfilesystem/webfilesystem.go @@ -65,8 +65,12 @@ type FrontEndFile struct { ParentPath string `json:"parentPath"` } -//TODO To private, get name from path and set it to file struct, force set newObjectID +//TODO To private, get name from path and set it to file struct; force set newObjectID func (fs *WebFileSystem) Write(filePath string, file *FileHeader, data interface{}) (primitive.ObjectID, primitive.ObjectID, error) { + if fs.CheckFileExist(filePath) { + return primitive.NilObjectID, primitive.NilObjectID, errors.New("file exists") + } + headerId, dataId, err := fs.writeFileToMongo(file, data) if err != nil { return primitive.NilObjectID, primitive.NilObjectID, err @@ -174,7 +178,7 @@ func (fs *WebFileSystem) Move(sourcePath string, targetPath string) error { if err != nil { return err } - + //TODO: use moveByID() if targetParentDirHeader.Type != "directory" { return errors.New("target parent object is not a directory") } @@ -189,7 +193,33 @@ func (fs *WebFileSystem) Move(sourcePath string, targetPath string) error { return err } return nil +} +func (fs *WebFileSystem) moveByID(fileID primitive.ObjectID, oldDirID primitive.ObjectID, newDirID primitive.ObjectID, isForced bool) error { + //TODO check, if directory is child for parent-parent dir and other shit + targetDirData := DirectoryData{} + targetDirHeader, err := fs.readFSDocs(newDirID, &targetDirData) + if err != nil { + return err + } + if targetDirHeader.Type != "directory" { + return errors.New("parent directory path is bad") + } + for _, childID := range targetDirData.Children { + if childID == fileID { + return errors.New("file already in this directory") + } + } + err = fs.RemoveChildToDirectory(fileID, oldDirID) + if err != nil && !isForced { + return err + } + + err = fs.AppendChildToDirectory(fileID, newDirID) + if err != nil { + return err + } + return nil } func (fs *WebFileSystem) Remove(filePath string) error { @@ -221,6 +251,12 @@ func (fs *WebFileSystem) Remove(filePath string) error { if err != nil { return err } + if parentPath == "/orfaned" { //TODO path to struct + err := fs.removeFromMongo(fileId) + if err != nil { + return err + } + } return nil } @@ -271,10 +307,10 @@ func (fs *WebFileSystem) CreatePathLink(sourcePath string, linkPath string) (pri if sourceFileHeader.Type == "pathlink" { return primitive.NilObjectID, primitive.NilObjectID, errors.New("multiplies pathlinks not supported yet") //TODO } - + splittedPath := strings.Split(linkPath, "/") newLinkHeader := FileHeader{ MongoId: primitive.NewObjectID(), - Name: sourceFileHeader.Name, + Name: splittedPath[len(splittedPath)-1], Type: "pathlink", Icon: "", Data: primitive.NewObjectID(), @@ -317,3 +353,11 @@ func (fs *WebFileSystem) GetParentPath(path string) string { } return "/" } + +func (fs *WebFileSystem) CheckFileExist(filePath string) bool { + fileHeader, err := fs.Read(filePath, nil) + if err == nil && fileHeader != nil { + return true + } + return false +}