personal-website/apps/blogviewer/blogviewer.go

115 lines
2.4 KiB
Go

package blogviewer
import (
"net/http"
"personalwebsite/webfilesystem"
"github.com/gin-gonic/gin"
"go.mongodb.org/mongo-driver/bson/primitive"
)
type BlogViewerApplication struct {
fs *webfilesystem.WebFileSystem
appID string
}
func NewBlogViewerApp(webFs *webfilesystem.WebFileSystem) *BlogViewerApplication {
return &BlogViewerApplication{
fs: webFs,
appID: "BlogViewer",
}
}
func (b *BlogViewerApplication) GetAppID() string {
return b.appID
}
func (b *BlogViewerApplication) PrivateRoutes(route *gin.RouterGroup) {
b.PublicRoutes(route)
}
func (b *BlogViewerApplication) PublicRoutes(route *gin.RouterGroup) {
route.GET("writeMockBlog", func(ctx *gin.Context) {
path := ctx.Query("path")
if path == "" {
ctx.JSON(http.StatusBadRequest, "no path provided")
return
}
err := b.WriteMock(path)
if err != nil {
ctx.Status(http.StatusInternalServerError)
return
}
ctx.JSON(http.StatusOK, "OK")
})
route.GET("render", func(ctx *gin.Context) {
isMobileParam := ctx.Query("isMobile")
path := ctx.Query("path")
if path == "" {
ctx.JSON(http.StatusBadRequest, "no path provided")
return
}
isMobile := isMobileParam == "true"
ginH, err := b.Render(path, isMobile)
if err != nil {
ctx.JSON(http.StatusInternalServerError, "TODO")
return
}
if isMobile {
ctx.HTML(http.StatusOK, "blog-viewer/mobile-app.tmpl", ginH)
} else {
ctx.HTML(http.StatusOK, "blog-viewer/app.tmpl", ginH)
}
})
}
func (b *BlogViewerApplication) WriteMock(path string) error {
blogFileHeader := webfilesystem.FileHeader{
MongoId: primitive.NewObjectID(),
Name: "blog1.blog",
Type: "",
Icon: "",
Data: [12]byte{},
}
blogFileData := BlogFileData{
Header: "OMG THIS IS BLOG",
Blocks: []Block{
{
Type: "plain-text",
Data: []string{
"Apoqiwepoqiwepo",
".,mas;dakls;d",
"q[poqwieqpipoi]",
},
},
},
}
_, _, err := b.fs.Write("/home/user/blog1.blog", &blogFileHeader, blogFileData)
if err != nil {
println(err.Error())
return err
}
return nil
}
func (b *BlogViewerApplication) Render(filePath string, isMobile bool) (gin.H, error) {
data := BlogFileData{}
_, err := b.fs.Read(filePath, &data)
if err != nil {
return nil, err
}
return gin.H{
"header": data.Header,
"blocks": data.Blocks,
}, nil
}
type Block struct {
Type string `bson:"type"`
Data []string `bson:"data"`
}