Compare commits

..

2 Commits

Author SHA1 Message Date
2197356dcc assive commit 2023-05-05 17:44:03 +03:00
ccaebdc667 Add file deletion (not work) 2023-05-05 01:11:11 +03:00
13 changed files with 672 additions and 401 deletions

View File

@ -33,15 +33,15 @@ 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) // b.WriteMock(path)
ctx.JSON(http.StatusOK, "OK") // 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,33 +67,33 @@ func (b *BlogViewerApplication) Route(route *gin.RouterGroup) {
}) })
} }
func (b *BlogViewerApplication) WriteMock(path string) { // func (b *BlogViewerApplication) WriteMock(path string) {
blogFile := webfilesystem.WebFSFile{ // blogFile := webfilesystem.WebFSFile{
MongoId: primitive.NewObjectID(), // MongoId: primitive.NewObjectID(),
Name: "test-1.blog", // Name: "test-1.blog",
Type: "blog-page", // Type: "blog-page",
Data: BlogFileData{ // Data: BlogFileData{
Header: "OMG THIS IS BLOG", // Header: "OMG THIS IS BLOG",
Blocks: []Block{ // Blocks: []Block{
{ // {
Type: "plain-text", // Type: "plain-text",
Data: []string{ // Data: []string{
"Apoqiwepoqiwepo", // "Apoqiwepoqiwepo",
".,mas;dakls;d", // ".,mas;dakls;d",
"q[poqwieqpipoi]", // "q[poqwieqpipoi]",
}, // },
}, // },
}, // },
}, // },
} // }
err := b.fs.CreateFile(&blogFile, path) // err := b.fs.CreateFile(&blogFile, path)
if err != nil { // if err != nil {
println(err.Error()) // println(err.Error())
} // }
} // }
func (b *BlogViewerApplication) Render(path string, isMobile bool) (gin.H, error) { func (b *BlogViewerApplication) Render(path string, isMobile bool) (gin.H, error) {
file, err := b.fs.Read(path) file, err := b.fs.NewRead(path)
if err != nil { if err != nil {
println(err.Error()) println(err.Error())
return nil, err return nil, err

View File

@ -1,7 +1,6 @@
package finder package finder
import ( import (
"net/http"
"personalwebsite/apps" "personalwebsite/apps"
"personalwebsite/wde" "personalwebsite/wde"
"personalwebsite/webfilesystem" "personalwebsite/webfilesystem"
@ -108,38 +107,38 @@ func (f *FinderApplication) RenderContextMenu(context string, data string) gin.H
} }
} }
func (f *FinderApplication) Routes(routes *gin.RouterGroup) { // func (f *FinderApplication) Routes(routes *gin.RouterGroup) {
routes.GET("render", func(ctx *gin.Context) { // routes.GET("render", func(ctx *gin.Context) {
isMobileParam := ctx.Query("isMobile") // isMobileParam := ctx.Query("isMobile")
isMobile := isMobileParam == "true" // isMobile := isMobileParam == "true"
admin := true // admin := true
if isMobile { // if isMobile {
ctx.HTML(http.StatusOK, "finder/mobile-app.tmpl", f.Render(isMobile)) // ctx.HTML(http.StatusOK, "finder/mobile-app.tmpl", f.Render(isMobile))
return // return
} // }
if admin { // if admin {
ctx.HTML(http.StatusOK, "finder/admin-app.tmpl", f.Render(isMobile)) // ctx.HTML(http.StatusOK, "finder/admin-app.tmpl", f.Render(isMobile))
return // return
} // }
ctx.HTML(http.StatusOK, "finder/app.tmpl", f.Render(isMobile)) // ctx.HTML(http.StatusOK, "finder/app.tmpl", f.Render(isMobile))
}) // })
routes.GET("renderMobileDesktop", func(ctx *gin.Context) { // routes.GET("renderMobileDesktop", func(ctx *gin.Context) {
ctx.HTML(http.StatusOK, "finder/mobile-desktop.tmpl", gin.H{}) // ctx.HTML(http.StatusOK, "finder/mobile-desktop.tmpl", gin.H{})
}) // })
routes.GET("renderDesktop", func(ctx *gin.Context) { // routes.GET("renderDesktop", 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
} // }
ctx.HTML(http.StatusOK, "finder/desktop.tmpl", gin.H{}) // ctx.HTML(http.StatusOK, "finder/desktop.tmpl", gin.H{})
}) // })
routes.GET("contextMenu", func(ctx *gin.Context) { // routes.GET("contextMenu", func(ctx *gin.Context) {
context := ctx.Query("context") // context := ctx.Query("context")
data := ctx.Query("data") // data := ctx.Query("data")
ginH := f.RenderContextMenu(context, data) // ginH := f.RenderContextMenu(context, data)
ctx.HTML(http.StatusOK, "wde-widgets/context-menu.tmpl", ginH) // ctx.HTML(http.StatusOK, "wde-widgets/context-menu.tmpl", ginH)
}) // })
} // }

43
apps/finder/routes.go Normal file
View File

@ -0,0 +1,43 @@
package finder
import (
"net/http"
"github.com/gin-gonic/gin"
)
func (f *FinderApplication) Routes(routes *gin.RouterGroup) {
routes.GET("render", func(ctx *gin.Context) {
isMobileParam := ctx.Query("isMobile")
isMobile := isMobileParam == "true"
admin := true
if isMobile {
ctx.HTML(http.StatusOK, "finder/mobile-app.tmpl", f.Render(isMobile))
return
}
if admin {
ctx.HTML(http.StatusOK, "finder/admin-app.tmpl", f.Render(isMobile))
return
}
ctx.HTML(http.StatusOK, "finder/app.tmpl", f.Render(isMobile))
})
routes.GET("renderMobileDesktop", func(ctx *gin.Context) {
ctx.HTML(http.StatusOK, "finder/mobile-desktop.tmpl", gin.H{})
})
routes.GET("renderDesktop", func(ctx *gin.Context) {
path := ctx.Query("path")
if path == "" {
ctx.JSON(http.StatusBadRequest, "no path provided")
return
}
ctx.HTML(http.StatusOK, "finder/desktop.tmpl", gin.H{})
})
routes.GET("contextMenu", func(ctx *gin.Context) {
context := ctx.Query("context")
data := ctx.Query("data")
ginH := f.RenderContextMenu(context, data)
ctx.HTML(http.StatusOK, "wde-widgets/context-menu.tmpl", ginH)
})
}

View File

@ -55,7 +55,7 @@ func (p *ImgViewerApp) GetId() string {
} }
func (p *ImgViewerApp) Render(path string, isMobile bool) (gin.H, error) { func (p *ImgViewerApp) Render(path string, isMobile bool) (gin.H, error) {
img, err := p.fs.Read(path) img, err := p.fs.NewRead(path)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -50,113 +50,113 @@ func (p *PersonalPropertiesApp) GetId() string {
return p.manifest.AppId return p.manifest.AppId
} }
func (p *PersonalPropertiesApp) WriteToDb() { // func (p *PersonalPropertiesApp) WriteToDb() {
allProps := make([]PropIsland, 0) // allProps := make([]PropIsland, 0)
// careerProps := make([]Prop, 0) // // careerProps := make([]Prop, 0)
expertiseIsland := PropIsland{ // expertiseIsland := PropIsland{
Header: "Area Of Expertise", // Header: "Area Of Expertise",
Props: []PropElement{{ // Props: []PropElement{{
Key: "Programming", // Key: "Programming",
Values: []string{ // Values: []string{
"Creating tools and plugins for artists", // "Creating tools and plugins for artists",
"Editor and basic gameplay scripting", // "Editor and basic gameplay scripting",
}, // },
}, // },
{ // {
Key: "Game Art", // Key: "Game Art",
Values: []string{ // Values: []string{
"Professional modeling", // "Professional modeling",
"Complete knowledge in CG render theory", // "Complete knowledge in CG render theory",
}, // },
}, // },
}, // },
} // }
eduIsland := PropIsland{ // eduIsland := PropIsland{
Header: "Education", // Header: "Education",
Props: []PropElement{ // Props: []PropElement{
{ // {
Key: "Gymnasium 526", // Key: "Gymnasium 526",
KeyComments: []string{"2005-2015"}, // KeyComments: []string{"2005-2015"},
Values: []string{"Extended natural sciences course", "Additional C++, media production and computer graphics courses", "Winner of conference “The future of a strong Russia is in high technology” in programming section"}, // Values: []string{"Extended natural sciences course", "Additional C++, media production and computer graphics courses", "Winner of conference “The future of a strong Russia is in high technology” in programming section"},
}, // },
{ // {
Key: "Lyceum 281", // Key: "Lyceum 281",
KeyComments: []string{"2015-2016"}, // KeyComments: []string{"2015-2016"},
Values: []string{"Extended IT and Physical sciences course"}, // Values: []string{"Extended IT and Physical sciences course"},
}, // },
{ // {
Key: "University", // Key: "University",
KeyComments: []string{"2017-2019"}, // KeyComments: []string{"2017-2019"},
Values: []string{"Faculty: Info-communication Networks and Systems", "Specialty: Information Security"}, // Values: []string{"Faculty: Info-communication Networks and Systems", "Specialty: Information Security"},
}, // },
}, // },
} // }
careerProps := PropIsland{ // careerProps := PropIsland{
Header: "Career", // Header: "Career",
Props: []PropElement{ // Props: []PropElement{
{ // {
Key: "VR lab assistant", // Key: "VR lab assistant",
KeyComments: []string{"Academy of Digital Technologies", "2019-2020"}, // KeyComments: []string{"Academy of Digital Technologies", "2019-2020"},
Values: []string{"Teaching lessons for students in Unreal Engine 4, Unity and Blender editor courses", "Training students for World Skills Russia"}, // Values: []string{"Teaching lessons for students in Unreal Engine 4, Unity and Blender editor courses", "Training students for World Skills Russia"},
}, // },
{ // {
Key: "3d artist", // Key: "3d artist",
KeyComments: []string{"Space Time VR", "2020-2020"}, // KeyComments: []string{"Space Time VR", "2020-2020"},
Values: []string{"Creating 3d assets for VR game"}, // Values: []string{"Creating 3d assets for VR game"},
}, // },
{ // {
Key: "Jr. Techartist", // Key: "Jr. Techartist",
KeyComments: []string{"MP Games"}, // KeyComments: []string{"MP Games"},
Values: []string{"Game content integration and production", "Shader coding", "Optimization asset production in artists pipeline"}, // Values: []string{"Game content integration and production", "Shader coding", "Optimization asset production in artists pipeline"},
}, // },
{ // {
Key: "Techartist", // Key: "Techartist",
Values: []string{"Game content optimization and production", "Profiling and debugging render pipeline", "Creating in-house tools for pipeline software", "Working process pipeline integration and maintenance", "Linux servers administration"}, // Values: []string{"Game content optimization and production", "Profiling and debugging render pipeline", "Creating in-house tools for pipeline software", "Working process pipeline integration and maintenance", "Linux servers administration"},
}, // },
}, // },
} // }
volunteerProps := PropIsland{ // volunteerProps := PropIsland{
Header: "Volunteer Experience", // Header: "Volunteer Experience",
Props: []PropElement{ // Props: []PropElement{
{ // {
Key: "Metrostroi Mod", // Key: "Metrostroi Mod",
Values: []string{ // Values: []string{
"Help unite fragmented community on one social platform", // "Help unite fragmented community on one social platform",
"Worked on social elements of official site, create ranking", // "Worked on social elements of official site, create ranking",
"Took a part on creating ranking system for players", // "Took a part on creating ranking system for players",
"Creating models and maps for Steam Workshop"}, // "Creating models and maps for Steam Workshop"},
}, // },
{ // {
Key: "Age of Silence", // Key: "Age of Silence",
Values: []string{ // Values: []string{
"Start as tech-artist, create naming system in big ue4 project", // "Start as tech-artist, create naming system in big ue4 project",
"Promoted to chief of 3d Department", // "Promoted to chief of 3d Department",
"Project win Unreal Day 2019", // "Project win Unreal Day 2019",
}, // },
}, // },
}, // },
} // }
allProps = append(allProps, expertiseIsland, careerProps, eduIsland, volunteerProps) // allProps = append(allProps, expertiseIsland, careerProps, eduIsland, volunteerProps)
file := webfilesystem.WebFSFile{ // file := webfilesystem.WebFSFile{
MongoId: primitive.NewObjectID(), // MongoId: primitive.NewObjectID(),
Name: "personal.props", // Name: "personal.props",
Type: "props", // Type: "props",
Data: PropertiesFile{ // Data: PropertiesFile{
Props: allProps, // Props: allProps,
}, // },
} // }
err := p.fs.CreateFile(&file, "/home/user/") // err := p.fs.CreateFile(&file, "/home/user/")
if err != nil { // if err != nil {
println(err.Error()) // println(err.Error())
} else { // } else {
println("Ok") // println("Ok")
} // }
} // }
func (p *PersonalPropertiesApp) Render() (gin.H, error) { func (p *PersonalPropertiesApp) Render() (gin.H, error) {
props, err := p.fs.Read("/home/user/personal.props") props, err := p.fs.NewRead("/home/user/personal.props")
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -46,7 +46,7 @@ func (l *ImagLib) Route(route *gin.RouterGroup) {
return return
} }
file, err := l.fs.Read(path) file, err := l.fs.NewRead(path)
if err != nil { if err != nil {
ctx.String(http.StatusInternalServerError, "TODO") //TODO ctx.String(http.StatusInternalServerError, "TODO") //TODO
} }

View File

@ -30,19 +30,19 @@ class Finder{
newWindow.innerHTML = html newWindow.innerHTML = html
this.fileView = new FileView(newWindow.querySelector(".FileTileView"), this.fileView = new FileView(newWindow.querySelector(".FileTileView"),
(event) =>{ this.Open(event, false) }, (event) =>{ this.Click(event) },
(event) =>{ this.RightClick(event) }, (event) =>{ this.RightClick(event) },
(event) =>{ this.FileUploading(event) }, (event) =>{ this.FileUploading(event) },
) )
this.OpenDir(this.path) this.OpenDir(this.path)
newWindow.querySelector("#BackButton").addEventListener('click', () =>{ // newWindow.querySelector("#BackButton").addEventListener('click', () =>{
this.OpenPreviousDir() // this.OpenPreviousDir()
}) // })
newWindow.querySelector("#HomeButton").addEventListener('click', () =>{ // newWindow.querySelector("#HomeButton").addEventListener('click', () =>{
this.OpenDir(this.homePath) // this.OpenDir(this.homePath)
}) // })
this.windowElement = newWindow this.windowElement = newWindow
@ -102,7 +102,7 @@ class Finder{
args[2].innerHTML = html args[2].innerHTML = html
this.fileView = new FileView(args[2].querySelector(".FileTileView"), (event) =>{ this.fileView = new FileView(args[2].querySelector(".FileTileView"), (event) =>{
this.Open(event, true) this.Click(event, true)
}) })
this.OpenDir(this.path) this.OpenDir(this.path)
}) })
@ -111,55 +111,53 @@ class Finder{
}) })
} }
OpenPreviousDir(){ // OpenPreviousDir(){
if (this.pathHistory.length > 0){ // if (this.pathHistory.length > 0){
// console.log(this.pathHistory) // // console.log(this.pathHistory)
let path = this.pathHistory[this.pathHistory.length - 1] // let path = this.pathHistory[this.pathHistory.length - 1]
// console.log(typeof( this.pathHistory)) // // console.log(typeof( this.pathHistory))
this.pathHistory.pop() // this.pathHistory.pop()
this.OpenDir(this.path) // this.OpenDir(this.path)
} // }
} // }
/** /**
* @param {string} path * @param {string} path
*/ */
OpenDir(path){ OpenDir(path){
this.pathHistory += this.path
this.path = path
this.fileView.OpenFolder(this.path) this.fileView.OpenFolder(this.path)
} }
/** /**
* @param {MouseEvent} event
* @param {boolean} inNewWindow
*/ */
Click(event, inNewWindow){ OpenNewDir(){
WebDesktopEnvironment.Open("finder", [this.path])
} }
/** /**
* @param {MouseEvent} event * @param {MouseEvent} event
* @param {boolean} inNewWindow
*/ */
Open(event, inNewWindow){ RightClick(event){
this.CreateContextMenu(event.target, [event.clientY, event.clientX])
}
/**
* @param {MouseEvent} event
*/
Click(event){
let fileType = event.target.getAttribute("fileType") let fileType = event.target.getAttribute("fileType")
let fileName = event.target.getAttribute("name") let fileName = event.target.getAttribute("name")
switch (fileType) { switch (fileType) {
case "directory": case "directory":
if (inNewWindow){ WebDesktopEnvironment.Open("finder", [`${this.path}/${fileName}`]) //FIXME this.path is shared for all windows
WebDesktopEnvironment.Open("finder", ["/home/user/" + fileName]) //FIXME this.path is shared for all windows
break
}
this.OpenDir(this.path +"/" + fileName)
break break
case "blog-page": case "blog-page":
WebDesktopEnvironment.Open("blog-viewer", [this.path + "/" + fileName]) WebDesktopEnvironment.Open("blog-viewer", [`${this.path}/${fileName}`])
break break
case "deleteFile": case "deleteFile":
fetch(`/fs/delete` + new URLSearchParams({ fetch(`/fs/delete` + new URLSearchParams({
path: "/home/user/" + fileName //FIXME path: `${this.path}/${fileName}` //FIXME
})) }))
.then((response) => { .then((response) => {
console.log(response.status) console.log(response.status)
@ -182,10 +180,6 @@ class Finder{
} }
} }
RightClick(event){
this.CreateContextMenu(event.target, [event.clientY, event.clientX])
}
CreateContextMenu(target, pos){ CreateContextMenu(target, pos){
let context = "" let context = ""
if (target.classList.contains("FileTileView")) if (target.classList.contains("FileTileView"))

View File

@ -22,7 +22,7 @@ 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.List(path) list, err := w.fs.NewList(path)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -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.List(directory) list, err := w.fs.NewList(directory)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -0,0 +1,36 @@
package webfilesystem
import (
"github.com/mitchellh/mapstructure"
"go.mongodb.org/mongo-driver/bson/primitive"
)
type DirectoryData struct {
Parent primitive.ObjectID `bson:"parent"`
Children []primitive.ObjectID `bson:"children"`
}
// type Directory struct {
// Header Header `bson:"header"`
// Data DirectoryData `bson:"data"`
// }
// func (d *Directory) Get() interface{} {
// return d
// }
func castToFile(raw *interface{}) *WebFSFile {
var dirPtr interface{} = *raw
return dirPtr.(*WebFSFile)
}
func castToDirectory(data interface{}) (*FolderData, error) {
dirData := FolderData{}
err := mapstructure.Decode(data.(primitive.D).Map(), &dirData)
if err != nil {
return nil, err
}
return &dirData, nil
}
// func List()

37
webfilesystem/mongo.go Normal file
View File

@ -0,0 +1,37 @@
package webfilesystem
import (
"context"
"go.mongodb.org/mongo-driver/bson/primitive"
)
type readStruct struct {
File interface{}
Filter interface{}
}
func (fs *WebFileSystem) readMongo(read readStruct) (*interface{}, error) {
err := fs.webfsCollection.FindOne(fs.ctx, read.Filter).Decode(read.File)
if err != nil {
return nil, err
}
return &read.File, nil
}
func (fs *WebFileSystem) writeMongo(file WebFSFile, parentPath string) (primitive.ObjectID, error) {
//TODO Check file existance
parentDir, err := fs.NewRead(parentPath)
if err != nil {
return primitive.NilObjectID, err
}
res, err := fs.webfsCollection.InsertOne(context.Background(), &file)
if err != nil {
return primitive.NilObjectID, err
}
fileId := fs.castInsertId(res)
fs.insertFileToDirectory(fileId, parentDir.MongoId)
return fileId, nil
}

View File

@ -0,0 +1,83 @@
package webfilesystem
import (
"errors"
"go.mongodb.org/mongo-driver/bson/primitive"
)
func (fs *WebFileSystem) NewRead(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
}
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: FolderData{
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) NewList(dirPath string) ([]*WebFSFile, error) {
dirFile, err := fs.NewRead(dirPath)
if err != nil {
return nil, err
}
if dirFile.Type != "directory" {
return nil, errors.New("file is not a directory")
}
fileData, err := castToDirectory(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) CreateFile(file *WebFSFile, parentPath string) error {
fs.writeMongo(*file, parentPath)
return errors.New("Not ready yet")
}

149
webfilesystem/routes.go Normal file
View File

@ -0,0 +1,149 @@
package webfilesystem
import (
"net/http"
"github.com/gin-gonic/gin"
)
func (fs *WebFileSystem) Route(route *gin.RouterGroup) {
route.POST("/upload", func(ctx *gin.Context) { //TODO To PUT request
// fileName := ctx.Query("fileName")
// if fileName == "" {
// ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct
// return
// }
path := ctx.Query("path")
if path == "" {
ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct
return
}
// single file
file, _ := ctx.FormFile("file")
if file == nil {
ctx.String(http.StatusBadRequest, "file is nil")
return
}
// generateMins := c.Param("generateMins")
// log.Println(file.Filename)
// Upload the file to specific dst.
dst := "./test-img/" + file.Filename
ctx.SaveUploadedFile(file, dst)
//TODO: Not Save to disk
err := fs.UploadFile(dst, path)
if err != nil {
ctx.String(http.StatusInternalServerError, "TODO") //TODO
return
}
// webFsCollection.CreateMiniatures("./test-img/", file.Filename)
// webfs.CreateFile(&img, "/home/user/")
ctx.Status(http.StatusCreated)
})
// route.GET("writeFile", func(ctx *gin.Context) {
// parentPath := ctx.Query("parentPath")
// if parentPath == "" {
// ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct
// return
// }
// file := WebFSFile{
// MongoId: primitive.NewObjectID(),
// Name: "pp",
// Type: "test",
// }
// err := fs.NewCreateFile(&file, parentPath)
// if err != nil {
// ctx.JSON(http.StatusInternalServerError, "TODO") //TODO json error struct
// return
// }
// ctx.JSON(http.StatusOK, "OK")
// })
// route.GET("init", func(ctx *gin.Context) {
// err := fs.InitFS()
// if err != nil {
// ctx.JSON(http.StatusInternalServerError, err.Error()) //TODO json error struct
// return
// }
// ctx.JSON(http.StatusOK, "OK")
// })
route.GET("createDir", func(ctx *gin.Context) {
path := ctx.Query("path")
if path == "" {
ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct
return
}
_, err := fs.NewCreateDirectory(path)
if err != nil {
ctx.JSON(http.StatusInternalServerError, err.Error()) //TODO json error struct
return
}
ctx.JSON(http.StatusOK, "OK")
})
route.GET("list", func(ctx *gin.Context) {
path := ctx.Query("path")
if path == "" {
ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct
return
}
files, err := fs.NewList(path)
if err != nil {
ctx.JSON(http.StatusInternalServerError, "TODO") //TODO json error struct
return
}
ctx.JSON(http.StatusOK, &files)
})
route.GET("read", func(ctx *gin.Context) {
path := ctx.Query("path")
if path == "" {
ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct
return
}
file, err := fs.NewRead(path)
if err != nil {
ctx.JSON(http.StatusInternalServerError, "TODO") //TODO json error struct
return
}
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)
})
route.GET("delete", func(ctx *gin.Context) {
path := ctx.Query("path")
if path == "" {
ctx.Status(http.StatusBadRequest) //TODO
return
}
err := fs.Delete(path)
if err != nil {
ctx.Status(http.StatusInternalServerError)
return
}
ctx.Status(http.StatusOK)
})
}

View File

@ -3,11 +3,9 @@ package webfilesystem
import ( import (
"context" "context"
"errors" "errors"
"net/http"
"strconv" "strconv"
"strings" "strings"
"github.com/gin-gonic/gin"
"github.com/mitchellh/mapstructure" "github.com/mitchellh/mapstructure"
"go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/bson/primitive"
@ -17,25 +15,27 @@ import (
type WebFileSystem struct { type WebFileSystem struct {
webfsCollection *mongo.Collection webfsCollection *mongo.Collection
// folders []*Folder // folders []*Folder
ctx context.Context
} }
func NewWebFileSystem(mongoClient *mongo.Client, dBName string, fsCollectionName string) *WebFileSystem { func NewWebFileSystem(mongoClient *mongo.Client, dBName string, fsCollectionName string) *WebFileSystem {
return &WebFileSystem{ return &WebFileSystem{
webfsCollection: mongoClient.Database(dBName).Collection(fsCollectionName), // TODO Check collection is exist webfsCollection: mongoClient.Database(dBName).Collection(fsCollectionName), // TODO Check collection is exist
ctx: context.Background(),
} }
} }
func (fs *WebFileSystem) Read(path string) (*WebFSFile, error) { // func (fs *WebFileSystem) Read(path string) (*WebFSFile, error) {
splittedPath := fs.SplitPath(path) // splittedPath := fs.SplitPath(path)
filter := primitive.D{ // filter := primitive.D{
{ // {
Key: "name", // Key: "name",
Value: splittedPath[len(splittedPath)-1], // Value: splittedPath[len(splittedPath)-1],
}, // },
} // }
file, err := fs.findFileInMongo(filter) // file, err := fs.findFileInMongo(filter)
return file, err // return file, err
} // }
func (fs *WebFileSystem) ReadByObjectID(objectId primitive.ObjectID) (*WebFSFile, error) { func (fs *WebFileSystem) ReadByObjectID(objectId primitive.ObjectID) (*WebFSFile, error) {
filter := primitive.D{ filter := primitive.D{
@ -58,76 +58,93 @@ func (fs *WebFileSystem) findFileInMongo(filter primitive.D) (*WebFSFile, error)
return &file, nil return &file, nil
} }
func (fs *WebFileSystem) List(path string) ([]*WebFSFile, error) { // func (fs *WebFileSystem) List(path string) ([]*WebFSFile, error) {
// dirFile, err := fs.Read(fs.GetParentPath(path)) // // dirFile, err := fs.Read(fs.GetParentPath(path))
dirFile, err := fs.Read(path) // dirFile, err := fs.Read(path)
if err != nil { // if err != nil {
return nil, err // return nil, err
} // }
if dirFile.Type != "directory" { // if dirFile.Type != "directory" {
return nil, errors.New("file is not a directory") // return nil, errors.New("file is not a directory")
} // }
fileData := FolderData{} // fileData := FolderData{}
err = mapstructure.Decode(dirFile.Data.(primitive.D).Map(), &fileData) // err = mapstructure.Decode(dirFile.Data.(primitive.D).Map(), &fileData)
if err != nil { // if err != nil {
return nil, err // 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
// }
files := []*WebFSFile{} // func (fs *WebFileSystem) CreateDirectory(path string) error {
for _, child := range fileData.Children { // splittedpath := fs.SplitPath(path)
file, err := fs.ReadByObjectID(child) // parentPath := fs.GetParentPath(path)
if err != nil { // parentDir, err := fs.Read(parentPath)
println(err.Error())
continue
}
files = append(files, file)
}
return files, nil
}
func (fs *WebFileSystem) CreateDirectory(path string) error {
splittedpath := fs.SplitPath(path)
parentPath := fs.GetParentPath(path)
parentDir, err := fs.Read(parentPath)
if err != nil {
return err
}
directory := WebFSFile{
MongoId: primitive.NewObjectID(),
Name: splittedpath[len(splittedpath)-1],
Type: "directory",
Data: FolderData{
Parent: parentDir.MongoId,
Children: []primitive.ObjectID{},
},
}
fs.CreateFile(&directory, parentPath)
// res, err := fs.webfsCollection.InsertOne(context.Background(), &directory)
// if err != nil { // if err != nil {
// return err // return err
// } // }
// directory := WebFSFile{
// MongoId: primitive.NewObjectID(),
// Name: splittedpath[len(splittedpath)-1],
// Type: "directory",
// Data: FolderData{
// Parent: parentDir.MongoId,
// Children: []primitive.ObjectID{},
// },
// }
// fs.CreateFile(&directory, parentPath)
// // res, err := fs.webfsCollection.InsertOne(context.Background(), &directory) //TODO
// // if err != nil {
// // return err
// // }
// // fileId := fs.castInsertId(res)
// // fs.insertFileToDirectory(fileId, parentDir.MongoId)
// return nil
// }
// func (fs *WebFileSystem) UpdateFile(filePath string, update primitive.M) error {
// file, err := fs.Read(filePath)
// if err != nil {
// return err
// }
// if file.MongoId.IsZero() {
// return errors.New("mongo id is zero")
// }
// filter := primitive.M{
// "_id": file.MongoId,
// }
// _, err = fs.webfsCollection.UpdateOne(context.Background(), filter, primitive.M{"$set": update})
// if err != nil {
// return err
// }
// return nil
// }
// func (fs *WebFileSystem) CreateFile(file *WebFSFile, parentPath string) error {
// //TODO Check file existance
// parentDir, err := fs.Read(parentPath)
// if err != nil {
// return err
// }
// res, err := fs.webfsCollection.InsertOne(context.Background(), &file)
// if err != nil {
// return err
// }
// _ = parentDir
// fileId := fs.castInsertId(res) // fileId := fs.castInsertId(res)
// fs.insertFileToDirectory(fileId, parentDir.MongoId) // fs.insertFileToDirectory(fileId, parentDir.MongoId)
return nil // return nil
} // }
func (fs *WebFileSystem) CreateFile(file *WebFSFile, parentPath string) error {
//TODO Check file existance
parentDir, err := fs.Read(parentPath)
if err != nil {
return err
}
res, err := fs.webfsCollection.InsertOne(context.Background(), &file)
if err != nil {
return err
}
_ = parentDir
fileId := fs.castInsertId(res)
fs.insertFileToDirectory(fileId, parentDir.MongoId)
return nil
}
func (fs *WebFileSystem) castInsertId(res *mongo.InsertOneResult) primitive.ObjectID { func (fs *WebFileSystem) castInsertId(res *mongo.InsertOneResult) primitive.ObjectID {
return res.InsertedID.(primitive.ObjectID) return res.InsertedID.(primitive.ObjectID)
@ -175,122 +192,35 @@ func (fs *WebFileSystem) GetParentPath(path string) string {
return parentPath return parentPath
} }
func (fs *WebFileSystem) Route(route *gin.RouterGroup) { func (fs *WebFileSystem) Delete(filePath string) error {
route.POST("/upload", func(ctx *gin.Context) { //TODO To PUT request splittedPath := fs.SplitPath(filePath)
// fileName := ctx.Query("fileName") parentPath := strings.Join(splittedPath[:len(splittedPath)-1], "/")
// if fileName == "" {
// ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct file, err := fs.NewRead(filePath)
// return if err != nil {
return err
}
parentDir, err := fs.NewRead(parentPath)
if err != nil {
return err
}
parentDir.Data.(primitive.D).Map()
// update:= primitive.M{
// "data.children":
// } // }
path := ctx.Query("path") // filter := primitive.M{}
if path == "" { res, err := fs.webfsCollection.UpdateByID(context.Background(), parentDir.MongoId, primitive.M{"$unset": bson.M{"data.children." + file.MongoId.String(): ""}})
ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct // res, err := fs.webfsCollection.UpdateOne(context.Background(), filter, primitive.M{"$unset": bson.M{"data.children." + file.MongoId.String(): ""}})
return
}
// single file
file, _ := ctx.FormFile("file")
if file == nil {
ctx.String(http.StatusBadRequest, "file is nil")
return
}
// generateMins := c.Param("generateMins")
// log.Println(file.Filename)
// Upload the file to specific dst.
dst := "./test-img/" + file.Filename
ctx.SaveUploadedFile(file, dst)
//TODO: Not Save to disk
err := fs.UploadFile(dst, path)
if err != nil { if err != nil {
ctx.String(http.StatusInternalServerError, "TODO") //TODO return err
return
} }
if res.MatchedCount < 1 {
// webFsCollection.CreateMiniatures("./test-img/", file.Filename) return errors.New("no documents found")
// webfs.CreateFile(&img, "/home/user/")
ctx.Status(http.StatusCreated)
})
route.GET("writeFile", func(ctx *gin.Context) {
parentPath := ctx.Query("parentPath")
if parentPath == "" {
ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct
return
} }
file := WebFSFile{ return nil
MongoId: primitive.NewObjectID(),
Name: "pp",
Type: "test",
Data: nil,
}
err := fs.CreateFile(&file, parentPath)
if err != nil {
ctx.JSON(http.StatusInternalServerError, "TODO") //TODO json error struct
return
}
ctx.JSON(http.StatusOK, "OK")
})
route.GET("createDir", func(ctx *gin.Context) {
path := ctx.Query("path")
if path == "" {
ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct
return
}
err := fs.CreateDirectory(path)
if err != nil {
ctx.JSON(http.StatusInternalServerError, "TODO") //TODO json error struct
return
}
ctx.JSON(http.StatusOK, "OK")
})
route.GET("list", func(ctx *gin.Context) {
path := ctx.Query("path")
if path == "" {
ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct
return
}
files, err := fs.List(path)
if err != nil {
ctx.JSON(http.StatusInternalServerError, "TODO") //TODO json error struct
return
}
ctx.JSON(http.StatusOK, &files)
})
route.GET("read", func(ctx *gin.Context) {
path := ctx.Query("path")
if path == "" {
ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct
return
}
file, err := fs.Read(path)
if err != nil {
ctx.JSON(http.StatusInternalServerError, "TODO") //TODO json error struct
return
}
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 { func (fs *WebFileSystem) Validate() error {