2018-05-27 09:36:35 +00:00
/* Copyright Azareal 2016 - 2019 */
package common
import (
"bytes"
2019-03-11 08:47:45 +00:00
"crypto/sha256"
2018-10-02 04:09:17 +00:00
"database/sql"
2019-03-11 08:47:45 +00:00
"encoding/hex"
2018-05-27 09:36:35 +00:00
"errors"
2019-02-10 05:52:26 +00:00
htmpl "html/template"
2018-05-27 09:36:35 +00:00
"io"
"io/ioutil"
"log"
"mime"
"net/http"
"os"
"path/filepath"
2018-12-14 04:08:53 +00:00
"reflect"
2019-07-23 10:41:34 +00:00
"strconv"
2020-02-18 23:04:14 +00:00
"strings"
2018-05-27 09:36:35 +00:00
"text/template"
2018-11-01 06:43:56 +00:00
2019-10-06 05:32:08 +00:00
p "github.com/Azareal/Gosora/common/phrases"
2018-05-27 09:36:35 +00:00
)
2018-10-02 04:09:17 +00:00
var ErrNoDefaultTheme = errors . New ( "The default theme isn't registered in the system" )
2019-06-01 12:31:48 +00:00
var ErrBadDefaultTemplate = errors . New ( "The template you tried to load doesn't exist in the interpreted pool." )
2018-10-02 04:09:17 +00:00
2018-05-27 09:36:35 +00:00
type Theme struct {
Path string // Redirect this file to another folder
2019-02-28 07:28:17 +00:00
Name string
FriendlyName string
Version string
Creator string
FullImage string
MobileFriendly bool
Disabled bool
HideFromThemes bool
BgAvatars bool // For profiles, at the moment
GridLists bool // User Manager
ForkOf string
Tag string
URL string
Docks [ ] string // Allowed Values: leftSidebar, rightSidebar, footer
2020-04-12 05:00:15 +00:00
DocksID [ ] int // Integer versions of Docks to try to get a speed boost in BuildWidget()
2019-02-28 07:28:17 +00:00
Settings map [ string ] ThemeSetting
IntTmplHandle * htmpl . Template
// TODO: Do we really need both OverridenTemplates AND OverridenMap?
2019-02-10 05:52:26 +00:00
OverridenTemplates [ ] string
2019-02-28 07:28:17 +00:00
OverridenMap map [ string ] bool
2019-02-10 05:52:26 +00:00
Templates [ ] TemplateMapping
TemplatesMap map [ string ] string
TmplPtr map [ string ] interface { }
Resources [ ] ThemeResource
ResourceTemplates * template . Template
2018-05-27 09:36:35 +00:00
// Dock intercepters
// TODO: Implement this
MapTmplToDock map [ string ] ThemeMapTmplToDock // map[dockName]data
RunOnDock func ( string ) string //(dock string) (sbody string)
2020-04-12 05:00:15 +00:00
RunOnDockID func ( int ) string //(dock int) (sbody string)
2018-05-27 09:36:35 +00:00
// This variable should only be set and unset by the system, not the theme meta file
2018-12-14 04:08:53 +00:00
// TODO: Should we phase out Active and make the default theme store the primary source of truth?
2018-05-27 09:36:35 +00:00
Active bool
}
type ThemeSetting struct {
FriendlyName string
Options [ ] string
}
type TemplateMapping struct {
Name string
Source string
//When string
}
2020-03-27 23:10:54 +00:00
const (
ResTypeUnknown = iota
ResTypeSheet
ResTypeScript
)
const (
LocUnknown = iota
LocGlobal
LocFront
LocPanel
)
2018-05-27 09:36:35 +00:00
type ThemeResource struct {
Name string
2020-03-27 23:10:54 +00:00
Type int // 0 = unknown, 1 = sheet, 2 = script
2018-05-27 09:36:35 +00:00
Location string
2020-03-27 23:10:54 +00:00
LocID int
2018-05-27 09:36:35 +00:00
Loggedin bool // Only serve this resource to logged in users
2019-03-21 22:59:41 +00:00
Async bool
2018-05-27 09:36:35 +00:00
}
type ThemeMapTmplToDock struct {
//Name string
File string
}
// TODO: It might be unsafe to call the template parsing functions with fsnotify, do something more concurrent
2019-10-06 05:32:08 +00:00
func ( t * Theme ) LoadStaticFiles ( ) error {
t . ResourceTemplates = template . New ( "" )
2018-12-06 11:09:10 +00:00
fmap := make ( map [ string ] interface { } )
2020-02-18 23:04:14 +00:00
fmap [ "lang" ] = func ( phraseNameInt , tmplInt interface { } ) interface { } {
2018-12-06 11:09:10 +00:00
phraseName , ok := phraseNameInt . ( string )
if ! ok {
panic ( "phraseNameInt is not a string" )
}
tmpl , ok := tmplInt . ( CSSData )
if ! ok {
panic ( "tmplInt is not a CSSData" )
}
phrase , ok := tmpl . Phrases [ phraseName ]
if ! ok {
// TODO: XSS? Only server admins should have access to theme files anyway, but think about it
return "{lang." + phraseName + "}"
}
return phrase
}
2018-12-14 04:08:53 +00:00
fmap [ "toArr" ] = func ( args ... interface { } ) [ ] interface { } {
return args
}
fmap [ "concat" ] = func ( args ... interface { } ) interface { } {
var out string
for _ , arg := range args {
out += arg . ( string )
}
return out
}
2019-10-06 05:32:08 +00:00
t . ResourceTemplates . Funcs ( fmap )
2020-03-23 01:18:10 +00:00
// TODO: Minify these
2020-04-03 05:53:15 +00:00
//template.Must(t.ResourceTemplates.ParseGlob("./themes/" + t.Name + "/public/*.css"))
fnames , err := filepath . Glob ( "./themes/" + t . Name + "/public/*.css" )
if err != nil {
return err
}
for _ , fname := range fnames {
b , err := ioutil . ReadFile ( fname )
if err != nil {
return err
}
//b := []byte("trolololol")
//b = bytes.ReplaceAll(b, []byte{10}, []byte(""))
//b = bytes.Replace(b, []byte("\n\n"), []byte(""), -1)
//b = bytes.Replace(b, []byte("}\n."), []byte("}."), -1)
//b = bytes.Replace(b, []byte("}\n:"), []byte("}:"), -1)
s := func ( ) string {
s := string ( b )
rep := func ( from , to string ) {
s = strings . Replace ( s , from , to , - 1 )
}
rep ( "\r" , "" )
rep ( "}\n" , "}" )
rep ( "\n{" , "{" )
rep ( "\n" , "" )
rep ( `
` , "" )
rep ( ": {{" , ":{{" )
rep ( "display: " , "display:" )
rep ( "float: " , "float:" )
rep ( "-left: " , "-left:" )
rep ( "-right: " , "-right:" )
rep ( "-top: " , "-top:" )
rep ( "-bottom: " , "-bottom:" )
rep ( "border: " , "border:" )
rep ( "radius: " , "radius:" )
rep ( "content: " , "content:" )
rep ( "width: " , "width:" )
rep ( "padding: " , "padding:" )
rep ( "-size: " , "-size:" )
return s
} ( )
name := filepath . Base ( fname )
t := t . ResourceTemplates
var tmpl * template . Template
/ * if name == t . Name ( ) {
tmpl = t
} else { * /
tmpl = t . New ( name )
//}
_ , err = tmpl . Parse ( s )
if err != nil {
return err
}
}
2018-05-27 09:36:35 +00:00
// It should be safe for us to load the files for all the themes in memory, as-long as the admin hasn't setup a ridiculous number of themes
2019-10-06 05:32:08 +00:00
return t . AddThemeStaticFiles ( )
2018-05-27 09:36:35 +00:00
}
2019-10-06 05:32:08 +00:00
func ( t * Theme ) AddThemeStaticFiles ( ) error {
phraseMap := p . GetTmplPhrases ( )
2018-05-27 09:36:35 +00:00
// TODO: Use a function instead of a closure to make this more testable? What about a function call inside the closure to take the theme variable into account?
2019-10-06 05:32:08 +00:00
return filepath . Walk ( "./themes/" + t . Name + "/public" , func ( path string , f os . FileInfo , err error ) error {
DebugLog ( "Attempting to add static file '" + path + "' for default theme '" + t . Name + "'" )
2018-05-27 09:36:35 +00:00
if err != nil {
return err
}
if f . IsDir ( ) {
return nil
}
path = strings . Replace ( path , "\\" , "/" , - 1 )
data , err := ioutil . ReadFile ( path )
if err != nil {
return err
}
2019-10-06 05:32:08 +00:00
ext := filepath . Ext ( path )
2020-04-03 05:53:15 +00:00
if ext == ".js" {
data = bytes . Replace ( data , [ ] byte ( "\r" ) , [ ] byte ( "" ) , - 1 )
}
2018-05-27 09:36:35 +00:00
if ext == ".css" && len ( data ) != 0 {
var b bytes . Buffer
2019-09-29 04:56:39 +00:00
pieces := strings . Split ( path , "/" )
filename := pieces [ len ( pieces ) - 1 ]
2018-12-06 11:09:10 +00:00
// TODO: Prepare resource templates for each loaded langpack?
2019-10-06 05:32:08 +00:00
err = t . ResourceTemplates . ExecuteTemplate ( & b , filename , CSSData { Phrases : phraseMap } )
2018-05-27 09:36:35 +00:00
if err != nil {
2019-10-06 05:32:08 +00:00
log . Print ( "Failed in adding static file '" + path + "' for default theme '" + t . Name + "'" )
2018-05-27 09:36:35 +00:00
return err
}
data = b . Bytes ( )
2020-04-03 05:53:15 +00:00
rep := func ( from , to string ) {
data = bytes . Replace ( data , [ ] byte ( from ) , [ ] byte ( to ) , - 1 )
}
rep ( "\t" , "" )
//rep("\n\n", "")
rep ( "\n" , "" )
rep ( "\n" , "" )
rep ( `
` , "" )
rep ( "}\n." , "}." )
rep ( "}\n:" , "}:" )
rep ( ": #" , ":#" )
rep ( " {" , "{" )
rep ( "{\n" , "{" )
rep ( ",\n" , "," )
rep ( ";\n" , ";" )
rep ( ";\n}" , ";}" )
rep ( ": 0px;" , ":0;" )
rep ( "; }" , ";}" )
rep ( ", #" , ",#" )
2018-05-27 09:36:35 +00:00
}
2019-10-06 05:32:08 +00:00
path = strings . TrimPrefix ( path , "themes/" + t . Name + "/public" )
2020-04-13 03:28:52 +00:00
brData , err := CompressBytesBrotli ( data )
if err != nil {
return err
}
// Don't use Brotli if we get meagre gains from it as it takes longer to process the responses
if len ( brData ) >= ( len ( data ) + 130 ) {
brData = nil
} else {
diff := len ( data ) - len ( brData )
if diff <= len ( data ) / 100 {
brData = nil
}
}
2019-04-27 10:22:39 +00:00
gzipData , err := CompressBytesGzip ( data )
2018-08-21 08:00:35 +00:00
if err != nil {
return err
}
2020-03-12 03:00:04 +00:00
// Don't use Gzip if we get meagre gains from it as it takes longer to process the responses
if len ( gzipData ) >= ( len ( data ) + 150 ) {
gzipData = nil
} else {
diff := len ( data ) - len ( gzipData )
if diff <= len ( data ) / 100 {
gzipData = nil
}
}
2018-08-21 08:00:35 +00:00
2019-03-11 08:47:45 +00:00
// Get a checksum for CSPs and cache busting
hasher := sha256 . New ( )
hasher . Write ( data )
2019-03-21 22:59:41 +00:00
checksum := hex . EncodeToString ( hasher . Sum ( nil ) )
2019-03-11 08:47:45 +00:00
2020-07-26 04:36:40 +00:00
StaticFiles . Set ( "/s/" + t . Name + path , & SFile { data , gzipData , brData , checksum , t . Name + path + "?h=" + checksum , 0 , int64 ( len ( data ) ) , strconv . Itoa ( len ( data ) ) , int64 ( len ( gzipData ) ) , strconv . Itoa ( len ( gzipData ) ) , int64 ( len ( brData ) ) , strconv . Itoa ( len ( brData ) ) , mime . TypeByExtension ( ext ) , f , f . ModTime ( ) . UTC ( ) . Format ( http . TimeFormat ) } )
2018-05-27 09:36:35 +00:00
2019-10-06 05:32:08 +00:00
DebugLog ( "Added the '/" + t . Name + path + "' static file for theme " + t . Name + "." )
2018-05-27 09:36:35 +00:00
return nil
} )
}
2019-10-06 05:32:08 +00:00
func ( t * Theme ) MapTemplates ( ) {
if t . Templates != nil {
for _ , themeTmpl := range t . Templates {
2018-05-27 09:36:35 +00:00
if themeTmpl . Name == "" {
LogError ( errors . New ( "Invalid destination template name" ) )
}
if themeTmpl . Source == "" {
LogError ( errors . New ( "Invalid source template name" ) )
}
// `go generate` is one possibility for letting plugins inject custom page structs, but it would simply add another step of compilation. It might be simpler than the current build process from the perspective of the administrator?
destTmplPtr , ok := TmplPtrMap [ themeTmpl . Name ]
if ! ok {
return
}
sourceTmplPtr , ok := TmplPtrMap [ themeTmpl . Source ]
if ! ok {
LogError ( errors . New ( "The source template doesn't exist!" ) )
}
2019-02-10 05:52:26 +00:00
dTmplPtr , ok := destTmplPtr . ( * func ( interface { } , io . Writer ) error )
if ! ok {
2018-05-27 09:36:35 +00:00
log . Print ( "themeTmpl.Name: " , themeTmpl . Name )
log . Print ( "themeTmpl.Source: " , themeTmpl . Source )
LogError ( errors . New ( "Unknown destination template type!" ) )
2019-02-10 05:52:26 +00:00
return
2018-05-27 09:36:35 +00:00
}
2019-02-10 05:52:26 +00:00
sTmplPtr , ok := sourceTmplPtr . ( * func ( interface { } , io . Writer ) error )
if ! ok {
LogError ( errors . New ( "The source and destination templates are incompatible" ) )
return
}
overridenTemplates [ themeTmpl . Name ] = true
* dTmplPtr = * sTmplPtr
2018-05-27 09:36:35 +00:00
}
}
}
2019-10-06 05:32:08 +00:00
func ( t * Theme ) setActive ( active bool ) error {
2018-10-02 04:09:17 +00:00
var sink bool
2019-10-06 05:32:08 +00:00
err := themeStmts . isDefault . QueryRow ( t . Name ) . Scan ( & sink )
2018-10-02 04:09:17 +00:00
if err != nil && err != sql . ErrNoRows {
return err
}
hasTheme := err != sql . ErrNoRows
if hasTheme {
2019-10-06 05:32:08 +00:00
_ , err = themeStmts . update . Exec ( active , t . Name )
2018-10-02 04:09:17 +00:00
} else {
2019-10-06 05:32:08 +00:00
_ , err = themeStmts . add . Exec ( t . Name , active )
2018-10-02 04:09:17 +00:00
}
if err != nil {
return err
}
// TODO: Think about what we want to do for multi-server configurations
2019-10-06 05:32:08 +00:00
log . Printf ( "Setting theme '%s' as the default theme" , t . Name )
t . Active = active
2018-10-02 04:09:17 +00:00
return nil
}
2019-10-06 05:32:08 +00:00
func UpdateDefaultTheme ( t * Theme ) error {
2018-10-02 04:09:17 +00:00
ChangeDefaultThemeMutex . Lock ( )
defer ChangeDefaultThemeMutex . Unlock ( )
2019-10-06 05:32:08 +00:00
err := t . setActive ( true )
2018-10-02 04:09:17 +00:00
if err != nil {
return err
}
defaultTheme := DefaultThemeBox . Load ( ) . ( string )
dtheme , ok := Themes [ defaultTheme ]
if ! ok {
return ErrNoDefaultTheme
}
err = dtheme . setActive ( false )
if err != nil {
return err
}
2019-10-06 05:32:08 +00:00
DefaultThemeBox . Store ( t . Name )
2018-10-02 04:09:17 +00:00
ResetTemplateOverrides ( )
2019-10-06 05:32:08 +00:00
t . MapTemplates ( )
2018-10-02 04:09:17 +00:00
return nil
}
2019-10-06 05:32:08 +00:00
func ( t Theme ) HasDock ( name string ) bool {
for _ , dock := range t . Docks {
2018-05-27 09:36:35 +00:00
if dock == name {
return true
}
}
return false
}
2019-10-06 05:32:08 +00:00
func ( t Theme ) BuildDock ( dock string ) ( sbody string ) {
runOnDock := t . RunOnDock
2018-05-27 09:36:35 +00:00
if runOnDock != nil {
return runOnDock ( dock )
}
return ""
}
2018-12-14 04:08:53 +00:00
2020-04-12 05:00:15 +00:00
func ( t Theme ) HasDockByID ( id int ) bool {
for _ , dock := range t . DocksID {
if dock == id {
return true
}
}
return false
}
func ( t Theme ) BuildDockByID ( id int ) ( sbody string ) {
runOnDock := t . RunOnDockID
if runOnDock != nil {
return runOnDock ( id )
}
return ""
}
2018-12-14 04:08:53 +00:00
type GzipResponseWriter struct {
io . Writer
http . ResponseWriter
}
func ( w GzipResponseWriter ) Write ( b [ ] byte ) ( int , error ) {
return w . Writer . Write ( b )
}
// NEW method of doing theme templates to allow one user to have a different theme to another. Under construction.
// TODO: Generate the type switch instead of writing it by hand
// TODO: Cut the number of types in half
2019-10-06 05:32:08 +00:00
func ( t * Theme ) RunTmpl ( template string , pi interface { } , w io . Writer ) error {
2018-12-14 04:08:53 +00:00
// Unpack this to avoid an indirect call
2020-07-26 04:36:40 +00:00
if gzw , ok := w . ( GzipResponseWriter ) ; ok {
2018-12-14 04:08:53 +00:00
w = gzw . Writer
2020-03-12 06:52:26 +00:00
gzw . Header ( ) . Set ( "Content-Type" , "text/html;charset=utf-8" )
2018-12-14 04:08:53 +00:00
}
2019-10-06 05:32:08 +00:00
getTmpl := t . GetTmpl ( template )
2018-12-14 04:08:53 +00:00
switch tmplO := getTmpl . ( type ) {
2019-02-10 05:52:26 +00:00
case * func ( interface { } , io . Writer ) error :
2018-12-14 04:08:53 +00:00
var tmpl = * tmplO
2019-02-10 05:52:26 +00:00
return tmpl ( pi , w )
case func ( interface { } , io . Writer ) error :
return tmplO ( pi , w )
2018-12-14 04:08:53 +00:00
case nil , string :
2019-02-28 07:28:17 +00:00
//fmt.Println("falling back to interpreted for " + template)
2019-10-06 05:32:08 +00:00
mapping , ok := t . TemplatesMap [ template ]
2018-12-14 04:08:53 +00:00
if ! ok {
mapping = template
}
2019-10-06 05:32:08 +00:00
if t . IntTmplHandle . Lookup ( mapping + ".html" ) == nil {
2019-06-01 12:31:48 +00:00
return ErrBadDefaultTemplate
}
2019-10-06 05:32:08 +00:00
return t . IntTmplHandle . ExecuteTemplate ( w , mapping + ".html" , pi )
2018-12-14 04:08:53 +00:00
default :
2019-10-06 05:32:08 +00:00
log . Print ( "theme " , t )
2018-12-14 04:08:53 +00:00
log . Print ( "template " , template )
log . Print ( "pi " , pi )
log . Print ( "tmplO " , tmplO )
log . Print ( "getTmpl " , getTmpl )
valueOf := reflect . ValueOf ( tmplO )
log . Print ( "initial valueOf.Type()" , valueOf . Type ( ) )
for valueOf . Kind ( ) == reflect . Interface || valueOf . Kind ( ) == reflect . Ptr {
valueOf = valueOf . Elem ( )
log . Print ( "valueOf.Elem().Type() " , valueOf . Type ( ) )
}
log . Print ( "deferenced valueOf.Type() " , valueOf . Type ( ) )
log . Print ( "valueOf.Kind() " , valueOf . Kind ( ) )
return errors . New ( "Unknown template type" )
}
}
// GetTmpl attempts to get the template for a specific theme, otherwise it falls back on the default template pointer, which if absent will fallback onto the template interpreter
2019-10-06 05:32:08 +00:00
func ( t * Theme ) GetTmpl ( template string ) interface { } {
2018-12-14 04:08:53 +00:00
// TODO: Figure out why we're getting a nil pointer here when transpiled templates are disabled, I would have assumed that we would just fall back to !ok on this
// Might have something to do with it being the theme's TmplPtr map, investigate.
2019-10-06 05:32:08 +00:00
tmpl , ok := t . TmplPtr [ template ]
2018-12-14 04:08:53 +00:00
if ok {
return tmpl
}
2019-10-06 05:32:08 +00:00
tmpl , ok = TmplPtrMap [ template + "_" + t . Name ]
2019-02-28 07:28:17 +00:00
if ok {
return tmpl
}
2018-12-14 04:08:53 +00:00
tmpl , ok = TmplPtrMap [ template ]
if ok {
return tmpl
}
return template
}