This commit is contained in:
cyber-dream 2023-05-17 16:09:22 +03:00
parent f363ebbe10
commit 56038cc284
12 changed files with 269 additions and 58 deletions

View File

@ -61,7 +61,7 @@ func (as *ApplicationsStorage) createApp(appName string, appId string, appPath s
return nil return nil
} }
func (aStorage *ApplicationsStorage) Route(route *gin.RouterGroup) { func (aStorage *ApplicationsStorage) PrivateRoute(route *gin.RouterGroup) {
route.GET("/get", func(ctx *gin.Context) { route.GET("/get", func(ctx *gin.Context) {
appId := ctx.Query("appid") appId := ctx.Query("appid")
if appId == "" { if appId == "" {

View File

@ -0,0 +1,5 @@
package errormessage
type ErrorMessage struct {
Message string `json:"message"`
}

View File

@ -131,15 +131,18 @@ class FinderWindow{
WebDesktopEnvironment.Alert("UWAGA TODO MOVE FILE ERROR") //TODO WebDesktopEnvironment.Alert("UWAGA TODO MOVE FILE ERROR") //TODO
} }
} else { } else {
WebDesktopEnvironment.Alert("Not fixed yet") console.log(event)
return
let formData = new FormData()
let files = event.dataTransfer.files let files = event.dataTransfer.files
for (let i = 0; i < files.length; i++) { for (let i = 0; i < files.length; i++) {
const element = files[i]; const file = files[i];
console.log(element) console.log("file:" + file)
formData.append("file", element) //FIXME Conn reset
const res = await WebFS.UploadFile(file, this.curPath)
if (res){
this.ReRenderDir()
}
} }
return
const params = new URLSearchParams({ const params = new URLSearchParams({
parentPath: this.curPath, parentPath: this.curPath,
}) })
@ -168,7 +171,7 @@ class FinderWindow{
* @param {string} filePath * @param {string} filePath
*/ */
async OpenFile(parentPath, fileName, fileType){ async OpenFile(parentPath, fileName, fileType){
console.log(parentPath, fileName, fileType) // console.log(parentPath, fileName, fileType)
// const splittedPath = filePath.split("/") // const splittedPath = filePath.split("/")
// const fileName = splittedPath[splittedPath.length - 1] // const fileName = splittedPath[splittedPath.length - 1]
const fileExtension = fileName.split(".")[fileName.split(".").length - 1] //FIXME const fileExtension = fileName.split(".")[fileName.split(".").length - 1] //FIXME
@ -258,7 +261,7 @@ class FinderWindow{
let res = false let res = false
switch (event.target.children[0].getAttribute("action")) { switch (event.target.children[0].getAttribute("action")) {
case "createPathLink": 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){ if (res){
this.ReRenderDir() this.ReRenderDir()
} }

View File

@ -16,6 +16,10 @@ document.addEventListener('DOMContentLoaded', function() {
// WebDesktopEnvironment.Open("personal-properties") // WebDesktopEnvironment.Open("personal-properties")
}, false); }, false);
// const ErrorObject = {
// message string
// }
class WebDesktopEnvironment{ class WebDesktopEnvironment{
static Applications = {}; static Applications = {};
static isMobile = false static isMobile = false
@ -31,8 +35,8 @@ class WebDesktopEnvironment{
async loadWDE(){ async loadWDE(){
// await WebDesktopEnvironment.load2('/Applications/Finder.app', [ "desktop", document.querySelector('#desktop-layer')]) // await WebDesktopEnvironment.load2('/Applications/Finder.app', [ "desktop", document.querySelector('#desktop-layer')])
WebDesktopEnvironment.Open('/Applications/Finder.app', ["/home/user/.Desktop", "-desktop", document.querySelector('#desktop-layer')]) await WebDesktopEnvironment.Open('/Applications/Finder.app', ["/home/user/.desktop", "-desktop", document.querySelector('#desktop-layer')])
// WebDesktopEnvironment.Open('/Applications/Finder.app', ["/home/user",]) WebDesktopEnvironment.Open('/Applications/Finder.app', ["/",])
} }
/** /**
@ -82,10 +86,12 @@ class WebDesktopEnvironment{
* @returns {Object | undefined} //FIXME * @returns {Object | undefined} //FIXME
*/ */
static async fetchApp(path){ static async fetchApp(path){
console.log("path: " + path ) // console.log("path: " + path )
const params = new URLSearchParams({path: path, mode: "json"}) const params = new URLSearchParams({path: path, mode: "json"})
const response = await fetch(`/system/loadApp?` + params) const response = await fetch(`/system/loadApp?` + params)
if (response.status != 200){ if (response.status != 200){
const error = await response.json()
WebDesktopEnvironment.Alert(error.message)
return undefined return undefined
} }
//TODO Validate manifest //TODO Validate manifest
@ -363,4 +369,30 @@ class WebFS{
//TODO Validate //TODO Validate
return file 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
}
} }

View File

@ -5,6 +5,7 @@ import (
"net/http" "net/http"
"path" "path"
"personalwebsite/apps" "personalwebsite/apps"
"personalwebsite/errormessage"
"personalwebsite/libs" "personalwebsite/libs"
"personalwebsite/routewde" "personalwebsite/routewde"
"personalwebsite/wde" "personalwebsite/wde"
@ -45,7 +46,7 @@ func PrivateRoutes(webfs *webfilesystem.WebFileSystem, webde *wde.WDE, appsStora
appsStorageGroup := libsGroup.Group("apps") 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) routewde.PublicRoutes(wdeGroup, webde)
} }
fsGroup := systemGroup.Group("fs") fsGroup := systemGroup.Group("fs")
{ {
webfs.PrivateRoutes(fsGroup) webfs.PrivateRoutes(fsGroup)
} }
systemGroup.GET("/loadApp", func(ctx *gin.Context) { systemGroup.GET("/loadApp", func(ctx *gin.Context) {
appPath := ctx.Query("path") appPath := ctx.Query("path")
if appPath == "" { if appPath == "" {
ctx.Status(http.StatusBadRequest) ctx.JSON(http.StatusBadRequest, errormessage.ErrorMessage{
Message: "Path for the App not provided in request",
})
return return
} }
appBundleData := webfilesystem.DirectoryData{} appBundleData := webfilesystem.DirectoryData{}
appBundle, err := webfs.Read(appPath, &appBundleData) appBundle, err := webfs.Read(appPath, &appBundleData)
if err != nil { if err != nil {
ctx.Status(http.StatusInternalServerError) ctx.JSON(http.StatusInternalServerError, errormessage.ErrorMessage{
Message: "Error in read App bundle",
})
return return
} }
if appBundle.Type != "directory" { if appBundle.Type != "directory" {
ctx.Status(http.StatusBadRequest) ctx.JSON(http.StatusBadRequest, errormessage.ErrorMessage{
Message: "App bundle file is bad",
})
return return
} }
appManifestData := apps.ApplicationManifest{} appManifestData := apps.ApplicationManifest{}
appManifestHeader, err := webfs.Read(path.Join(appPath, ".appmanifest"), &appManifestData) appManifestHeader, err := webfs.Read(path.Join(appPath, ".appmanifest"), &appManifestData)
if err != nil { if err != nil {
ctx.Status(http.StatusInternalServerError) ctx.JSON(http.StatusInternalServerError, errormessage.ErrorMessage{
Message: "Error in read App manifest",
})
return return
} }
if appManifestHeader.Type != "application-manifest" { if appManifestHeader.Type != "application-manifest" {
ctx.Status(http.StatusBadRequest) ctx.JSON(http.StatusInternalServerError, errormessage.ErrorMessage{
Message: "Error in read App manifest",
})
return return
} }
ctx.JSON(http.StatusOK, appManifestData) ctx.JSON(http.StatusOK, appManifestData)
}) })
} }

BIN
test-img/myphoto.jpg (Stored with Git LFS)

Binary file not shown.

View File

@ -96,15 +96,37 @@ func (fs *WebFileSystem) ListDir(dirPath string) ([]*FileHeader, error) {
return nil, err 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{} dirData := DirectoryData{}
_, err = fs.readFSDocs(dirId, &dirData) _, err := fs.readFSDocs(dirId, &dirData)
if err != nil { if err != nil {
return nil, err return nil, err
} }
// println(dirId.String())
// println(dirData.MongoId.String())
children := []*FileHeader{} children := []*FileHeader{}
for _, childID := range dirData.Children { for _, childID := range dirData.Children {
childFile, err := fs.readFSDocs(childID, nil) childFile, err := fs.readFSDocs(childID, nil)

View File

@ -5,13 +5,13 @@ package webfilesystem
import ( import (
"errors" "errors"
"os" "os"
"path"
"go.mongodb.org/mongo-driver/bson/primitive" "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 //TODO check is file exists
// parentPath := fs.GetParentPath(filePath)
file, err := os.ReadFile(realFilepath) file, err := os.ReadFile(realFilepath)
if err != nil { if err != nil {
return err return err
@ -33,7 +33,7 @@ func (fs *WebFileSystem) UploadFile(realFilepath string, parentPath string) erro
Bin: file, Bin: file,
} }
filePath := path.Join(parentPath, fileName) // filePath := path.Join(parentPath, fileName)
switch extension { switch extension {
case "jpg": case "jpg":

View File

@ -42,7 +42,33 @@ func (fs *WebFileSystem) writeFileToMongo(file *FileHeader, data interface{}) (p
} }
func (fs *WebFileSystem) removeFromMongo(fileId primitive.ObjectID) error { 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 //Deprecated

View File

@ -2,6 +2,7 @@ package webfilesystem
import ( import (
"net/http" "net/http"
"personalwebsite/errormessage"
"github.com/gin-gonic/gin" "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 // ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct
// return // return
// } // }
parentPath := ctx.Query("parentPath") filePath := ctx.Query("filePath")
if parentPath == "" { if filePath == "" {
ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct
return return
} }
@ -33,9 +34,11 @@ func (fs *WebFileSystem) PrivateRoutes(route *gin.RouterGroup) {
ctx.SaveUploadedFile(file, dst) ctx.SaveUploadedFile(file, dst)
//TODO: Not Save to disk //TODO: Not Save to disk
err := fs.UploadFile(dst, parentPath) err := fs.UploadFile(dst, filePath)
if err != nil { if err != nil {
ctx.String(http.StatusInternalServerError, "TODO") //TODO ctx.JSON(http.StatusInternalServerError, errormessage.ErrorMessage{
Message: err.Error(),
})
return return
} }
@ -46,27 +49,27 @@ func (fs *WebFileSystem) PrivateRoutes(route *gin.RouterGroup) {
ctx.Status(http.StatusCreated) ctx.Status(http.StatusCreated)
}) })
//TODO Support links //TODO Support Object links
route.POST("/createlink", func(ctx *gin.Context) { //TODO To PUT request // route.POST("/createlink", func(ctx *gin.Context) { //TODO To PUT request
sourcePath := ctx.Query("sourcePath") // sourcePath := ctx.Query("sourcePath")
if sourcePath == "" { // if sourcePath == "" {
ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct // ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct
return // return
} // }
targetPath := ctx.Query("targetPath") // targetPath := ctx.Query("targetPath")
if sourcePath == "" { // if sourcePath == "" {
ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct // ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct
return // return
} // }
err := fs.CreateObjectLink(sourcePath, targetPath) // err := fs.CreateObjectLink(sourcePath, targetPath)
if err != nil { // if err != nil {
ctx.String(http.StatusInternalServerError, err.Error()) //TODO // ctx.String(http.StatusInternalServerError, err.Error()) //TODO
return // return
} // }
ctx.Status(http.StatusCreated) // ctx.Status(http.StatusCreated)
}) // })
// route.GET("writeFile", func(ctx *gin.Context) { // route.GET("writeFile", func(ctx *gin.Context) {
// parentPath := ctx.Query("parentPath") // parentPath := ctx.Query("parentPath")

View File

@ -1,6 +1,45 @@
package webfilesystem package webfilesystem
import (
"go.mongodb.org/mongo-driver/bson/primitive"
)
func (fs *WebFileSystem) validate() error { 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() // rootHeader, rootData, err := fs.GetRootDir()
// if err != nil { // if err != nil {
// return err // return err
@ -53,6 +92,35 @@ func (fs *WebFileSystem) validate() error {
return nil 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) { // func (fs *WebFileSystem) GetChildrenHeaders(directoryID primitive.ObjectID) ([]FileHeader, error) {
// fs.ReadByObjectID(directoryID, nil) // fs.ReadByObjectID(directoryID, nil)
// } // }

View File

@ -65,8 +65,12 @@ type FrontEndFile struct {
ParentPath string `json:"parentPath"` 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) { 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) headerId, dataId, err := fs.writeFileToMongo(file, data)
if err != nil { if err != nil {
return primitive.NilObjectID, primitive.NilObjectID, err return primitive.NilObjectID, primitive.NilObjectID, err
@ -174,7 +178,7 @@ func (fs *WebFileSystem) Move(sourcePath string, targetPath string) error {
if err != nil { if err != nil {
return err return err
} }
//TODO: use moveByID()
if targetParentDirHeader.Type != "directory" { if targetParentDirHeader.Type != "directory" {
return errors.New("target parent object is not a 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 err
} }
return nil 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 { func (fs *WebFileSystem) Remove(filePath string) error {
@ -221,6 +251,12 @@ func (fs *WebFileSystem) Remove(filePath string) error {
if err != nil { if err != nil {
return err return err
} }
if parentPath == "/orfaned" { //TODO path to struct
err := fs.removeFromMongo(fileId)
if err != nil {
return err
}
}
return nil return nil
} }
@ -271,10 +307,10 @@ func (fs *WebFileSystem) CreatePathLink(sourcePath string, linkPath string) (pri
if sourceFileHeader.Type == "pathlink" { if sourceFileHeader.Type == "pathlink" {
return primitive.NilObjectID, primitive.NilObjectID, errors.New("multiplies pathlinks not supported yet") //TODO return primitive.NilObjectID, primitive.NilObjectID, errors.New("multiplies pathlinks not supported yet") //TODO
} }
splittedPath := strings.Split(linkPath, "/")
newLinkHeader := FileHeader{ newLinkHeader := FileHeader{
MongoId: primitive.NewObjectID(), MongoId: primitive.NewObjectID(),
Name: sourceFileHeader.Name, Name: splittedPath[len(splittedPath)-1],
Type: "pathlink", Type: "pathlink",
Icon: "", Icon: "",
Data: primitive.NewObjectID(), Data: primitive.NewObjectID(),
@ -317,3 +353,11 @@ func (fs *WebFileSystem) GetParentPath(path string) string {
} }
return "/" return "/"
} }
func (fs *WebFileSystem) CheckFileExist(filePath string) bool {
fileHeader, err := fs.Read(filePath, nil)
if err == nil && fileHeader != nil {
return true
}
return false
}