command.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. package commands
  2. import (
  3. "encoding/gob"
  4. "flag"
  5. "fmt"
  6. "log"
  7. "net/url"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. "time"
  12. "encoding/json"
  13. "github.com/astaxie/beego"
  14. beegoCache "github.com/astaxie/beego/cache"
  15. _ "github.com/astaxie/beego/cache/memcache"
  16. _ "github.com/astaxie/beego/cache/redis"
  17. "github.com/astaxie/beego/logs"
  18. "github.com/astaxie/beego/orm"
  19. "github.com/lifei6671/gocaptcha"
  20. "github.com/lifei6671/mindoc/cache"
  21. "github.com/lifei6671/mindoc/conf"
  22. "github.com/lifei6671/mindoc/models"
  23. "github.com/lifei6671/mindoc/utils/filetil"
  24. )
  25. // RegisterDataBase 注册数据库
  26. func RegisterDataBase() {
  27. beego.Info("正在初始化数据库配置.")
  28. adapter := beego.AppConfig.String("db_adapter")
  29. if adapter == "mysql" {
  30. host := beego.AppConfig.String("db_host")
  31. database := beego.AppConfig.String("db_database")
  32. username := beego.AppConfig.String("db_username")
  33. password := beego.AppConfig.String("db_password")
  34. timezone := beego.AppConfig.String("timezone")
  35. location, err := time.LoadLocation(timezone)
  36. if err == nil {
  37. orm.DefaultTimeLoc = location
  38. } else {
  39. beego.Error("加载时区配置信息失败,请检查是否存在ZONEINFO环境变量:", err)
  40. }
  41. port := beego.AppConfig.String("db_port")
  42. dataSource := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true&loc=%s", username, password, host, port, database, url.QueryEscape(timezone))
  43. if err := orm.RegisterDataBase("default", "mysql", dataSource); err != nil {
  44. beego.Error("注册默认数据库失败:", err)
  45. os.Exit(1)
  46. }
  47. } else if adapter == "sqlite3" {
  48. orm.DefaultTimeLoc = time.UTC
  49. database := beego.AppConfig.String("db_database")
  50. if strings.HasPrefix(database, "./") {
  51. database = filepath.Join(conf.WorkingDirectory, string(database[1:]))
  52. }
  53. dbPath := filepath.Dir(database)
  54. os.MkdirAll(dbPath, 0777)
  55. err := orm.RegisterDataBase("default", "sqlite3", database)
  56. if err != nil {
  57. beego.Error("注册默认数据库失败:", err)
  58. }
  59. } else {
  60. beego.Error("不支持的数据库类型.")
  61. os.Exit(1)
  62. }
  63. beego.Info("数据库初始化完成.")
  64. }
  65. // RegisterModel 注册Model
  66. func RegisterModel() {
  67. orm.RegisterModelWithPrefix(conf.GetDatabasePrefix(),
  68. new(models.Member),
  69. new(models.Book),
  70. new(models.Relationship),
  71. new(models.Option),
  72. new(models.Document),
  73. new(models.Attachment),
  74. new(models.Logger),
  75. new(models.MemberToken),
  76. new(models.DocumentHistory),
  77. new(models.Migration),
  78. new(models.Label),
  79. )
  80. //migrate.RegisterMigration()
  81. }
  82. // RegisterLogger 注册日志
  83. func RegisterLogger(log string) {
  84. logs.SetLogFuncCall(true)
  85. logs.SetLogger("console")
  86. logs.EnableFuncCallDepth(true)
  87. logs.Async()
  88. logPath := filepath.Join(log, "log.log")
  89. if _, err := os.Stat(logPath); os.IsNotExist(err) {
  90. os.MkdirAll(log, 0777)
  91. if f, err := os.Create(logPath); err == nil {
  92. f.Close()
  93. config := make(map[string]interface{}, 1)
  94. config["filename"] = logPath
  95. b, _ := json.Marshal(config)
  96. beego.SetLogger("file", string(b))
  97. }
  98. }
  99. beego.SetLogFuncCall(true)
  100. beego.BeeLogger.Async()
  101. }
  102. // RunCommand 注册orm命令行工具
  103. func RegisterCommand() {
  104. if len(os.Args) >= 2 && os.Args[1] == "install" {
  105. ResolveCommand(os.Args[2:])
  106. Install()
  107. } else if len(os.Args) >= 2 && os.Args[1] == "version" {
  108. CheckUpdate()
  109. os.Exit(0)
  110. }
  111. }
  112. //注册模板函数
  113. func RegisterFunction() {
  114. beego.AddFuncMap("config", models.GetOptionValue)
  115. beego.AddFuncMap("cdn", func(p string) string {
  116. cdn := beego.AppConfig.DefaultString("cdn", "")
  117. if strings.HasPrefix(p, "http://") || strings.HasPrefix(p, "https://") {
  118. return p
  119. }
  120. //如果没有设置cdn,则使用baseURL拼接
  121. if cdn == "" {
  122. baseUrl := beego.AppConfig.DefaultString("baseurl", "")
  123. if strings.HasPrefix(p, "/") && strings.HasSuffix(baseUrl, "/") {
  124. return baseUrl + p[1:]
  125. }
  126. if !strings.HasPrefix(p, "/") && !strings.HasSuffix(baseUrl, "/") {
  127. return baseUrl + "/" + p
  128. }
  129. return baseUrl + p
  130. }
  131. if strings.HasPrefix(p, "/") && strings.HasSuffix(cdn, "/") {
  132. return cdn + string(p[1:])
  133. }
  134. if !strings.HasPrefix(p, "/") && !strings.HasSuffix(cdn, "/") {
  135. return cdn + "/" + p
  136. }
  137. return cdn + p
  138. })
  139. beego.AddFuncMap("cdnjs", conf.URLForWithCdnJs)
  140. beego.AddFuncMap("cdncss", conf.URLForWithCdnCss)
  141. beego.AddFuncMap("cdnimg", conf.URLForWithCdnImage)
  142. //重写url生成,支持配置域名以及域名前缀
  143. beego.AddFuncMap("urlfor", conf.URLFor)
  144. beego.AddFuncMap("date_format", func(t time.Time, format string) string {
  145. return t.Local().Format(format)
  146. })
  147. }
  148. //解析命令
  149. func ResolveCommand(args []string) {
  150. flagSet := flag.NewFlagSet("MinDoc command: ", flag.ExitOnError)
  151. flagSet.StringVar(&conf.ConfigurationFile, "config", "", "MinDoc configuration file.")
  152. flagSet.StringVar(&conf.WorkingDirectory, "dir", "", "MinDoc working directory.")
  153. flagSet.StringVar(&conf.LogFile, "log", "", "MinDoc log file path.")
  154. flagSet.Parse(args)
  155. if conf.WorkingDirectory == "" {
  156. if p, err := filepath.Abs(os.Args[0]); err == nil {
  157. conf.WorkingDirectory = filepath.Dir(p)
  158. }
  159. }
  160. if conf.LogFile == "" {
  161. conf.LogFile = conf.WorkingDir("runtime","logs")
  162. }
  163. if conf.ConfigurationFile == "" {
  164. conf.ConfigurationFile = conf.WorkingDir( "conf", "app.conf")
  165. config := conf.WorkingDir("conf", "app.conf.example")
  166. if !filetil.FileExists(conf.ConfigurationFile) && filetil.FileExists(config) {
  167. filetil.CopyFile(conf.ConfigurationFile, config)
  168. }
  169. }
  170. if err := gocaptcha.ReadFonts(conf.WorkingDir( "static", "fonts"), ".ttf");err != nil {
  171. log.Fatal("读取字体文件时出错 -> ",err)
  172. }
  173. if err := beego.LoadAppConfig("ini", conf.ConfigurationFile);err != nil {
  174. log.Fatal("An error occurred:", err)
  175. }
  176. uploads := conf.WorkingDir("uploads")
  177. os.MkdirAll(uploads, 0666)
  178. beego.BConfig.WebConfig.StaticDir["/static"] = filepath.Join(conf.WorkingDirectory, "static")
  179. beego.BConfig.WebConfig.StaticDir["/uploads"] = uploads
  180. beego.BConfig.WebConfig.ViewsPath = conf.WorkingDir("views")
  181. fonts := conf.WorkingDir("static", "fonts")
  182. if !filetil.FileExists(fonts) {
  183. log.Fatal("Font path not exist.")
  184. }
  185. gocaptcha.ReadFonts(filepath.Join(conf.WorkingDirectory, "static", "fonts"), ".ttf")
  186. RegisterDataBase()
  187. RegisterCache()
  188. RegisterModel()
  189. RegisterLogger(conf.LogFile)
  190. ModifyPassword()
  191. }
  192. //注册缓存管道
  193. func RegisterCache() {
  194. isOpenCache := beego.AppConfig.DefaultBool("cache", false)
  195. if !isOpenCache {
  196. cache.Init(&cache.NullCache{})
  197. }
  198. beego.Info("正常初始化缓存配置.")
  199. cacheProvider := beego.AppConfig.String("cache_provider")
  200. if cacheProvider == "file" {
  201. cacheFilePath := beego.AppConfig.DefaultString("cache_file_path", "./runtime/cache/")
  202. if strings.HasPrefix(cacheFilePath, "./") {
  203. cacheFilePath = filepath.Join(conf.WorkingDirectory, string(cacheFilePath[1:]))
  204. }
  205. fileCache := beegoCache.NewFileCache()
  206. fileConfig := make(map[string]string, 0)
  207. fileConfig["CachePath"] = cacheFilePath
  208. fileConfig["DirectoryLevel"] = beego.AppConfig.DefaultString("cache_file_dir_level", "2")
  209. fileConfig["EmbedExpiry"] = beego.AppConfig.DefaultString("cache_file_expiry", "120")
  210. fileConfig["FileSuffix"] = beego.AppConfig.DefaultString("cache_file_suffix", ".bin")
  211. bc, err := json.Marshal(&fileConfig)
  212. if err != nil {
  213. beego.Error("初始化file缓存失败:", err)
  214. os.Exit(1)
  215. }
  216. fileCache.StartAndGC(string(bc))
  217. cache.Init(fileCache)
  218. } else if cacheProvider == "memory" {
  219. cacheInterval := beego.AppConfig.DefaultInt("cache_memory_interval", 60)
  220. memory := beegoCache.NewMemoryCache()
  221. beegoCache.DefaultEvery = cacheInterval
  222. cache.Init(memory)
  223. } else if cacheProvider == "redis" {
  224. var redisConfig struct {
  225. Conn string `json:"conn"`
  226. Password string `json:"password"`
  227. DbNum int `json:"dbNum"`
  228. }
  229. redisConfig.DbNum = 0
  230. redisConfig.Conn = beego.AppConfig.DefaultString("cache_redis_host", "")
  231. if pwd := beego.AppConfig.DefaultString("cache_redis_password", ""); pwd != "" {
  232. redisConfig.Password = pwd
  233. }
  234. if dbNum := beego.AppConfig.DefaultInt("cache_redis_db", 0); dbNum > 0 {
  235. redisConfig.DbNum = dbNum
  236. }
  237. bc, err := json.Marshal(&redisConfig)
  238. if err != nil {
  239. beego.Error("初始化Redis缓存失败:", err)
  240. os.Exit(1)
  241. }
  242. redisCache, err := beegoCache.NewCache("redis", string(bc))
  243. if err != nil {
  244. beego.Error("初始化Redis缓存失败:", err)
  245. os.Exit(1)
  246. }
  247. cache.Init(redisCache)
  248. } else if cacheProvider == "memcache" {
  249. var memcacheConfig struct {
  250. Conn string `json:"conn"`
  251. }
  252. memcacheConfig.Conn = beego.AppConfig.DefaultString("cache_memcache_host", "")
  253. bc, err := json.Marshal(&memcacheConfig)
  254. if err != nil {
  255. beego.Error("初始化Redis缓存失败:", err)
  256. os.Exit(1)
  257. }
  258. memcache, err := beegoCache.NewCache("memcache", string(bc))
  259. if err != nil {
  260. beego.Error("初始化Memcache缓存失败:", err)
  261. os.Exit(1)
  262. }
  263. cache.Init(memcache)
  264. } else {
  265. cache.Init(&cache.NullCache{})
  266. beego.Warn("不支持的缓存管道,缓存将禁用.")
  267. return
  268. }
  269. beego.Info("缓存初始化完成.")
  270. }
  271. func init() {
  272. if configPath, err := filepath.Abs(conf.ConfigurationFile); err == nil {
  273. conf.ConfigurationFile = configPath
  274. }
  275. gocaptcha.ReadFonts("./static/fonts", ".ttf")
  276. gob.Register(models.Member{})
  277. if p, err := filepath.Abs(os.Args[0]); err == nil {
  278. conf.WorkingDirectory = filepath.Dir(p)
  279. }
  280. }