Compare commits

...

5 Commits

Author SHA1 Message Date
405f45e788 Initial file props window 2023-05-06 01:07:09 +03:00
c95501dbb7 Working img viewer 2023-05-05 23:31:42 +03:00
5736b8de31 File Deleting and new decoding 2023-05-05 21:32:41 +03:00
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
18 changed files with 876 additions and 582 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,11 +1,9 @@
package finder package finder
import ( import (
"net/http"
"personalwebsite/apps" "personalwebsite/apps"
"personalwebsite/wde" "personalwebsite/wde"
"personalwebsite/webfilesystem" "personalwebsite/webfilesystem"
"strings"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@ -32,114 +30,84 @@ func (f *FinderApplication) GetId() string {
} }
func (f *FinderApplication) Render(isMobile bool) gin.H { func (f *FinderApplication) Render(isMobile bool) gin.H {
return gin.H{} return gin.H{}
} }
func (f *FinderApplication) RenderContextMenu(context string, data string) gin.H { func (f *FinderApplication) RenderContextMenu(context string, data string) gin.H {
islands := [][]wde.ContexMenuRow{} //FIXME islands := [][]wde.ContexMenuRow{}
switch context {
case "FileTileView": islands = append(islands, []wde.ContexMenuRow{
islands = [][]wde.ContexMenuRow{ {Label: "Get Info", Action: "getInfo"},
{ {Label: "New Directory", Action: "createDir"},
{ })
Label: "Get Info", if context == "FileTileView" {
Action: strings.Join([]string{"getInfo"}[:], ","), return gin.H{
}, "Islands": islands,
},
{
{
Label: "New Directory",
Action: strings.Join([]string{"newDir"}[:], ","),
},
},
}
case "directory":
islands = [][]wde.ContexMenuRow{
{
{
Label: "Test",
Action: strings.Join([]string{""}[:], ","),
},
{
Label: "Delete",
Action: strings.Join([]string{""}[:], ","),
},
},
{
{
Label: "Get Info",
Action: strings.Join([]string{""}[:], ","),
},
},
}
default:
islands = [][]wde.ContexMenuRow{
{
{
Label: "temp Menu 1",
Action: strings.Join([]string{""}[:], ","),
},
{
Label: "temp Menu 2",
Action: strings.Join([]string{""}[:], ","),
},
{
Label: "temp Menu 3",
Action: strings.Join([]string{""}[:], ","),
},
{
Label: "temp Menu 4",
Action: strings.Join([]string{""}[:], ","),
},
},
} }
} }
islands = append(islands, []wde.ContexMenuRow{ islands = append(islands, []wde.ContexMenuRow{
{ {Label: "Delete File", Action: "deleteFile"},
Label: "Delete File", // {Label: "Get Info", Action: "getInfo"},
Action: strings.Join([]string{"deleteFile"}[:], ";"),
},
}) })
switch context {
case "directory":
default:
islands = append(islands, []wde.ContexMenuRow{
{Label: "temp Menu 1", Action: ""},
{Label: "temp Menu 2", Action: ""},
})
}
return gin.H{ return gin.H{
"Islands": islands, "Islands": islands,
} }
} }
func (f *FinderApplication) Routes(routes *gin.RouterGroup) { func (f *FinderApplication) RenderProps(filePath string) gin.H {
routes.GET("render", func(ctx *gin.Context) { file, err := f.fs.NewRead(filePath)
isMobileParam := ctx.Query("isMobile") if err != nil {
isMobile := isMobileParam == "true" return nil
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))
}) return gin.H{
routes.GET("renderMobileDesktop", func(ctx *gin.Context) { "file": file,
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)
})
} }
// 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)
// })
// }

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

@ -0,0 +1,49 @@
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)
})
routes.GET("renderProps", func(ctx *gin.Context) {
filePath := ctx.Query("path")
ginH := f.RenderProps(filePath)
ctx.HTML(http.StatusOK, "finder/props.tmpl", ginH)
})
}

