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
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)
// 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
}
type ThemeResource struct {
Name string
Location string
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 )
template . Must ( t . ResourceTemplates . ParseGlob ( "./themes/" + t . Name + "/public/*.css" ) )
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 )
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 ( )
}
2019-10-06 05:32:08 +00:00
path = strings . TrimPrefix ( path , "themes/" + t . Name + "/public" )
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-03-06 21:55:26 +00:00
StaticFiles . Set ( "/s/" + t . Name + path , SFile { data , gzipData , checksum , t . Name + path + "?h=" + checksum , 0 , int64 ( len ( data ) ) , strconv . Itoa ( len ( data ) ) , int64 ( len ( gzipData ) ) , strconv . Itoa ( len ( gzipData ) ) , 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
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
gzw , ok := w . ( GzipResponseWriter )
if ok {
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
}