mindoc/commands/command.go

341 lines
9.2 KiB
Go
Raw Normal View History

2017-04-21 18:20:35 +08:00
package commands
import (
"encoding/gob"
2018-03-24 17:24:02 +08:00
"flag"
2017-04-21 18:20:35 +08:00
"fmt"
2018-03-24 17:24:02 +08:00
"log"
2017-04-21 18:20:35 +08:00
"net/url"
"os"
"path/filepath"
"strings"
2018-03-24 17:24:02 +08:00
"time"
"encoding/json"
2018-03-24 17:24:02 +08:00
2017-04-21 18:20:35 +08:00
"github.com/astaxie/beego"
2018-03-24 17:24:02 +08:00
beegoCache "github.com/astaxie/beego/cache"
_ "github.com/astaxie/beego/cache/memcache"
_ "github.com/astaxie/beego/cache/redis"
2017-04-21 18:20:35 +08:00
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm"
"github.com/lifei6671/gocaptcha"
2018-03-24 17:24:02 +08:00
"github.com/lifei6671/mindoc/cache"
2017-06-14 09:23:29 +08:00
"github.com/lifei6671/mindoc/conf"
"github.com/lifei6671/mindoc/models"
2018-03-24 17:24:02 +08:00
"github.com/lifei6671/mindoc/utils/filetil"
)
2017-05-27 17:53:35 +08:00
2017-04-21 18:20:35 +08:00
// RegisterDataBase 注册数据库
func RegisterDataBase() {
2018-02-27 17:20:42 +08:00
beego.Info("正在初始化数据库配置.")
adapter := beego.AppConfig.String("db_adapter")
2017-04-21 18:20:35 +08:00
if adapter == "mysql" {
host := beego.AppConfig.String("db_host")
database := beego.AppConfig.String("db_database")
username := beego.AppConfig.String("db_username")
password := beego.AppConfig.String("db_password")
2018-03-22 16:42:34 +08:00
2018-03-23 17:50:10 +08:00
timezone := beego.AppConfig.String("timezone")
location, err := time.LoadLocation(timezone)
if err == nil {
orm.DefaultTimeLoc = location
} else {
2018-03-24 17:24:02 +08:00
beego.Error("加载时区配置信息失败,请检查是否存在ZONEINFO环境变量:", err)
2018-03-23 17:50:10 +08:00
}
port := beego.AppConfig.String("db_port")
2017-04-21 18:20:35 +08:00
dataSource := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true&loc=%s", username, password, host, port, database, url.QueryEscape(timezone))
2017-04-21 18:20:35 +08:00
2018-03-23 17:50:10 +08:00
if err := orm.RegisterDataBase("default", "mysql", dataSource); err != nil {
2018-03-24 17:24:02 +08:00
beego.Error("注册默认数据库失败:", err)
2018-02-27 17:20:42 +08:00
os.Exit(1)
}
} else if adapter == "sqlite3" {
2018-03-23 17:50:10 +08:00
orm.DefaultTimeLoc = time.UTC
database := beego.AppConfig.String("db_database")
if strings.HasPrefix(database, "./") {
database = filepath.Join(conf.WorkingDirectory, string(database[1:]))
2017-06-05 12:23:01 +08:00
}
2017-06-05 13:55:07 +08:00
dbPath := filepath.Dir(database)
os.MkdirAll(dbPath, 0777)
2017-04-21 18:20:35 +08:00
2018-02-27 17:20:42 +08:00
err := orm.RegisterDataBase("default", "sqlite3", database)
if err != nil {
2018-03-24 17:24:02 +08:00
beego.Error("注册默认数据库失败:", err)
2018-02-27 17:20:42 +08:00
}
2018-03-24 17:24:02 +08:00
} else {
2018-02-27 17:20:42 +08:00
beego.Error("不支持的数据库类型.")
os.Exit(1)
}
2018-02-27 17:20:42 +08:00
beego.Info("数据库初始化完成.")
2017-04-21 18:20:35 +08:00
}
// RegisterModel 注册Model
func RegisterModel() {
orm.RegisterModelWithPrefix(conf.GetDatabasePrefix(),
2017-04-21 18:20:35 +08:00
new(models.Member),
new(models.Book),
new(models.Relationship),
new(models.Option),
new(models.Document),
new(models.Attachment),
new(models.Logger),
2017-05-03 14:22:05 +08:00
new(models.MemberToken),
2017-05-19 17:20:33 +08:00
new(models.DocumentHistory),
2017-05-27 17:53:35 +08:00
new(models.Migration),
new(models.Label),
2018-07-13 19:04:51 +08:00
new(models.Blog),
2017-04-21 18:20:35 +08:00
)
2018-02-28 16:29:26 +08:00
//migrate.RegisterMigration()
2017-04-21 18:20:35 +08:00
}
// RegisterLogger 注册日志
func RegisterLogger(log string) {
2017-04-21 18:20:35 +08:00
logs.SetLogFuncCall(true)
2017-04-21 18:20:35 +08:00
logs.SetLogger("console")
logs.EnableFuncCallDepth(true)
logs.Async()
logPath := filepath.Join(log, "log.log")
if _, err := os.Stat(logPath); os.IsNotExist(err) {
2017-05-04 10:35:56 +08:00
os.MkdirAll(log, 0777)
if f, err := os.Create(logPath); err == nil {
2017-05-01 16:17:26 +08:00
f.Close()
config := make(map[string]interface{}, 1)
2017-06-02 16:29:31 +08:00
config["filename"] = logPath
b, _ := json.Marshal(config)
2017-06-02 16:29:31 +08:00
beego.SetLogger("file", string(b))
2017-05-01 16:17:26 +08:00
}
}
2017-05-01 17:17:04 +08:00
beego.SetLogFuncCall(true)
beego.BeeLogger.Async()
2017-04-21 18:20:35 +08:00
}
// RunCommand 注册orm命令行工具
func RegisterCommand() {
if len(os.Args) >= 2 && os.Args[1] == "install" {
ResolveCommand(os.Args[2:])
Install()
} else if len(os.Args) >= 2 && os.Args[1] == "version" {
CheckUpdate()
2018-02-28 16:29:26 +08:00
os.Exit(0)
}
2018-07-11 18:06:02 +08:00
2017-04-21 18:20:35 +08:00
}
2018-03-13 14:14:56 +08:00
2018-02-27 17:20:42 +08:00
//注册模板函数
func RegisterFunction() {
beego.AddFuncMap("config", models.GetOptionValue)
beego.AddFuncMap("cdn", func(p string) string {
cdn := beego.AppConfig.DefaultString("cdn", "")
if strings.HasPrefix(p, "http://") || strings.HasPrefix(p, "https://") {
return p
}
2018-03-13 14:14:56 +08:00
//如果没有设置cdn则使用baseURL拼接
if cdn == "" {
2018-03-24 17:24:02 +08:00
baseUrl := beego.AppConfig.DefaultString("baseurl", "")
2018-03-24 17:24:02 +08:00
if strings.HasPrefix(p, "/") && strings.HasSuffix(baseUrl, "/") {
2018-03-13 14:14:56 +08:00
return baseUrl + p[1:]
}
2018-03-24 17:24:02 +08:00
if !strings.HasPrefix(p, "/") && !strings.HasSuffix(baseUrl, "/") {
2018-03-13 14:14:56 +08:00
return baseUrl + "/" + p
}
2018-03-24 17:24:02 +08:00
return baseUrl + p
}
if strings.HasPrefix(p, "/") && strings.HasSuffix(cdn, "/") {
return cdn + string(p[1:])
}
if !strings.HasPrefix(p, "/") && !strings.HasSuffix(cdn, "/") {
return cdn + "/" + p
}
return cdn + p
})
2018-03-13 14:14:56 +08:00
2018-03-24 17:24:02 +08:00
beego.AddFuncMap("cdnjs", conf.URLForWithCdnJs)
beego.AddFuncMap("cdncss", conf.URLForWithCdnCss)
2018-03-13 19:20:50 +08:00
beego.AddFuncMap("cdnimg", conf.URLForWithCdnImage)
2018-03-13 14:14:56 +08:00
//重写url生成支持配置域名以及域名前缀
2018-03-13 19:20:50 +08:00
beego.AddFuncMap("urlfor", conf.URLFor)
2018-03-24 17:24:02 +08:00
beego.AddFuncMap("date_format", func(t time.Time, format string) string {
return t.Local().Format(format)
})
}
2018-02-27 17:20:42 +08:00
//解析命令
func ResolveCommand(args []string) {
flagSet := flag.NewFlagSet("MinDoc command: ", flag.ExitOnError)
flagSet.StringVar(&conf.ConfigurationFile, "config", "", "MinDoc configuration file.")
flagSet.StringVar(&conf.WorkingDirectory, "dir", "", "MinDoc working directory.")
flagSet.StringVar(&conf.LogFile, "log", "", "MinDoc log file path.")
flagSet.Parse(args)
if conf.WorkingDirectory == "" {
if p, err := filepath.Abs(os.Args[0]); err == nil {
conf.WorkingDirectory = filepath.Dir(p)
}
}
if conf.LogFile == "" {
2018-07-11 14:18:27 +08:00
conf.LogFile = conf.WorkingDir("runtime","logs")
}
if conf.ConfigurationFile == "" {
2018-07-11 14:18:27 +08:00
conf.ConfigurationFile = conf.WorkingDir( "conf", "app.conf")
config := conf.WorkingDir("conf", "app.conf.example")
2018-03-24 17:24:02 +08:00
if !filetil.FileExists(conf.ConfigurationFile) && filetil.FileExists(config) {
filetil.CopyFile(conf.ConfigurationFile, config)
}
}
2018-07-11 14:18:27 +08:00
if err := gocaptcha.ReadFonts(conf.WorkingDir( "static", "fonts"), ".ttf");err != nil {
log.Fatal("读取字体文件时出错 -> ",err)
}
2018-07-11 14:18:27 +08:00
if err := beego.LoadAppConfig("ini", conf.ConfigurationFile);err != nil {
log.Fatal("An error occurred:", err)
}
2018-07-11 14:18:27 +08:00
uploads := conf.WorkingDir("uploads")
os.MkdirAll(uploads, 0666)
beego.BConfig.WebConfig.StaticDir["/static"] = filepath.Join(conf.WorkingDirectory, "static")
beego.BConfig.WebConfig.StaticDir["/uploads"] = uploads
2018-07-11 14:18:27 +08:00
beego.BConfig.WebConfig.ViewsPath = conf.WorkingDir("views")
2018-07-11 14:18:27 +08:00
fonts := conf.WorkingDir("static", "fonts")
2018-03-24 17:24:02 +08:00
if !filetil.FileExists(fonts) {
log.Fatal("Font path not exist.")
}
gocaptcha.ReadFonts(filepath.Join(conf.WorkingDirectory, "static", "fonts"), ".ttf")
RegisterDataBase()
2018-02-27 17:20:42 +08:00
RegisterCache()
RegisterModel()
RegisterLogger(conf.LogFile)
2018-07-10 19:13:33 +08:00
ModifyPassword()
}
2018-02-27 17:20:42 +08:00
//注册缓存管道
2018-03-24 17:24:02 +08:00
func RegisterCache() {
isOpenCache := beego.AppConfig.DefaultBool("cache", false)
2018-02-27 17:20:42 +08:00
if !isOpenCache {
cache.Init(&cache.NullCache{})
}
beego.Info("正常初始化缓存配置.")
cacheProvider := beego.AppConfig.String("cache_provider")
if cacheProvider == "file" {
2018-03-24 17:24:02 +08:00
cacheFilePath := beego.AppConfig.DefaultString("cache_file_path", "./runtime/cache/")
2018-02-27 17:20:42 +08:00
if strings.HasPrefix(cacheFilePath, "./") {
cacheFilePath = filepath.Join(conf.WorkingDirectory, string(cacheFilePath[1:]))
}
fileCache := beegoCache.NewFileCache()
2018-03-01 10:12:31 +08:00
2018-03-24 17:24:02 +08:00
fileConfig := make(map[string]string, 0)
2018-03-01 10:12:31 +08:00
2018-03-24 17:24:02 +08:00
fileConfig["CachePath"] = cacheFilePath
fileConfig["DirectoryLevel"] = beego.AppConfig.DefaultString("cache_file_dir_level", "2")
fileConfig["EmbedExpiry"] = beego.AppConfig.DefaultString("cache_file_expiry", "120")
fileConfig["FileSuffix"] = beego.AppConfig.DefaultString("cache_file_suffix", ".bin")
2018-03-01 10:12:31 +08:00
2018-03-24 17:24:02 +08:00
bc, err := json.Marshal(&fileConfig)
2018-03-01 10:12:31 +08:00
if err != nil {
2018-06-11 16:26:06 +08:00
beego.Error("初始化file缓存失败:", err)
2018-03-01 10:12:31 +08:00
os.Exit(1)
}
fileCache.StartAndGC(string(bc))
2018-02-27 17:20:42 +08:00
cache.Init(fileCache)
2018-03-01 10:12:31 +08:00
2018-03-24 17:24:02 +08:00
} else if cacheProvider == "memory" {
cacheInterval := beego.AppConfig.DefaultInt("cache_memory_interval", 60)
2018-02-27 17:20:42 +08:00
memory := beegoCache.NewMemoryCache()
beegoCache.DefaultEvery = cacheInterval
cache.Init(memory)
2018-03-24 17:24:02 +08:00
} else if cacheProvider == "redis" {
var redisConfig struct {
Conn string `json:"conn"`
2018-02-27 17:20:42 +08:00
Password string `json:"password"`
2018-03-24 17:24:02 +08:00
DbNum int `json:"dbNum"`
2018-02-27 17:20:42 +08:00
}
redisConfig.DbNum = 0
2018-03-24 17:24:02 +08:00
redisConfig.Conn = beego.AppConfig.DefaultString("cache_redis_host", "")
if pwd := beego.AppConfig.DefaultString("cache_redis_password", ""); pwd != "" {
2018-02-27 17:20:42 +08:00
redisConfig.Password = pwd
}
2018-03-24 17:24:02 +08:00
if dbNum := beego.AppConfig.DefaultInt("cache_redis_db", 0); dbNum > 0 {
2018-02-27 17:20:42 +08:00
redisConfig.DbNum = dbNum
}
2018-03-24 17:24:02 +08:00
bc, err := json.Marshal(&redisConfig)
2018-02-27 17:20:42 +08:00
if err != nil {
2018-03-24 17:24:02 +08:00
beego.Error("初始化Redis缓存失败:", err)
2018-02-27 17:20:42 +08:00
os.Exit(1)
}
2018-03-24 17:24:02 +08:00
redisCache, err := beegoCache.NewCache("redis", string(bc))
2018-02-27 17:20:42 +08:00
if err != nil {
2018-03-24 17:24:02 +08:00
beego.Error("初始化Redis缓存失败:", err)
2018-02-27 17:20:42 +08:00
os.Exit(1)
}
cache.Init(redisCache)
2018-03-24 17:24:02 +08:00
} else if cacheProvider == "memcache" {
2018-02-27 17:20:42 +08:00
2018-03-24 17:24:02 +08:00
var memcacheConfig struct {
2018-02-27 17:20:42 +08:00
Conn string `json:"conn"`
}
2018-03-24 17:24:02 +08:00
memcacheConfig.Conn = beego.AppConfig.DefaultString("cache_memcache_host", "")
2018-02-27 17:20:42 +08:00
2018-03-24 17:24:02 +08:00
bc, err := json.Marshal(&memcacheConfig)
2018-02-27 17:20:42 +08:00
if err != nil {
2018-03-24 17:24:02 +08:00
beego.Error("初始化Redis缓存失败:", err)
2018-02-27 17:20:42 +08:00
os.Exit(1)
}
2018-03-24 17:24:02 +08:00
memcache, err := beegoCache.NewCache("memcache", string(bc))
2018-02-27 17:20:42 +08:00
if err != nil {
2018-03-24 17:24:02 +08:00
beego.Error("初始化Memcache缓存失败:", err)
2018-02-27 17:20:42 +08:00
os.Exit(1)
}
cache.Init(memcache)
2018-03-24 17:24:02 +08:00
} else {
2018-02-27 17:20:42 +08:00
cache.Init(&cache.NullCache{})
beego.Warn("不支持的缓存管道,缓存将禁用.")
return
}
beego.Info("缓存初始化完成.")
}
func init() {
2018-03-24 17:24:02 +08:00
if configPath, err := filepath.Abs(conf.ConfigurationFile); err == nil {
conf.ConfigurationFile = configPath
}
gocaptcha.ReadFonts("./static/fonts", ".ttf")
gob.Register(models.Member{})
if p, err := filepath.Abs(os.Args[0]); err == nil {
conf.WorkingDirectory = filepath.Dir(p)
}
}