View File

@ -3,7 +3,6 @@ package imgviewer
import ( import (
"net/http" "net/http"
websiteapp "personalwebsite/apps" websiteapp "personalwebsite/apps"
"personalwebsite/libs"
"personalwebsite/webfilesystem" "personalwebsite/webfilesystem"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@ -54,17 +53,25 @@ func (p *ImgViewerApp) GetId() string {
return p.manifest.AppId return p.manifest.AppId
} }
func (p *ImgViewerApp) Render(path string, isMobile bool) (gin.H, error) { func (p *ImgViewerApp) Render(filePath string, isMobile bool) (gin.H, error) {
img, err := p.fs.Read(path) // file, err := p.fs.NewRead(filePath)
if err != nil { // if err != nil {
return nil, err // return nil, err
} // }
data, err := libs.ReadImage(img) // println(file.Data.(primitive.Binary).Data)
if err != nil {
return nil, err // img, err := p.fs.NewRead(path)
} // if err != nil {
// return nil, err
// }
// data, err := libs.ReadImage(img)
// if err != nil {
// return nil, err
// }
// url := location.Get(ctx)
return gin.H{ return gin.H{
"header": data.Header, "imgUrl": "/system/libs/img/get?path=" + filePath,
// "header": data.Header,
// "base64": data.Base64, // "base64": data.Base64,
}, nil }, nil
} }

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,68 +111,57 @@ 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
case "deleteFile":
fetch(`/fs/delete` + new URLSearchParams({
path: "/home/user/" + fileName //FIXME
}))
.then((response) => {
console.log(response.status)
})
.catch((error) => {
WebDesktopEnvironment.Alert(error);
})
break break
// case "app": // case "app":
// //TODO get real id // //TODO get real id
// WebDesktopEnvironment.Open("personal-properties", []) // WebDesktopEnvironment.Open("personal-properties", [])
// break; // break;
case "base64img": case "jpeg":
case "png":
WebDesktopEnvironment.Open("img-viewer", [this.path + "/" + fileName]) WebDesktopEnvironment.Open("img-viewer", [this.path + "/" + fileName])
break; break;
default: default:
@ -182,10 +171,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"))
@ -217,9 +202,64 @@ class Finder{
overlay.appendChild(menu) overlay.appendChild(menu)
document.body.appendChild(overlay) document.body.appendChild(overlay)
overlay.addEventListener('click',(event) => { overlay.addEventListener('click', (event) => {
if (event.target.classList.contains("Row")){ //TODO add uuid id to rows to more accurate checks?? if (event.target.classList.contains("Row")){ //TODO add uuid id to rows to more accurate checks??
let fileType = target.getAttribute("fileType")
let fileName = target.getAttribute("name")
switch (event.target.children[0].getAttribute("action")) { switch (event.target.children[0].getAttribute("action")) {
case "createDir":
fetch(`/fs/createDir?` + new URLSearchParams({
path: `${this.path}/New Directory`
}))
.then((response) => {
console.log(response.status)
if (response.status == 200){
this.OpenDir(this.path)
}
})
.catch((error) => {
WebDesktopEnvironment.Alert(error);
})
break
case "deleteFile":
console.log(fileName)
// break
fetch(`/fs/delete?` + new URLSearchParams({
path: `${this.path}/${fileName}`
}))
.then((response) => {
console.log(response.status)
if (response.status == 200){
this.OpenDir(this.path)
}
})
.catch((error) => {
WebDesktopEnvironment.Alert(error);
})
break
case "getInfo":
fetch(`/application/${this.appId}/renderProps?` + new URLSearchParams({
path: `${this.path}/${fileName}`
}))
.then((response) => {
console.log(response)
if (response.status == 200){
console.log("Success")
return response.text();
}
})
.then((html) =>{
let newWindow = WebDesktopEnvironment.CreateNewWindow(this.appId, 350, 500 )
newWindow.innerHTML = html
newWindow.querySelector("#closeWindowButton").addEventListener('click', function (params) {
WebDesktopEnvironment.CloseWindow(newWindow)
})
})
.catch((error) => {
WebDesktopEnvironment.Alert(error);
})
default: default:
break; break;
} }

View File

@ -193,7 +193,7 @@ class WebDesktopEnvironment{
* @param {string} alertText * @param {string} alertText
*/ */
static CreateAlertWindow(alertText){ static CreateAlertWindow(alertText){
console.log("alertWinfdo") // console.log("alertWinfdo")
let newWindow = document.createElement("div") let newWindow = document.createElement("div")
newWindow.setAttribute("class", "WindowFrameless") newWindow.setAttribute("class", "WindowFrameless")
newWindow.setAttribute("windowId", "SuperUniqUUID") //TODO: newWindow.setAttribute("windowId", "SuperUniqUUID") //TODO:

View File

@ -21,7 +21,7 @@ func Route(route *gin.RouterGroup, wde *wde.WDE) {
{ {
widgets.GET("/file-tile-view", func(ctx *gin.Context) { widgets.GET("/file-tile-view", func(ctx *gin.Context) {
url := location.Get(ctx) url := location.Get(ctx)
_ = url // _ = url
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

View File

@ -0,0 +1,53 @@
{{ define "finder/props.tmpl" }}
<div class="TitleBar DragArea">
<button id="closeWindowButton" class="Button" title="Close Window"></button>
<div id="Drag" class="VisualDragArea"></div>
<div class="Lable">
File Properties
</div>
<div id="Drag" class="VisualDragArea"></div>
</div>
<div class="ContentBorder">
<div class="PropertiesList">
<div class="Personal-properties-bio">
<img src="data:{{ .headerProps.Icon.Header }},{{ .headerProps.Icon.Base64 }}" alt="File Icon" style="width: 48px;height: 48px;">
<div class="Personal-properties-textbio">
<div>{{ .file.Name }}</div>
<!-- <div>{{ .headerProps.Info1 }}</div>
<div>{{ .headerProps.Info2 }}</div> -->
</div>
</div>
{{ range $propIsland := .allprops }}
<div id="prop" class="Personal-properties-prop">
<div class="Personal-properties-prop-title">
{{$propIsland.Header}}:
</div>
<div class="Personal-properties-prop-content">
{{range $prop := $propIsland.Props}}
<div class="Personal-properties-prop-row">
<div class="Personal-properties-prop-key">
{{$prop.Key}}:
{{ range $value := $prop.KeyComments }}
<div class="Personal-properties-prop-key-comments">
{{ $value }}
</div>
{{ end }}
</div>
<div class="Personal-properties-prop-values">
{{ range $value := $prop.Values }}
<div class="Personal-properties-prop-value">
{{ $value }}
</div>
{{ end }}
</div>
</div>
{{ end }}
</div>
</div>
{{ end }}
</div>
</div>
</div>
{{ end }}

View File

@ -12,7 +12,7 @@
Toolbar Toolbar
</div> --> </div> -->
<img class="Img-Viewer-Picture-Container"src="data:{{.header}},{{.base64}}"> <img class="Img-Viewer-Picture-Container"src="{{.imgUrl}}">
</div> </div>
{{ end }} {{ end }}

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,84 @@
package webfilesystem
import (
"context"
"strconv"
"github.com/mitchellh/mapstructure"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
type DirectoryData struct {
Parent primitive.ObjectID `bson:"parent"`
Children []primitive.ObjectID `bson:"children"`
}
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: 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) 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

@ -29,7 +29,7 @@ func (fs *WebFileSystem) UploadFile(realFilepath string, path string) error {
Data: file, Data: file,
Icon: "", Icon: "",
} }
err := fs.CreateFile(&newFile, path) err := fs.WriteFile(&newFile, path)
return err return err
case "png": case "png":
newFile := WebFSFile{ newFile := WebFSFile{
@ -38,7 +38,7 @@ func (fs *WebFileSystem) UploadFile(realFilepath string, path string) error {
Type: "png", Type: "png",
Data: file, Data: file,
} }
err := fs.CreateFile(&newFile, path) err := fs.WriteFile(&newFile, path)
return err return err
default: default:
return errors.New("this filetype not allowed") return errors.New("this filetype not allowed")
@ -58,7 +58,7 @@ func (fs *WebFileSystem) UploadBinaryFile(file []byte, fileName string, path str
Data: file, Data: file,
Icon: "", Icon: "",
} }
err := fs.CreateFile(&newFile, path) err := fs.WriteFile(&newFile, path)
return err return err
case "png": case "png":
newFile := WebFSFile{ newFile := WebFSFile{
@ -67,7 +67,7 @@ func (fs *WebFileSystem) UploadBinaryFile(file []byte, fileName string, path str
Type: "png", Type: "png",
Data: file, Data: file,
} }
err := fs.CreateFile(&newFile, path) err := fs.WriteFile(&newFile, path)
return err return err
default: default:
return errors.New("this filetype not allowed") return errors.New("this filetype not allowed")

94
webfilesystem/mongo.go Normal file
View File

@ -0,0 +1,94 @@
package webfilesystem
import (
"context"
"errors"
"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
}
func (fs *WebFileSystem) removeMongo(filePath string) error {
file, err := fs.NewRead(filePath)
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 {
filter := primitive.D{
{
Key: "type",
Value: "directory",
},
}
cur, err := fs.webfsCollection.Find(context.Background(), filter)
if err != nil {
return err
}
defer cur.Close(context.Background())
directories := []*WebFSFile{}
for cur.Next(context.Background()) {
dir := &WebFSFile{}
err = cur.Decode(dir)
if err != nil {
println(err.Error())
return err
}
directories = append(directories, dir)
}
for _, d := range directories {
fs.validateDir(d)
}
return nil
}

View File

@ -0,0 +1,56 @@
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) 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 := 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")
}

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

@ -2,12 +2,8 @@ package webfilesystem
import ( import (
"context" "context"
"errors"
"net/http"
"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"
@ -16,27 +12,16 @@ import (
type WebFileSystem struct { type WebFileSystem struct {
webfsCollection *mongo.Collection webfsCollection *mongo.Collection
// 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) {
splittedPath := fs.SplitPath(path)
filter := primitive.D{
{
Key: "name",
Value: splittedPath[len(splittedPath)-1],
},
}
file, err := fs.findFileInMongo(filter)
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{
{ {
@ -44,10 +29,12 @@ func (fs *WebFileSystem) ReadByObjectID(objectId primitive.ObjectID) (*WebFSFile
Value: objectId, Value: objectId,
}, },
} }
//TODO to readMongo()
file, err := fs.findFileInMongo(filter) file, err := fs.findFileInMongo(filter)
return file, err return file, err
} }
// Deprecated
func (fs *WebFileSystem) findFileInMongo(filter primitive.D) (*WebFSFile, error) { func (fs *WebFileSystem) findFileInMongo(filter primitive.D) (*WebFSFile, error) {
res := fs.webfsCollection.FindOne(context.Background(), &filter) res := fs.webfsCollection.FindOne(context.Background(), &filter)
file := WebFSFile{} file := WebFSFile{}
@ -58,77 +45,6 @@ func (fs *WebFileSystem) findFileInMongo(filter primitive.D) (*WebFSFile, error)
return &file, nil return &file, nil
} }
func (fs *WebFileSystem) List(path string) ([]*WebFSFile, error) {
// dirFile, err := fs.Read(fs.GetParentPath(path))
dirFile, err := fs.Read(path)
if err != nil {
return nil, err
}
if dirFile.Type != "directory" {
return nil, errors.New("file is not a directory")
}
fileData := FolderData{}
err = mapstructure.Decode(dirFile.Data.(primitive.D).Map(), &fileData)
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) 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 {
// return err
// }
// fileId := fs.castInsertId(res)
// fs.insertFileToDirectory(fileId, parentDir.MongoId)
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)
} }
@ -139,7 +55,7 @@ func (fs *WebFileSystem) insertFileToDirectory(fileId primitive.ObjectID, direct
return err return err
} }
//TODO check if file exist //TODO check if file exist
fileData := FolderData{} fileData := DirectoryData{}
err = mapstructure.Decode(dir.Data.(primitive.D).Map(), &fileData) err = mapstructure.Decode(dir.Data.(primitive.D).Map(), &fileData)
if err != nil { if err != nil {
return err return err
@ -163,7 +79,6 @@ func (fs *WebFileSystem) SplitPath(path string) []string {
} }
func (fs *WebFileSystem) GetExtension(filename string) string { func (fs *WebFileSystem) GetExtension(filename string) string {
// extension := []string{}
splittedName := strings.Split(filename, ".") splittedName := strings.Split(filename, ".")
return splittedName[len(splittedName)-1] return splittedName[len(splittedName)-1]
@ -175,213 +90,92 @@ 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 := fs.GetParentPath(filePath)
// if fileName == "" {
// ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct _, err := fs.NewRead(filePath)
// return 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
// } // }
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. // parentDirData, err := castToDirectoryData(parentDir.Data)
dst := "./test-img/" + file.Filename // if err != nil {
ctx.SaveUploadedFile(file, dst) // return err
// }
//TODO: Not Save to disk // newChildrenSlice := []primitive.ObjectID{}
err := fs.UploadFile(dst, path) // for i := 0; i < len(parentDirData.Children); i++ {
if err != nil { // if parentDirData.Children[i] != file.MongoId {
ctx.String(http.StatusInternalServerError, "TODO") //TODO // newChildrenSlice = append(newChildrenSlice, parentDirData.Children[i])
return // }
} // }
// webFsCollection.CreateMiniatures("./test-img/", file.Filename) // parentDirData.Children = newChildrenSlice
// parentDir.Data = parentDirData
// parentParentDir := fs.GetParentPath(parentPath)
// webfs.CreateFile(&img, "/home/user/") // _, err = fs.writeMongo(*parentDir, parentParentDir)
// if err != nil {
ctx.Status(http.StatusCreated) // return err
}) // }
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",
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 {
filter := primitive.D{
{
Key: "type",
Value: "directory",
},
}
cur, err := fs.webfsCollection.Find(context.Background(), filter)
if err != nil {
return err
}
defer cur.Close(context.Background())
directories := []*WebFSFile{}
for cur.Next(context.Background()) {
dir := &WebFSFile{}
err = cur.Decode(dir)
if err != nil {
println(err.Error())
return err
}
directories = append(directories, dir)
}
for _, d := range directories {
fs.validateDir(d)
}
return 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 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 { type WebFSFile struct {
MongoId primitive.ObjectID `bson:"_id" json:"-"` MongoId primitive.ObjectID `bson:"_id" json:"-"`
Name string `bson:"name" json:"name"` Name string `bson:"name" json:"name"`
Type string `bson:"type" json:"type"` Type string `bson:"type" json:"type"`
Data interface{} `bson:"data" json:"-"`
Icon string `bson:"-" json:"icon"` Icon string `bson:"-" json:"icon"`
Data interface{} `bson:"data" json:"-"`
} }
type FolderData struct {
Parent primitive.ObjectID `bson:"parent"`
Children []primitive.ObjectID `bson:"children"`
}
type File interface {
GetUuid() string
GetFileName() string
}
type Image struct {
}
type Exec struct {
WebFSFile
}
func (e *Exec) GetFileName() string {
return e.Name
}
// type WebFSFile2 interface {
// GetName() string
// GetType() string
// GetData() interface{}
// }