command.go 9.4 KB

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