[refactor] template handling
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
2023-11-28 20:05:50 -05:00
parent bb837dd30e
commit 756db7a493
29 changed files with 851 additions and 972 deletions

View File

@@ -3,7 +3,10 @@ package api
import (
"crypto/rand"
"html/template"
"io/ioutil"
"net/http"
"path/filepath"
"strings"
"github.com/gin-contrib/multitemplate"
"github.com/gin-contrib/sessions"
@@ -70,25 +73,8 @@ func NewApi(db *database.DBManager, c *config.Config) *API {
}
func (api *API) registerWebAppRoutes() {
// Define Templates & Helper Functions
render := multitemplate.NewRenderer()
helperFuncs := template.FuncMap{
"GetSVGGraphData": getSVGGraphData,
"GetUTCOffsets": getUTCOffsets,
"NiceSeconds": niceSeconds,
}
// Templates
render.AddFromFiles("error", "templates/error.html")
render.AddFromFilesFuncs("activity", helperFuncs, "templates/base.html", "templates/activity.html")
render.AddFromFilesFuncs("document", helperFuncs, "templates/base.html", "templates/document.html")
render.AddFromFilesFuncs("documents", helperFuncs, "templates/base.html", "templates/documents.html")
render.AddFromFilesFuncs("home", helperFuncs, "templates/base.html", "templates/home.html")
render.AddFromFilesFuncs("login", helperFuncs, "templates/login.html")
render.AddFromFilesFuncs("search", helperFuncs, "templates/base.html", "templates/search.html")
render.AddFromFilesFuncs("settings", helperFuncs, "templates/base.html", "templates/settings.html")
api.Router.HTMLRender = render
// Generate Templates
api.Router.HTMLRender = *api.generateTemplates()
// Static Assets (Required @ Root)
api.Router.GET("/manifest.json", api.webManifest)
@@ -175,6 +161,55 @@ func (api *API) registerOPDSRoutes(apiGroup *gin.RouterGroup) {
opdsGroup.GET("/documents/:document/file", api.authOPDSMiddleware, api.downloadDocument)
}
func (api *API) generateTemplates() *multitemplate.Renderer {
// Define Templates & Helper Functions
render := multitemplate.NewRenderer()
helperFuncs := template.FuncMap{
"GetSVGGraphData": getSVGGraphData,
"GetUTCOffsets": getUTCOffsets,
"NiceSeconds": niceSeconds,
"dict": dict,
}
// Load Base
b, _ := ioutil.ReadFile("./templates/base.html")
baseTemplate := template.Must(template.New("base").Funcs(helperFuncs).Parse(string(b)))
// Load SVGs
svgs, _ := filepath.Glob("./templates/svgs/*")
for _, path := range svgs {
basename := filepath.Base(path)
name := strings.TrimSuffix(basename, filepath.Ext(basename))
b, _ := ioutil.ReadFile(path)
baseTemplate = template.Must(baseTemplate.New("svg/" + name).Parse(string(b)))
}
// Load Components
components, _ := filepath.Glob("./templates/components/*")
for _, path := range components {
basename := filepath.Base(path)
name := strings.TrimSuffix(basename, filepath.Ext(basename))
b, _ := ioutil.ReadFile(path)
baseTemplate = template.Must(baseTemplate.New("component/" + name).Parse(string(b)))
}
// Load Pages
pages, _ := filepath.Glob("./templates/pages/*")
for _, path := range pages {
basename := filepath.Base(path)
name := strings.TrimSuffix(basename, filepath.Ext(basename))
// Clone Base Template
b, _ := ioutil.ReadFile(path)
pageTemplate, _ := template.Must(baseTemplate.Clone()).New("page/" + name).Parse(string(b))
render.Add("page/"+name, pageTemplate)
}
return &render
}
func generateToken(n int) ([]byte, error) {
b := make([]byte, n)
_, err := rand.Read(b)

View File

@@ -261,8 +261,7 @@ func (api *API) createAppResourcesRoute(routeName string, args ...map[string]any
} else if routeName == "login" {
templateVars["RegistrationEnabled"] = api.Config.RegistrationEnabled
}
c.HTML(http.StatusOK, routeName, templateVars)
c.HTML(http.StatusOK, "page/"+routeName, templateVars)
}
}
@@ -763,7 +762,7 @@ func (api *API) identifyDocument(c *gin.Context) {
templateVars["Data"] = document
templateVars["TotalTimeLeftSeconds"] = int64((100.0 - document.Percentage) * float64(document.SecondsPerPercent))
c.HTML(http.StatusOK, "document", templateVars)
c.HTML(http.StatusOK, "page/document", templateVars)
}
func (api *API) saveNewDocument(c *gin.Context) {
@@ -954,7 +953,7 @@ func (api *API) editSettings(c *gin.Context) {
"SearchEnabled": api.Config.SearchEnabled,
}
c.HTML(http.StatusOK, "settings", templateVars)
c.HTML(http.StatusOK, "page/settings", templateVars)
}
func (api *API) getDocumentsWordCount(documents []database.GetDocumentsWithStatsRow) error {
@@ -1029,7 +1028,7 @@ func errorPage(c *gin.Context, errorCode int, errorMessage string) {
errorHuman = "You're not allowed to do that."
}
c.HTML(errorCode, "error", gin.H{
c.HTML(errorCode, "page/error", gin.H{
"Status": errorCode,
"Error": errorHuman,
"Message": errorMessage,

View File

@@ -1,6 +1,7 @@
package api
import (
"errors"
"fmt"
"math"
@@ -95,3 +96,18 @@ func getSVGGraphData(inputData []database.GetDailyReadStatsRow, svgWidth int, sv
return graph.GetSVGGraphData(intData, svgWidth, svgHeight)
}
func dict(values ...interface{}) (map[string]interface{}, error) {
if len(values)%2 != 0 {
return nil, errors.New("invalid dict call")
}
dict := make(map[string]interface{}, len(values)/2)
for i := 0; i < len(values); i += 2 {
key, ok := values[i].(string)
if !ok {
return nil, errors.New("dict keys must be strings")
}
dict[key] = values[i+1]
}
return dict, nil
}