github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/routers/root/RThemeHandler.go (about)

     1  package root
     2  
     3  import (
     4  	"encoding/base64"
     5  	"fmt"
     6  	"github.com/insionng/makross"
     7  	
     8  	"io/ioutil"
     9  	"os"
    10  	"github.com/insionng/yougam/helper"
    11  	"github.com/insionng/yougam/libraries/goconfig"
    12  )
    13  
    14  func GetRThemeHandler(self *makross.Context) error {
    15  	
    16  
    17  	self.Set("catpage", "RThemeHandler")
    18  	self.Set("curtheme", helper.Theme())
    19  
    20  	themes := Fstdirs("themes")
    21  	logoz := make(map[string]string, 0)
    22  	for _, theme := range themes {
    23  		b, e := ioutil.ReadFile(fmt.Sprintf("themes/%s/static/%s.png", theme, theme))
    24  		if e != nil {
    25  			continue
    26  		}
    27  		if len(b) > 0 {
    28  			logoz[theme] = base64.StdEncoding.EncodeToString(b)
    29  		}
    30  	}
    31  	self.Set("logoz", logoz)
    32  
    33  	if themename := self.Param("name").String(); len(themename) > 0 && themename != helper.Theme() {
    34  
    35  		conf, e := goconfig.LoadConfigFile(helper.ConfigPath)
    36  		if e != nil {
    37  			self.Flash.Error(fmt.Sprintf("读取配置文件出错:", e))
    38  			return self.Render("root/theme")
    39  
    40  		} else {
    41  
    42  			newStaticPath := "themes/" + themename + "/static"
    43  			newTemplatesPath := "themes/" + themename + "/templates"
    44  
    45  			if helper.IsExist(newStaticPath) && helper.IsExist(newTemplatesPath) {
    46  
    47  				conf.SetValue("themes", "style", themename)
    48  				goconfig.SaveConfigFile(conf, helper.ConfigPath)
    49  
    50  				if e := os.RemoveAll("./public"); e != nil {
    51  					self.Flash.Error(fmt.Sprintf("删除目录出错:", e))
    52  					return self.Render("root/theme")
    53  
    54  				}
    55  
    56  				//复制模板静态资源到public目录
    57  				if e := helper.CopyDir(newStaticPath, "./public"); e != nil {
    58  					self.Flash.Error(fmt.Sprintf("复制模板静态资源到public目录时出现错误:", e))
    59  					return self.Render("root/theme")
    60  
    61  				}
    62  
    63  				return self.Redirect("/?version=" + helper.MD5(themename))
    64  
    65  			} else {
    66  				self.Flash.Error(fmt.Sprint(themename, "主题不存在!"))
    67  				return self.Render("root/theme")
    68  			}
    69  		}
    70  
    71  	}
    72  
    73  	return self.Render("root/theme")
    74  }
    75  
    76  func Fstdirs(dir string) (dirlist []string) {
    77  	f, _ := os.Open(dir)
    78  	defer f.Close()
    79  	dirs, _ := f.Readdir(0)
    80  	for _, fileInfo := range dirs {
    81  		if fileInfo.IsDir() {
    82  			dirlist = append(dirlist, fileInfo.Name())
    83  		}
    84  	}
    85  	return dirlist
    86  }