command.go 9.9 KB

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