command.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. package commands
  2. import (
  3. "encoding/gob"
  4. "fmt"
  5. "net/url"
  6. "os"
  7. "time"
  8. "flag"
  9. "path/filepath"
  10. "strings"
  11. "github.com/astaxie/beego"
  12. "github.com/astaxie/beego/logs"
  13. "github.com/astaxie/beego/orm"
  14. "github.com/lifei6671/gocaptcha"
  15. "github.com/lifei6671/godoc/commands/migrate"
  16. "github.com/lifei6671/godoc/conf"
  17. "github.com/lifei6671/godoc/models"
  18. "github.com/lifei6671/godoc/utils"
  19. "log"
  20. "encoding/json"
  21. )
  22. var (
  23. ConfigurationFile = "./conf/app.conf"
  24. WorkingDirectory = "./"
  25. LogFile = "./logs"
  26. )
  27. // RegisterDataBase 注册数据库
  28. func RegisterDataBase() {
  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. orm.RegisterDataBase("default", "mysql", dataSource)
  39. location, err := time.LoadLocation(timezone)
  40. if err == nil {
  41. orm.DefaultTimeLoc = location
  42. } else {
  43. log.Fatalln(err)
  44. }
  45. } else if adapter == "sqlite3" {
  46. database := beego.AppConfig.String("db_database")
  47. if strings.HasPrefix(database,"./") {
  48. database = filepath.Join(WorkingDirectory,string(database[1:]))
  49. }
  50. dbPath := filepath.Dir(database)
  51. os.MkdirAll(dbPath, 0777)
  52. orm.RegisterDataBase("default", "sqlite3", database)
  53. }
  54. }
  55. // RegisterModel 注册Model
  56. func RegisterModel() {
  57. orm.RegisterModelWithPrefix(conf.GetDatabasePrefix(),
  58. new(models.Member),
  59. new(models.Book),
  60. new(models.Relationship),
  61. new(models.Option),
  62. new(models.Document),
  63. new(models.Attachment),
  64. new(models.Logger),
  65. new(models.MemberToken),
  66. new(models.DocumentHistory),
  67. new(models.Migration),
  68. )
  69. migrate.RegisterMigration()
  70. }
  71. // RegisterLogger 注册日志
  72. func RegisterLogger(log string) {
  73. logs.SetLogFuncCall(true)
  74. logs.SetLogger("console")
  75. logs.EnableFuncCallDepth(true)
  76. logs.Async()
  77. logPath := filepath.Join(log, "log.log")
  78. if _, err := os.Stat(logPath); os.IsNotExist(err) {
  79. os.MkdirAll(log, 0777)
  80. if f, err := os.Create(logPath); err == nil {
  81. f.Close()
  82. config := make(map[string]interface{},1)
  83. config["filename"] = logPath
  84. b,_ := json.Marshal(config)
  85. beego.SetLogger("file", string(b))
  86. }
  87. }
  88. beego.SetLogFuncCall(true)
  89. beego.BeeLogger.Async()
  90. }
  91. // RunCommand 注册orm命令行工具
  92. func RegisterCommand() {
  93. if len(os.Args) >= 2 && os.Args[1] == "install" {
  94. ResolveCommand(os.Args[2:])
  95. Install()
  96. } else if len(os.Args) >= 2 && os.Args[1] == "version" {
  97. ResolveCommand(os.Args[2:])
  98. CheckUpdate()
  99. } else if len(os.Args) >= 2 && os.Args[1] == "migrate" {
  100. ResolveCommand(os.Args[2:])
  101. migrate.RunMigration()
  102. }
  103. }
  104. func RegisterFunction() {
  105. beego.AddFuncMap("config", models.GetOptionValue)
  106. beego.AddFuncMap("cdn", func(p string) string {
  107. cdn := beego.AppConfig.DefaultString("cdn", "")
  108. if strings.HasPrefix(p, "/") && strings.HasSuffix(cdn, "/") {
  109. return cdn + string(p[1:])
  110. }
  111. if !strings.HasPrefix(p, "/") && !strings.HasSuffix(cdn, "/") {
  112. return cdn + "/" + p
  113. }
  114. return cdn + p
  115. })
  116. beego.AddFuncMap("cdnjs", func(p string) string {
  117. cdn := beego.AppConfig.DefaultString("cdnjs", "")
  118. if strings.HasPrefix(p, "/") && strings.HasSuffix(cdn, "/") {
  119. return cdn + string(p[1:])
  120. }
  121. if !strings.HasPrefix(p, "/") && !strings.HasSuffix(cdn, "/") {
  122. return cdn + "/" + p
  123. }
  124. return cdn + p
  125. })
  126. beego.AddFuncMap("cdncss", func(p string) string {
  127. cdn := beego.AppConfig.DefaultString("cdncss", "")
  128. if strings.HasPrefix(p, "/") && strings.HasSuffix(cdn, "/") {
  129. return cdn + string(p[1:])
  130. }
  131. if !strings.HasPrefix(p, "/") && !strings.HasSuffix(cdn, "/") {
  132. return cdn + "/" + p
  133. }
  134. return cdn + p
  135. })
  136. beego.AddFuncMap("cdnimg", func(p string) string {
  137. cdn := beego.AppConfig.DefaultString("cdnimg", "")
  138. if strings.HasPrefix(p, "/") && strings.HasSuffix(cdn, "/") {
  139. return cdn + string(p[1:])
  140. }
  141. if !strings.HasPrefix(p, "/") && !strings.HasSuffix(cdn, "/") {
  142. return cdn + "/" + p
  143. }
  144. return cdn + p
  145. })
  146. }
  147. func ResolveCommand(args []string) {
  148. flagSet := flag.NewFlagSet("MinDoc command: ", flag.ExitOnError)
  149. flagSet.StringVar(&ConfigurationFile, "config", "", "MinDoc configuration file.")
  150. flagSet.StringVar(&WorkingDirectory, "dir", "", "MinDoc working directory.")
  151. flagSet.StringVar(&LogFile, "log", "", "MinDoc log file path.")
  152. flagSet.Parse(args)
  153. if WorkingDirectory == "" {
  154. if p, err := filepath.Abs(os.Args[0]); err == nil {
  155. WorkingDirectory = filepath.Dir(p)
  156. }
  157. }
  158. if LogFile == "" {
  159. LogFile = filepath.Join(WorkingDirectory,"logs")
  160. }
  161. if ConfigurationFile == "" {
  162. ConfigurationFile = filepath.Join(WorkingDirectory,"conf","app.conf")
  163. config := filepath.Join(WorkingDirectory,"conf","app.conf.example")
  164. if !utils.FileExists(ConfigurationFile) && utils.FileExists(config){
  165. utils.CopyFile(ConfigurationFile,config)
  166. }
  167. }
  168. gocaptcha.ReadFonts(filepath.Join(WorkingDirectory,"static","fonts"), ".ttf")
  169. err := beego.LoadAppConfig("ini", ConfigurationFile)
  170. if err != nil {
  171. log.Println("An error occurred:", err)
  172. os.Exit(1)
  173. }
  174. uploads := filepath.Join(WorkingDirectory, "uploads")
  175. os.MkdirAll(uploads,0666)
  176. beego.BConfig.WebConfig.StaticDir["/static"] = filepath.Join(WorkingDirectory, "static")
  177. beego.BConfig.WebConfig.StaticDir["/uploads"] = uploads
  178. beego.BConfig.WebConfig.ViewsPath = filepath.Join(WorkingDirectory, "views")
  179. fonts := filepath.Join(WorkingDirectory, "static", "fonts")
  180. if !utils.FileExists(fonts) {
  181. log.Fatal("Font path not exist.")
  182. }
  183. gocaptcha.ReadFonts(filepath.Join(WorkingDirectory, "static", "fonts"), ".ttf")
  184. RegisterDataBase()
  185. RegisterModel()
  186. RegisterLogger(LogFile)
  187. }
  188. func init() {
  189. gocaptcha.ReadFonts("./static/fonts", ".ttf")
  190. gob.Register(models.Member{})
  191. if p,err := filepath.Abs(os.Args[0]);err == nil{
  192. WorkingDirectory = filepath.Dir(p)
  193. }
  194. }