ytdl-web/app/views.go

70 lines
1.5 KiB
Go
Raw Normal View History

2023-08-12 23:27:11 -04:00
package app
import (
"embed"
"encoding/json"
"fmt"
2023-08-12 23:27:11 -04:00
"html/template"
"net/url"
"github.com/htfy96/reformism"
"go.fifitido.net/ytdl-web/pkg/view/html"
"go.fifitido.net/ytdl-web/pkg/ytdl/metadata"
2023-08-12 23:27:11 -04:00
)
//go:embed views/*
var viewsfs embed.FS
2023-08-14 18:14:08 -04:00
var Views = html.New(
2023-08-12 23:27:11 -04:00
viewsfs,
html.DefaultOptions().
WithBaseDir("views").
WithFunction("unsafe", func(s string) template.HTML {
return template.HTML(s)
}).
WithFunction("queryEscape", func(s string) string {
return url.QueryEscape(s)
}).
WithFunction("jsonMarshal", func(s any) (string, error) {
j, err := json.MarshalIndent(s, "", " ")
if err != nil {
return "", err
}
return string(j), nil
}).
WithFunction("downloadContext", func(meta metadata.Metadata, url, basePath string, format metadata.Format) map[string]any {
return map[string]any{
"Meta": meta,
"Url": url,
"BasePath": basePath,
"Format": format,
}
}).
WithFunction("sprintf", func(format string, args ...any) string {
return fmt.Sprintf(format, args...)
}).
WithFunction("filesize", func(size *int) string {
if size == nil {
return "unknown"
}
const unit = 1000
if *size < unit {
return fmt.Sprintf("%d B", *size)
}
div, exp := int64(unit), 0
for n := *size / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %cB",
float64(*size)/float64(div), "kMGTPE"[exp])
}).
2023-08-12 23:27:11 -04:00
WithFunctions(reformism.FuncsHTML),
)
func init() {
2023-08-14 18:14:08 -04:00
if err := Views.Load(); err != nil {
2023-08-12 23:27:11 -04:00
panic(err)
}
}