refactor(admin): use go1.16 embed for templates and assets

This commit is contained in:
sentriz
2021-05-08 15:56:33 +01:00
committed by Senan Kelly
parent 6f15589c08
commit 0c871d888b
9 changed files with 78 additions and 11322 deletions

View File

@@ -12,7 +12,7 @@ WORKDIR /src
COPY . .
RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
./_do_build_server
GOOS=linux go build -o gonic cmd/gonic/gonic.go
FROM alpine:3.12.3
RUN apk add -U --no-cache \

View File

@@ -1,22 +0,0 @@
package main
import (
"fmt"
"log"
"os"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"go.senan.xyz/gonic/server/scanner/tags"
)
func main() {
t, err := tags.New(os.Args[1])
if err != nil {
log.Fatalf("error reading: %v", err)
}
fmt.Println("artist", t.Album())
fmt.Println("aartist", t.AlbumArtist())
fmt.Println("len", t.Length())
fmt.Println("br", t.Bitrate())
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,15 +1,18 @@
//nolint:gochecknoglobals,golint,stylecheck
package assets
import (
"strings"
"embed"
)
// PrefixDo runs a given callback for every path in our assets with
// the given prefix
func PrefixDo(pre string, cb func(path string, asset *EmbeddedAsset)) {
for path, asset := range Bytes {
if strings.HasPrefix(path, pre) {
cb(path, asset)
}
}
}
//go:embed layouts
var Layouts embed.FS
//go:embed pages
var Pages embed.FS
//go:embed partials
var Partials embed.FS
//go:embed static
var Static embed.FS

View File

@@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"html/template"
"io/fs"
"log"
"net/http"
"net/url"
@@ -19,11 +20,11 @@ import (
"github.com/oxtoacart/bpool"
"github.com/wader/gormstore"
"go.senan.xyz/gonic"
"go.senan.xyz/gonic/server/assets"
"go.senan.xyz/gonic/server/ctrlbase"
"go.senan.xyz/gonic/server/db"
"go.senan.xyz/gonic/server/podcasts"
"go.senan.xyz/gonic/version"
)
type CtxKey int
@@ -33,41 +34,12 @@ const (
CtxSession
)
// extendFromPaths /extends/ the given template for every asset
// with given prefix
func extendFromPaths(b *template.Template, p string) *template.Template {
assets.PrefixDo(p, func(_ string, asset *assets.EmbeddedAsset) {
tmplStr := string(asset.Bytes)
b = template.Must(b.Parse(tmplStr))
})
return b
}
// extendFromPaths /clones/ the given template for every asset
// with given prefix, extends it, and insert it into a new map
func pagesFromPaths(b *template.Template, p string) map[string]*template.Template {
ret := map[string]*template.Template{}
assets.PrefixDo(p, func(path string, asset *assets.EmbeddedAsset) {
tmplKey := filepath.Base(path)
clone := template.Must(b.Clone())
tmplStr := string(asset.Bytes)
ret[tmplKey] = template.Must(clone.Parse(tmplStr))
})
return ret
}
const (
prefixPartials = "partials"
prefixLayouts = "layouts"
prefixPages = "pages"
)
func funcMap() template.FuncMap {
return template.FuncMap{
"noCache": func(in string) string {
parsed, _ := url.Parse(in)
params := parsed.Query()
params.Set("v", version.VERSION)
params.Set("v", gonic.Version)
parsed.RawQuery = params.Encode()
return parsed.String()
},
@@ -86,23 +58,45 @@ type Controller struct {
Podcasts *podcasts.Podcasts
}
func New(b *ctrlbase.Controller, sessDB *gormstore.Store, podcasts *podcasts.Podcasts) *Controller {
tmplBase := template.
func New(b *ctrlbase.Controller, sessDB *gormstore.Store, podcasts *podcasts.Podcasts) (*Controller, error) {
tmpl := template.
New("layout").
Funcs(sprig.FuncMap()).
Funcs(funcMap()). // static
Funcs(template.FuncMap{ // from base
"path": b.Path,
})
tmplBase = extendFromPaths(tmplBase, prefixPartials)
tmplBase = extendFromPaths(tmplBase, prefixLayouts)
var err error
tmpl, err = tmpl.ParseFS(assets.Partials, "**/*.tmpl")
if err != nil {
return nil, fmt.Errorf("extend partials: %w", err)
}
tmpl, err = tmpl.ParseFS(assets.Layouts, "**/*.tmpl")
if err != nil {
return nil, fmt.Errorf("extend layouts: %w", err)
}
pagePaths, err := fs.Glob(assets.Pages, "**/*.tmpl")
if err != nil {
return nil, fmt.Errorf("parse pages: %w", err)
}
pages := map[string]*template.Template{}
for _, pagePath := range pagePaths {
pageBytes, _ := assets.Pages.ReadFile(pagePath)
page, _ := tmpl.Clone()
page, _ = page.Parse(string(pageBytes))
pageName := filepath.Base(pagePath)
pages[pageName] = page
}
return &Controller{
Controller: b,
buffPool: bpool.NewBufferPool(64),
templates: pagesFromPaths(tmplBase, prefixPages),
templates: pages,
sessDB: sessDB,
Podcasts: podcasts,
}
}, nil
}
type templateData struct {
@@ -178,10 +172,11 @@ func (c *Controller) H(h handlerAdmin) http.Handler {
http.Error(w, "useless handler return", 500)
return
}
if resp.data == nil {
resp.data = &templateData{}
}
resp.data.Version = version.VERSION
resp.data.Version = gonic.Version
if session != nil {
resp.data.Flashes = session.Flashes()
if err := session.Save(r, w); err != nil {
@@ -192,6 +187,7 @@ func (c *Controller) H(h handlerAdmin) http.Handler {
if user, ok := r.Context().Value(CtxUser).(*db.User); ok {
resp.data.User = user
}
buff := c.buffPool.Get()
defer c.buffPool.Put(buff)
tmpl, ok := c.templates[resp.template]
@@ -203,6 +199,7 @@ func (c *Controller) H(h handlerAdmin) http.Handler {
http.Error(w, fmt.Sprintf("executing template: %v", err), 500)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if resp.code != 0 {
w.WriteHeader(resp.code)

View File

@@ -7,13 +7,13 @@ import (
"github.com/gorilla/sessions"
"go.senan.xyz/gonic"
"go.senan.xyz/gonic/server/db"
"go.senan.xyz/gonic/version"
)
func (c *Controller) WithSession(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session, err := c.sessDB.Get(r, version.NAME)
session, err := c.sessDB.Get(r, gonic.Name)
if err != nil {
http.Error(w, fmt.Sprintf("error getting session: %s", err), 500)
return

View File

@@ -4,8 +4,8 @@ import (
"fmt"
"time"
"go.senan.xyz/gonic"
"go.senan.xyz/gonic/server/ctrlsubsonic/specid"
"go.senan.xyz/gonic/version"
)
const (
@@ -53,8 +53,8 @@ func NewResponse() *Response {
Status: "ok",
XMLNS: xmlns,
Version: apiVersion,
Type: version.NAME,
GonicVersion: version.VERSION,
Type: gonic.Name,
GonicVersion: gonic.Version,
}
}
@@ -82,8 +82,8 @@ func NewError(code int, message string, a ...interface{}) *Response {
Code: code,
Message: fmt.Sprintf(message, a...),
},
Type: version.NAME,
GonicVersion: version.VERSION,
Type: gonic.Name,
GonicVersion: gonic.Version,
}
}

View File

@@ -1,7 +1,6 @@
package server
import (
"bytes"
"fmt"
"log"
"net/http"
@@ -44,7 +43,7 @@ type Server struct {
podcast *podcasts.Podcasts
}
func New(opts Options) *Server {
func New(opts Options) (*Server, error) {
opts.MusicPath = filepath.Clean(opts.MusicPath)
opts.CachePath = filepath.Clean(opts.CachePath)
opts.PodcastPath = filepath.Clean(opts.PodcastPath)
@@ -70,7 +69,11 @@ func New(opts Options) *Server {
sessDB.SessionOpts.SameSite = http.SameSiteLaxMode
podcast := &podcasts.Podcasts{DB: opts.DB, PodcastBasePath: opts.PodcastPath}
ctrlAdmin := ctrladmin.New(base, sessDB, podcast)
ctrlAdmin, err := ctrladmin.New(base, sessDB, podcast)
if err != nil {
return nil, fmt.Errorf("create admin controller: %w", err)
}
ctrlSubsonic := &ctrlsubsonic.Controller{
Controller: base,
CachePath: opts.CachePath,
@@ -99,7 +102,7 @@ func New(opts Options) *Server {
server.jukebox = jukebox
}
return server
return server, nil
}
func setupMisc(r *mux.Router, ctrl *ctrlbase.Controller) {
@@ -124,14 +127,10 @@ func setupAdmin(r *mux.Router, ctrl *ctrladmin.Controller) {
r.Use(ctrl.WithSession)
r.Handle("/login", ctrl.H(ctrl.ServeLogin))
r.Handle("/login_do", ctrl.HR(ctrl.ServeLoginDo)) // "raw" handler, updates session
assets.PrefixDo("static", func(path string, asset *assets.EmbeddedAsset) {
_, name := filepath.Split(path)
route := filepath.Join("/static", name)
reader := bytes.NewReader(asset.Bytes)
r.HandleFunc(route, func(w http.ResponseWriter, r *http.Request) {
http.ServeContent(w, r, name, asset.ModTime, reader)
})
})
staticHandler := http.StripPrefix("/admin", http.FileServer(http.FS(assets.Static)))
r.PathPrefix("/static").Handler(staticHandler)
// ** begin user routes (if session is valid)
routUser := r.NewRoute().Subrouter()
routUser.Use(ctrl.WithUserSession)
@@ -153,6 +152,7 @@ func setupAdmin(r *mux.Router, ctrl *ctrladmin.Controller) {
routUser.Handle("/delete_podcast_do", ctrl.H(ctrl.ServePodcastDeleteDo))
routUser.Handle("/download_podcast_do", ctrl.H(ctrl.ServePodcastDownloadDo))
routUser.Handle("/update_podcast_do", ctrl.H(ctrl.ServePodcastUpdateDo))
// ** begin admin routes (if session is valid, and is admin)
routAdmin := routUser.NewRoute().Subrouter()
routAdmin.Use(ctrl.WithAdminSession)
@@ -168,6 +168,7 @@ func setupAdmin(r *mux.Router, ctrl *ctrladmin.Controller) {
routAdmin.Handle("/update_lastfm_api_key_do", ctrl.H(ctrl.ServeUpdateLastFMAPIKeyDo))
routAdmin.Handle("/start_scan_inc_do", ctrl.H(ctrl.ServeStartScanIncDo))
routAdmin.Handle("/start_scan_full_do", ctrl.H(ctrl.ServeStartScanFullDo))
// middlewares should be run for not found handler
// https://github.com/gorilla/mux/issues/416
notFoundHandler := ctrl.H(ctrl.ServeNotFound)
@@ -179,6 +180,7 @@ func setupSubsonic(r *mux.Router, ctrl *ctrlsubsonic.Controller) {
r.Use(ctrl.WithParams)
r.Use(ctrl.WithRequiredParams)
r.Use(ctrl.WithUser)
// ** begin common
r.Handle("/getLicense{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetLicence))
r.Handle("/getMusicFolders{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetMusicFolders))
@@ -201,10 +203,12 @@ func setupSubsonic(r *mux.Router, ctrl *ctrlsubsonic.Controller) {
r.Handle("/getBookmarks{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetBookmarks))
r.Handle("/createBookmark{_:(?:\\.view)?}", ctrl.H(ctrl.ServeCreateBookmark))
r.Handle("/deleteBookmark{_:(?:\\.view)?}", ctrl.H(ctrl.ServeDeleteBookmark))
// ** begin raw
r.Handle("/download{_:(?:\\.view)?}", ctrl.HR(ctrl.ServeDownload))
r.Handle("/getCoverArt{_:(?:\\.view)?}", ctrl.HR(ctrl.ServeGetCoverArt))
r.Handle("/stream{_:(?:\\.view)?}", ctrl.HR(ctrl.ServeStream))
// ** begin browse by tag
r.Handle("/getAlbum{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetAlbum))
r.Handle("/getAlbumList2{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetAlbumListTwo))
@@ -212,6 +216,7 @@ func setupSubsonic(r *mux.Router, ctrl *ctrlsubsonic.Controller) {
r.Handle("/getArtists{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetArtists))
r.Handle("/search3{_:(?:\\.view)?}", ctrl.H(ctrl.ServeSearchThree))
r.Handle("/getArtistInfo2{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetArtistInfoTwo))
// ** begin browse by folder
r.Handle("/getIndexes{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetIndexes))
r.Handle("/getMusicDirectory{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetMusicDirectory))
@@ -219,6 +224,7 @@ func setupSubsonic(r *mux.Router, ctrl *ctrlsubsonic.Controller) {
r.Handle("/search2{_:(?:\\.view)?}", ctrl.H(ctrl.ServeSearchTwo))
r.Handle("/getGenres{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetGenres))
r.Handle("/getArtistInfo{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetArtistInfo))
// ** begin podcasts
r.Handle("/getPodcasts{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetPodcasts))
r.Handle("/downloadPodcastEpisode{_:(?:\\.view)?}", ctrl.H(ctrl.ServeDownloadPodcastEpisode))
@@ -226,6 +232,7 @@ func setupSubsonic(r *mux.Router, ctrl *ctrlsubsonic.Controller) {
r.Handle("/refreshPodcasts{_:(?:\\.view)?}", ctrl.H(ctrl.ServeRefreshPodcasts))
r.Handle("/deletePodcastChannel{_:(?:\\.view)?}", ctrl.H(ctrl.ServeDeletePodcastChannel))
r.Handle("/deletePodcastEpisode{_:(?:\\.view)?}", ctrl.H(ctrl.ServeDeletePodcastEpisode))
// middlewares should be run for not found handler
// https://github.com/gorilla/mux/issues/416
notFoundHandler := ctrl.H(ctrl.ServeNotFound)

View File

@@ -7,3 +7,6 @@ import (
//go:embed version.txt
var Version string
const Name = "gonic"
const NameUpper = "GONIC"