command.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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/mindoc/commands/migrate"
  16. "github.com/lifei6671/mindoc/conf"
  17. "github.com/lifei6671/mindoc/models"
  18. "github.com/lifei6671/mindoc/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. new(models.Label),
  69. )
  70. migrate.RegisterMigration()
  71. }
  72. // RegisterLogger 注册日志
  73. func RegisterLogger(log string) {
  74. logs.SetLogFuncCall(true)
  75. logs.SetLogger("console")
  76. logs.EnableFuncCallDepth(true)
  77. logs.Async()
  78. logPath := filepath.Join(log, "log.log")
  79. if _, err := os.Stat(logPath); os.IsNotExist(err) {
  80. os.MkdirAll(log, 0777)
  81. if f, err := os.Create(logPath); err == nil {
  82. f.Close()
  83. config := make(map[string]interface{},1)
  84. config["filename"] = logPath
  85. b,_ := json.Marshal(config)
  86. beego.SetLogger("file", string(b))
  87. }
  88. }
  89. beego.SetLogFuncCall(true)
  90. beego.BeeLogger.Async()
  91. }
  92. // RunCommand 注册orm命令行工具
  93. func RegisterCommand() {
  94. if len(os.Args) >= 2 && os.Args[1] == "install" {
  95. ResolveCommand(os.Args[2:])
  96. Install()
  97. } else if len(os.Args) >= 2 && os.Args[1] == "version" {
  98. ResolveCommand(os.Args[2:])
  99. CheckUpdate()
  100. } else if len(os.Args) >= 2 && os.Args[1] == "migrate" {
  101. ResolveCommand(os.Args[2:])
  102. migrate.RunMigration()
  103. }
  104. }
  105. func RegisterFunction() {
  106. beego.AddFuncMap("config", models.GetOptionValue)
  107. beego.AddFuncMap("cdn", func(p string) string {
  108. cdn := beego.AppConfig.DefaultString("cdn", "")
  109. if strings.HasPrefix(p,"http://") || strings.HasPrefix(p,"https://") {
  110. return p
  111. }
  112. if strings.HasPrefix(p, "/") && strings.HasSuffix(cdn, "/") {
  113. return cdn + string(p[1:])
  114. }
  115. if !strings.HasPrefix(p, "/") && !strings.HasSuffix(cdn, "/") {
  116. return cdn + "/" + p
  117. }
  118. return cdn + p
  119. })
  120. beego.AddFuncMap("cdnjs", func(p string) string {
  121. cdn := beego.AppConfig.DefaultString("cdnjs", "")
  122. if strings.HasPrefix(p,"http://") || strings.HasPrefix(p,"https://") {
  123. return p
  124. }
  125. if strings.HasPrefix(p, "/") && strings.HasSuffix(cdn, "/") {
  126. return cdn + string(p[1:])
  127. }
  128. if !strings.HasPrefix(p, "/") && !strings.HasSuffix(cdn, "/") {
  129. return cdn + "/" + p
  130. }
  131. return cdn + p
  132. })
  133. beego.AddFuncMap("cdncss", func(p string) string {
  134. cdn := beego.AppConfig.DefaultString("cdncss", "")
  135. if strings.HasPrefix(p,"http://") || strings.HasPrefix(p,"https://") {
  136. return p
  137. }
  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. beego.AddFuncMap("cdnimg", func(p string) string {
  147. if strings.HasPrefix(p,"http://") || strings.HasPrefix(p,"https://") {
  148. return p
  149. }
  150. cdn := beego.AppConfig.DefaultString("cdnimg", "")
  151. if strings.HasPrefix(p, "/") && strings.HasSuffix(cdn, "/") {
  152. return cdn + string(p[1:])
  153. }
  154. if !strings.HasPrefix(p, "/") && !strings.HasSuffix(cdn, "/") {
  155. return cdn + "/" + p
  156. }
  157. return cdn + p
  158. })
  159. }
  160. func ResolveCommand(args []string) {
  161. flagSet := flag.NewFlagSet("MinDoc command: ", flag.ExitOnError)
  162. flagSet.StringVar(&ConfigurationFile, "config", "", "MinDoc configuration file.")
  163. flagSet.StringVar(&WorkingDirectory, "dir", "", "MinDoc working directory.")
  164. flagSet.StringVar(&LogFile, "log", "", "MinDoc log file path.")
  165. flagSet.Parse(args)
  166. if WorkingDirectory == "" {
  167. if p, err := filepath.Abs(os.Args[0]); err == nil {
  168. WorkingDirectory = filepath.Dir(p)
  169. }
  170. }
  171. if LogFile == "" {
  172. LogFile = filepath.Join(WorkingDirectory,"logs")
  173. }
  174. if ConfigurationFile == "" {
  175. ConfigurationFile = filepath.Join(WorkingDirectory,"conf","app.conf")
  176. config := filepath.Join(WorkingDirectory,"conf","app.conf.example")
  177. if !utils.FileExists(ConfigurationFile) && utils.FileExists(config){
  178. utils.CopyFile(ConfigurationFile,config)
  179. }
  180. }
  181. gocaptcha.ReadFonts(filepath.Join(WorkingDirectory,"static","fonts"), ".ttf")
  182. err := beego.LoadAppConfig("ini", ConfigurationFile)
  183. if err != nil {
  184. log.Println("An error occurred:", err)
  185. os.Exit(1)
  186. }
  187. uploads := filepath.Join(WorkingDirectory, "uploads")
  188. os.MkdirAll(uploads,0666)
  189. beego.BConfig.WebConfig.StaticDir["/static"] = filepath.Join(WorkingDirectory, "static")
  190. beego.BConfig.WebConfig.StaticDir["/uploads"] = uploads
  191. beego.BConfig.WebConfig.ViewsPath = filepath.Join(WorkingDirectory, "views")
  192. fonts := filepath.Join(WorkingDirectory, "static", "fonts")
  193. if !utils.FileExists(fonts) {
  194. log.Fatal("Font path not exist.")
  195. }
  196. gocaptcha.ReadFonts(filepath.Join(WorkingDirectory, "static", "fonts"), ".ttf")
  197. RegisterDataBase()
  198. RegisterModel()
  199. RegisterLogger(LogFile)
  200. }
  201. func init() {
  202. gocaptcha.ReadFonts("./static/fonts", ".ttf")
  203. gob.Register(models.Member{})
  204. if p,err := filepath.Abs(os.Args[0]);err == nil{
  205. WorkingDirectory = filepath.Dir(p)
  206. }
  207. }