command.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. "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. 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. new(models.Blog),
  81. )
  82. gob.Register(models.Blog{})
  83. gob.Register(models.Document{})
  84. //migrate.RegisterMigration()
  85. }
  86. // RegisterLogger 注册日志
  87. func RegisterLogger(log string) {
  88. logs.SetLogFuncCall(true)
  89. logs.SetLogger("console")
  90. logs.EnableFuncCallDepth(true)
  91. if beego.AppConfig.DefaultBool("log_is_async", true) {
  92. logs.Async(1e3)
  93. }
  94. if log == "" {
  95. log = conf.WorkingDir("runtime","logs")
  96. }
  97. logPath := filepath.Join(log, "log.log")
  98. if _, err := os.Stat(log); os.IsNotExist(err) {
  99. os.MkdirAll(log, 0777)
  100. }
  101. config := make(map[string]interface{}, 1)
  102. config["filename"] = logPath
  103. config["perm"] = "0755"
  104. config["rotate"] = true
  105. if maxLines := beego.AppConfig.DefaultInt("log_maxlines", 1000000); maxLines > 0 {
  106. config["maxLines"] = maxLines
  107. }
  108. if maxSize := beego.AppConfig.DefaultInt("log_maxsize", 1<<28); maxSize > 0 {
  109. config["maxsize"] = maxSize
  110. }
  111. if !beego.AppConfig.DefaultBool("log_daily", true) {
  112. config["daily"] = false
  113. }
  114. if maxDays := beego.AppConfig.DefaultInt("log_maxdays", 7); maxDays > 0 {
  115. config["maxdays"] = maxDays
  116. }
  117. if level := beego.AppConfig.DefaultString("log_level", "Trace"); level != "" {
  118. switch level {
  119. case "Emergency":
  120. config["level"] = beego.LevelEmergency;break
  121. case "Alert":
  122. config["level"] = beego.LevelAlert;break
  123. case "Critical":
  124. config["level"] = beego.LevelCritical;break
  125. case "Error":
  126. config["level"] = beego.LevelError; break
  127. case "Warning":
  128. config["level"] = beego.LevelWarning; break
  129. case "Notice":
  130. config["level"] = beego.LevelNotice; break
  131. case "Informational":
  132. config["level"] = beego.LevelInformational;break
  133. case "Debug":
  134. config["level"] = beego.LevelDebug;break
  135. }
  136. }
  137. b, err := json.Marshal(config);
  138. if err != nil {
  139. beego.Error("初始化文件日志时出错 ->",err)
  140. beego.SetLogger("file", `{"filename":"`+ logPath + `"}`)
  141. }else{
  142. beego.SetLogger(logs.AdapterFile, string(b))
  143. }
  144. beego.SetLogFuncCall(true)
  145. }
  146. // RunCommand 注册orm命令行工具
  147. func RegisterCommand() {
  148. if len(os.Args) >= 2 && os.Args[1] == "install" {
  149. ResolveCommand(os.Args[2:])
  150. Install()
  151. } else if len(os.Args) >= 2 && os.Args[1] == "version" {
  152. CheckUpdate()
  153. os.Exit(0)
  154. }
  155. }
  156. //注册模板函数
  157. func RegisterFunction() {
  158. beego.AddFuncMap("config", models.GetOptionValue)
  159. beego.AddFuncMap("cdn", func(p string) string {
  160. cdn := beego.AppConfig.DefaultString("cdn", "")
  161. if strings.HasPrefix(p, "http://") || strings.HasPrefix(p, "https://") {
  162. return p
  163. }
  164. //如果没有设置cdn,则使用baseURL拼接
  165. if cdn == "" {
  166. baseUrl := beego.AppConfig.DefaultString("baseurl", "")
  167. if strings.HasPrefix(p, "/") && strings.HasSuffix(baseUrl, "/") {
  168. return baseUrl + p[1:]
  169. }
  170. if !strings.HasPrefix(p, "/") && !strings.HasSuffix(baseUrl, "/") {
  171. return baseUrl + "/" + p
  172. }
  173. return baseUrl + p
  174. }
  175. if strings.HasPrefix(p, "/") && strings.HasSuffix(cdn, "/") {
  176. return cdn + string(p[1:])
  177. }
  178. if !strings.HasPrefix(p, "/") && !strings.HasSuffix(cdn, "/") {
  179. return cdn + "/" + p
  180. }
  181. return cdn + p
  182. })
  183. beego.AddFuncMap("cdnjs", conf.URLForWithCdnJs)
  184. beego.AddFuncMap("cdncss", conf.URLForWithCdnCss)
  185. beego.AddFuncMap("cdnimg", conf.URLForWithCdnImage)
  186. //重写url生成,支持配置域名以及域名前缀
  187. beego.AddFuncMap("urlfor", conf.URLFor)
  188. beego.AddFuncMap("date_format", func(t time.Time, format string) string {
  189. return t.Local().Format(format)
  190. })
  191. }
  192. //解析命令
  193. func ResolveCommand(args []string) {
  194. flagSet := flag.NewFlagSet("MinDoc command: ", flag.ExitOnError)
  195. flagSet.StringVar(&conf.ConfigurationFile, "config", "", "MinDoc configuration file.")
  196. flagSet.StringVar(&conf.WorkingDirectory, "dir", "", "MinDoc working directory.")
  197. flagSet.StringVar(&conf.LogFile, "log", "", "MinDoc log file path.")
  198. flagSet.Parse(args)
  199. if conf.WorkingDirectory == "" {
  200. if p, err := filepath.Abs(os.Args[0]); err == nil {
  201. conf.WorkingDirectory = filepath.Dir(p)
  202. }
  203. }
  204. if conf.LogFile == "" {
  205. conf.LogFile = conf.WorkingDir("runtime","logs")
  206. }
  207. if conf.ConfigurationFile == "" {
  208. conf.ConfigurationFile = conf.WorkingDir( "conf", "app.conf")
  209. config := conf.WorkingDir("conf", "app.conf.example")
  210. if !filetil.FileExists(conf.ConfigurationFile) && filetil.FileExists(config) {
  211. filetil.CopyFile(conf.ConfigurationFile, config)
  212. }
  213. }
  214. if err := gocaptcha.ReadFonts(conf.WorkingDir( "static", "fonts"), ".ttf");err != nil {
  215. log.Fatal("读取字体文件时出错 -> ",err)
  216. }
  217. if err := beego.LoadAppConfig("ini", conf.ConfigurationFile);err != nil {
  218. log.Fatal("An error occurred:", err)
  219. }
  220. uploads := conf.WorkingDir("uploads")
  221. os.MkdirAll(uploads, 0666)
  222. beego.BConfig.WebConfig.StaticDir["/static"] = filepath.Join(conf.WorkingDirectory, "static")
  223. beego.BConfig.WebConfig.StaticDir["/uploads"] = uploads
  224. beego.BConfig.WebConfig.ViewsPath = conf.WorkingDir("views")
  225. fonts := conf.WorkingDir("static", "fonts")
  226. if !filetil.FileExists(fonts) {
  227. log.Fatal("Font path not exist.")
  228. }
  229. gocaptcha.ReadFonts(filepath.Join(conf.WorkingDirectory, "static", "fonts"), ".ttf")
  230. RegisterDataBase()
  231. RegisterCache()
  232. RegisterModel()
  233. RegisterLogger(conf.LogFile)
  234. ModifyPassword()
  235. }
  236. //注册缓存管道
  237. func RegisterCache() {
  238. isOpenCache := beego.AppConfig.DefaultBool("cache", false)
  239. if !isOpenCache {
  240. cache.Init(&cache.NullCache{})
  241. }
  242. beego.Info("正常初始化缓存配置.")
  243. cacheProvider := beego.AppConfig.String("cache_provider")
  244. if cacheProvider == "file" {
  245. cacheFilePath := beego.AppConfig.DefaultString("cache_file_path", "./runtime/cache/")
  246. if strings.HasPrefix(cacheFilePath, "./") {
  247. cacheFilePath = filepath.Join(conf.WorkingDirectory, string(cacheFilePath[1:]))
  248. }
  249. fileCache := beegoCache.NewFileCache()
  250. fileConfig := make(map[string]string, 0)
  251. fileConfig["CachePath"] = cacheFilePath
  252. fileConfig["DirectoryLevel"] = beego.AppConfig.DefaultString("cache_file_dir_level", "2")
  253. fileConfig["EmbedExpiry"] = beego.AppConfig.DefaultString("cache_file_expiry", "120")
  254. fileConfig["FileSuffix"] = beego.AppConfig.DefaultString("cache_file_suffix", ".bin")
  255. bc, err := json.Marshal(&fileConfig)
  256. if err != nil {
  257. beego.Error("初始化file缓存失败:", err)
  258. os.Exit(1)
  259. }
  260. fileCache.StartAndGC(string(bc))
  261. cache.Init(fileCache)
  262. } else if cacheProvider == "memory" {
  263. cacheInterval := beego.AppConfig.DefaultInt("cache_memory_interval", 60)
  264. memory := beegoCache.NewMemoryCache()
  265. beegoCache.DefaultEvery = cacheInterval
  266. cache.Init(memory)
  267. } else if cacheProvider == "redis" {
  268. //设置Redis前缀
  269. if key := beego.AppConfig.DefaultString("cache_redis_prefix",""); key != "" {
  270. redis.DefaultKey = key
  271. }
  272. var redisConfig struct {
  273. Conn string `json:"conn"`
  274. Password string `json:"password"`
  275. DbNum int `json:"dbNum"`
  276. }
  277. redisConfig.DbNum = 0
  278. redisConfig.Conn = beego.AppConfig.DefaultString("cache_redis_host", "")
  279. if pwd := beego.AppConfig.DefaultString("cache_redis_password", ""); pwd != "" {
  280. redisConfig.Password = pwd
  281. }
  282. if dbNum := beego.AppConfig.DefaultInt("cache_redis_db", 0); dbNum > 0 {
  283. redisConfig.DbNum = dbNum
  284. }
  285. bc, err := json.Marshal(&redisConfig)
  286. if err != nil {
  287. beego.Error("初始化Redis缓存失败:", err)
  288. os.Exit(1)
  289. }
  290. redisCache, err := beegoCache.NewCache("redis", string(bc))
  291. if err != nil {
  292. beego.Error("初始化Redis缓存失败:", err)
  293. os.Exit(1)
  294. }
  295. cache.Init(redisCache)
  296. } else if cacheProvider == "memcache" {
  297. var memcacheConfig struct {
  298. Conn string `json:"conn"`
  299. }
  300. memcacheConfig.Conn = beego.AppConfig.DefaultString("cache_memcache_host", "")
  301. bc, err := json.Marshal(&memcacheConfig)
  302. if err != nil {
  303. beego.Error("初始化Redis缓存失败:", err)
  304. os.Exit(1)
  305. }
  306. memcache, err := beegoCache.NewCache("memcache", string(bc))
  307. if err != nil {
  308. beego.Error("初始化Memcache缓存失败:", err)
  309. os.Exit(1)
  310. }
  311. cache.Init(memcache)
  312. } else {
  313. cache.Init(&cache.NullCache{})
  314. beego.Warn("不支持的缓存管道,缓存将禁用 ->" ,cacheProvider)
  315. return
  316. }
  317. beego.Info("缓存初始化完成.")
  318. }
  319. func init() {
  320. if configPath, err := filepath.Abs(conf.ConfigurationFile); err == nil {
  321. conf.ConfigurationFile = configPath
  322. }
  323. gocaptcha.ReadFonts("./static/fonts", ".ttf")
  324. gob.Register(models.Member{})
  325. if p, err := filepath.Abs(os.Args[0]); err == nil {
  326. conf.WorkingDirectory = filepath.Dir(p)
  327. }
  328. }