command.go 9.9 KB

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