command.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. package commands
  2. import (
  3. "encoding/gob"
  4. "fmt"
  5. "net/url"
  6. "os"
  7. "time"
  8. "log"
  9. "flag"
  10. "path/filepath"
  11. "strings"
  12. "encoding/json"
  13. "github.com/astaxie/beego"
  14. "github.com/astaxie/beego/logs"
  15. "github.com/astaxie/beego/orm"
  16. "github.com/lifei6671/gocaptcha"
  17. "github.com/lifei6671/mindoc/commands/migrate"
  18. "github.com/lifei6671/mindoc/conf"
  19. "github.com/lifei6671/mindoc/models"
  20. "github.com/lifei6671/mindoc/utils"
  21. "github.com/lifei6671/mindoc/cache"
  22. beegoCache "github.com/astaxie/beego/cache"
  23. _ "github.com/astaxie/beego/cache/memcache"
  24. _ "github.com/astaxie/beego/cache/redis"
  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. port := beego.AppConfig.String("db_port")
  37. dataSource := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true&loc=%s", username, password, host, port, database, url.QueryEscape(timezone))
  38. err := orm.RegisterDataBase("default", "mysql", dataSource)
  39. if err != nil {
  40. beego.Error("注册默认数据库失败:",err)
  41. os.Exit(1)
  42. }
  43. location, err := time.LoadLocation(timezone)
  44. if err == nil {
  45. orm.DefaultTimeLoc = location
  46. } else {
  47. beego.Error("加载时区配置信息失败,请检查是否存在ZONEINFO环境变量:",err)
  48. }
  49. } else if adapter == "sqlite3" {
  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. }
  149. //解析命令
  150. func ResolveCommand(args []string) {
  151. flagSet := flag.NewFlagSet("MinDoc command: ", flag.ExitOnError)
  152. flagSet.StringVar(&conf.ConfigurationFile, "config", "", "MinDoc configuration file.")
  153. flagSet.StringVar(&conf.WorkingDirectory, "dir", "", "MinDoc working directory.")
  154. flagSet.StringVar(&conf.LogFile, "log", "", "MinDoc log file path.")
  155. flagSet.Parse(args)
  156. if conf.WorkingDirectory == "" {
  157. if p, err := filepath.Abs(os.Args[0]); err == nil {
  158. conf.WorkingDirectory = filepath.Dir(p)
  159. }
  160. }
  161. if conf.LogFile == "" {
  162. conf.LogFile = filepath.Join(conf.WorkingDirectory, "logs")
  163. }
  164. if conf.ConfigurationFile == "" {
  165. conf.ConfigurationFile = filepath.Join(conf.WorkingDirectory, "conf", "app.conf")
  166. config := filepath.Join(conf.WorkingDirectory, "conf", "app.conf.example")
  167. if !utils.FileExists(conf.ConfigurationFile) && utils.FileExists(config) {
  168. utils.CopyFile(conf.ConfigurationFile, config)
  169. }
  170. }
  171. gocaptcha.ReadFonts(filepath.Join(conf.WorkingDirectory, "static", "fonts"), ".ttf")
  172. err := beego.LoadAppConfig("ini", conf.ConfigurationFile)
  173. if err != nil {
  174. log.Println("An error occurred:", err)
  175. os.Exit(1)
  176. }
  177. uploads := filepath.Join(conf.WorkingDirectory, "uploads")
  178. os.MkdirAll(uploads, 0666)
  179. beego.BConfig.WebConfig.StaticDir["/static"] = filepath.Join(conf.WorkingDirectory, "static")
  180. beego.BConfig.WebConfig.StaticDir["/uploads"] = uploads
  181. beego.BConfig.WebConfig.ViewsPath = filepath.Join(conf.WorkingDirectory, "views")
  182. fonts := filepath.Join(conf.WorkingDirectory, "static", "fonts")
  183. if !utils.FileExists(fonts) {
  184. log.Fatal("Font path not exist.")
  185. }
  186. gocaptcha.ReadFonts(filepath.Join(conf.WorkingDirectory, "static", "fonts"), ".ttf")
  187. RegisterDataBase()
  188. RegisterCache()
  189. RegisterModel()
  190. RegisterLogger(conf.LogFile)
  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("初始化Redis缓存失败:",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. }