command.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. package commands
  2. import (
  3. "encoding/gob"
  4. "flag"
  5. "fmt"
  6. "log"
  7. "net/url"
  8. "os"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "time"
  13. _ "time/tzdata"
  14. "bytes"
  15. "encoding/json"
  16. "net/http"
  17. beegoCache "github.com/beego/beego/v2/client/cache"
  18. _ "github.com/beego/beego/v2/client/cache/memcache"
  19. "github.com/beego/beego/v2/client/cache/redis"
  20. "github.com/beego/beego/v2/client/orm"
  21. "github.com/beego/beego/v2/core/logs"
  22. "github.com/beego/beego/v2/server/web"
  23. "github.com/beego/i18n"
  24. "github.com/howeyc/fsnotify"
  25. _ "github.com/lib/pq"
  26. "github.com/lifei6671/gocaptcha"
  27. "github.com/mindoc-org/mindoc/cache"
  28. "github.com/mindoc-org/mindoc/conf"
  29. "github.com/mindoc-org/mindoc/models"
  30. "github.com/mindoc-org/mindoc/utils/filetil"
  31. )
  32. // RegisterDataBase 注册数据库
  33. func RegisterDataBase() {
  34. logs.Info("正在初始化数据库配置.")
  35. dbadapter, _ := web.AppConfig.String("db_adapter")
  36. orm.DefaultTimeLoc = time.Local
  37. orm.DefaultRowsLimit = -1
  38. if strings.EqualFold(dbadapter, "mysql") {
  39. host, _ := web.AppConfig.String("db_host")
  40. database, _ := web.AppConfig.String("db_database")
  41. username, _ := web.AppConfig.String("db_username")
  42. password, _ := web.AppConfig.String("db_password")
  43. timezone, _ := web.AppConfig.String("timezone")
  44. location, err := time.LoadLocation(timezone)
  45. if err == nil {
  46. orm.DefaultTimeLoc = location
  47. } else {
  48. logs.Error("加载时区配置信息失败,请检查是否存在 ZONEINFO 环境变量->", err)
  49. }
  50. port, _ := web.AppConfig.String("db_port")
  51. dataSource := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true&loc=%s", username, password, host, port, database, url.QueryEscape(timezone))
  52. if err := orm.RegisterDataBase("default", "mysql", dataSource); err != nil {
  53. logs.Error("注册默认数据库失败->", err)
  54. os.Exit(1)
  55. }
  56. } else if strings.EqualFold(dbadapter, "sqlite3") {
  57. database, _ := web.AppConfig.String("db_database")
  58. if strings.HasPrefix(database, "./") {
  59. database = filepath.Join(conf.WorkingDirectory, string(database[1:]))
  60. }
  61. if p, err := filepath.Abs(database); err == nil {
  62. database = p
  63. }
  64. dbPath := filepath.Dir(database)
  65. if _, err := os.Stat(dbPath); err != nil && os.IsNotExist(err) {
  66. _ = os.MkdirAll(dbPath, 0777)
  67. }
  68. err := orm.RegisterDataBase("default", "sqlite3", database)
  69. if err != nil {
  70. logs.Error("注册默认数据库失败->", err)
  71. }
  72. } else if strings.EqualFold(dbadapter, "postgres") {
  73. host, _ := web.AppConfig.String("db_host")
  74. database, _ := web.AppConfig.String("db_database")
  75. username, _ := web.AppConfig.String("db_username")
  76. password, _ := web.AppConfig.String("db_password")
  77. sslmode, _ := web.AppConfig.String("db_sslmode")
  78. timezone, _ := web.AppConfig.String("timezone")
  79. location, err := time.LoadLocation(timezone)
  80. if err == nil {
  81. orm.DefaultTimeLoc = location
  82. } else {
  83. logs.Error("加载时区配置信息失败,请检查是否存在 ZONEINFO 环境变量->", err)
  84. }
  85. port, _ := web.AppConfig.String("db_port")
  86. dataSource := fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=%s", username, password, host, port, database, sslmode)
  87. if err := orm.RegisterDataBase("default", "postgres", dataSource); err != nil {
  88. logs.Error("注册默认数据库失败->", err)
  89. os.Exit(1)
  90. }
  91. } else {
  92. logs.Error("不支持的数据库类型.")
  93. os.Exit(1)
  94. }
  95. logs.Info("数据库初始化完成.")
  96. }
  97. // RegisterModel 注册Model
  98. func RegisterModel() {
  99. orm.RegisterModelWithPrefix(conf.GetDatabasePrefix(),
  100. new(models.Member),
  101. new(models.Book),
  102. new(models.Relationship),
  103. new(models.Option),
  104. new(models.Document),
  105. new(models.Attachment),
  106. new(models.Logger),
  107. new(models.MemberToken),
  108. new(models.DocumentHistory),
  109. new(models.Migration),
  110. new(models.Label),
  111. new(models.Blog),
  112. new(models.Template),
  113. new(models.Team),
  114. new(models.TeamMember),
  115. new(models.TeamRelationship),
  116. new(models.Itemsets),
  117. new(models.Comment),
  118. new(models.WorkWeixinAccount),
  119. new(models.DingTalkAccount),
  120. )
  121. gob.Register(models.Blog{})
  122. gob.Register(models.Document{})
  123. gob.Register(models.Template{})
  124. //migrate.RegisterMigration()
  125. err := orm.RunSyncdb("default", false, true)
  126. if err != nil {
  127. logs.Error("注册Model失败 ->", err)
  128. os.Exit(1)
  129. }
  130. }
  131. // RegisterLogger 注册日志
  132. func RegisterLogger(log string) {
  133. logs.Reset()
  134. logs.SetLogFuncCall(true)
  135. _ = logs.SetLogger("console")
  136. logs.EnableFuncCallDepth(true)
  137. if web.AppConfig.DefaultBool("log_is_async", true) {
  138. logs.Async(1e3)
  139. }
  140. if log == "" {
  141. logPath, err := filepath.Abs(web.AppConfig.DefaultString("log_path", conf.WorkingDir("runtime", "logs")))
  142. if err == nil {
  143. log = logPath
  144. } else {
  145. log = conf.WorkingDir("runtime", "logs")
  146. }
  147. }
  148. logPath := filepath.Join(log, "log.log")
  149. if _, err := os.Stat(log); os.IsNotExist(err) {
  150. _ = os.MkdirAll(log, 0755)
  151. }
  152. config := make(map[string]interface{}, 1)
  153. config["filename"] = logPath
  154. config["perm"] = "0755"
  155. config["rotate"] = true
  156. if maxLines := web.AppConfig.DefaultInt("log_maxlines", 1000000); maxLines > 0 {
  157. config["maxLines"] = maxLines
  158. }
  159. if maxSize := web.AppConfig.DefaultInt("log_maxsize", 1<<28); maxSize > 0 {
  160. config["maxsize"] = maxSize
  161. }
  162. if !web.AppConfig.DefaultBool("log_daily", true) {
  163. config["daily"] = false
  164. }
  165. if maxDays := web.AppConfig.DefaultInt("log_maxdays", 7); maxDays > 0 {
  166. config["maxdays"] = maxDays
  167. }
  168. if level := web.AppConfig.DefaultString("log_level", "Trace"); level != "" {
  169. switch level {
  170. case "Emergency":
  171. config["level"] = logs.LevelEmergency
  172. case "Alert":
  173. config["level"] = logs.LevelAlert
  174. case "Critical":
  175. config["level"] = logs.LevelCritical
  176. case "Error":
  177. config["level"] = logs.LevelError
  178. case "Warning":
  179. config["level"] = logs.LevelWarning
  180. case "Notice":
  181. config["level"] = logs.LevelNotice
  182. case "Informational":
  183. config["level"] = logs.LevelInformational
  184. case "Debug":
  185. config["level"] = logs.LevelDebug
  186. }
  187. }
  188. b, err := json.Marshal(config)
  189. if err != nil {
  190. logs.Error("初始化文件日志时出错 ->", err)
  191. _ = logs.SetLogger("file", `{"filename":"`+logPath+`"}`)
  192. } else {
  193. _ = logs.SetLogger(logs.AdapterFile, string(b))
  194. }
  195. logs.SetLogFuncCall(true)
  196. }
  197. // RunCommand 注册orm命令行工具
  198. func RegisterCommand() {
  199. if len(os.Args) >= 2 && os.Args[1] == "install" {
  200. ResolveCommand(os.Args[2:])
  201. Install()
  202. } else if len(os.Args) >= 2 && os.Args[1] == "version" {
  203. CheckUpdate()
  204. os.Exit(0)
  205. }
  206. }
  207. // 注册模板函数
  208. func RegisterFunction() {
  209. err := web.AddFuncMap("config", models.GetOptionValue)
  210. if err != nil {
  211. logs.Error("注册函数 config 出错 ->", err)
  212. os.Exit(-1)
  213. }
  214. err = web.AddFuncMap("cdn", func(p string) string {
  215. cdn := web.AppConfig.DefaultString("cdn", "")
  216. if strings.HasPrefix(p, "http://") || strings.HasPrefix(p, "https://") {
  217. return p
  218. }
  219. //如果没有设置cdn,则使用baseURL拼接
  220. if cdn == "" {
  221. baseUrl := web.AppConfig.DefaultString("baseurl", "")
  222. if strings.HasPrefix(p, "/") && strings.HasSuffix(baseUrl, "/") {
  223. return baseUrl + p[1:]
  224. }
  225. if !strings.HasPrefix(p, "/") && !strings.HasSuffix(baseUrl, "/") {
  226. return baseUrl + "/" + p
  227. }
  228. return baseUrl + p
  229. }
  230. if strings.HasPrefix(p, "/") && strings.HasSuffix(cdn, "/") {
  231. return cdn + string(p[1:])
  232. }
  233. if !strings.HasPrefix(p, "/") && !strings.HasSuffix(cdn, "/") {
  234. return cdn + "/" + p
  235. }
  236. return cdn + p
  237. })
  238. if err != nil {
  239. logs.Error("注册函数 cdn 出错 ->", err)
  240. os.Exit(-1)
  241. }
  242. err = web.AddFuncMap("cdnjs", conf.URLForWithCdnJs)
  243. if err != nil {
  244. logs.Error("注册函数 cdnjs 出错 ->", err)
  245. os.Exit(-1)
  246. }
  247. err = web.AddFuncMap("cdncss", conf.URLForWithCdnCss)
  248. if err != nil {
  249. logs.Error("注册函数 cdncss 出错 ->", err)
  250. os.Exit(-1)
  251. }
  252. err = web.AddFuncMap("cdnimg", conf.URLForWithCdnImage)
  253. if err != nil {
  254. logs.Error("注册函数 cdnimg 出错 ->", err)
  255. os.Exit(-1)
  256. }
  257. //重写url生成,支持配置域名以及域名前缀
  258. err = web.AddFuncMap("urlfor", conf.URLFor)
  259. if err != nil {
  260. logs.Error("注册函数 urlfor 出错 ->", err)
  261. os.Exit(-1)
  262. }
  263. //读取配置值(未作任何转换)
  264. err = web.AddFuncMap("conf", conf.CONF)
  265. if err != nil {
  266. logs.Error("注册函数 conf 出错 ->", err)
  267. os.Exit(-1)
  268. }
  269. err = web.AddFuncMap("date_format", func(t time.Time, format string) string {
  270. return t.Local().Format(format)
  271. })
  272. if err != nil {
  273. logs.Error("注册函数 date_format 出错 ->", err)
  274. os.Exit(-1)
  275. }
  276. err = web.AddFuncMap("i18n", i18n.Tr)
  277. if err != nil {
  278. logs.Error("注册函数 i18n 出错 ->", err)
  279. os.Exit(-1)
  280. }
  281. langs := strings.Split("en-us|zh-cn", "|")
  282. for _, lang := range langs {
  283. if err := i18n.SetMessage(lang, "conf/lang/"+lang+".ini"); err != nil {
  284. logs.Error("Fail to set message file: " + err.Error())
  285. return
  286. }
  287. }
  288. }
  289. // 解析命令
  290. func ResolveCommand(args []string) {
  291. flagSet := flag.NewFlagSet("MinDoc command: ", flag.ExitOnError)
  292. flagSet.StringVar(&conf.ConfigurationFile, "config", "", "MinDoc configuration file.")
  293. flagSet.StringVar(&conf.WorkingDirectory, "dir", "", "MinDoc working directory.")
  294. flagSet.StringVar(&conf.LogFile, "log", "", "MinDoc log file path.")
  295. if err := flagSet.Parse(args); err != nil {
  296. log.Fatal("解析命令失败 ->", err)
  297. }
  298. if conf.WorkingDirectory == "" {
  299. if p, err := filepath.Abs(os.Args[0]); err == nil {
  300. conf.WorkingDirectory = filepath.Dir(p)
  301. }
  302. }
  303. if conf.ConfigurationFile == "" {
  304. conf.ConfigurationFile = conf.WorkingDir("conf", "app.conf")
  305. config := conf.WorkingDir("conf", "app.conf.example")
  306. if !filetil.FileExists(conf.ConfigurationFile) && filetil.FileExists(config) {
  307. _ = filetil.CopyFile(conf.ConfigurationFile, config)
  308. }
  309. }
  310. if err := gocaptcha.ReadFonts(conf.WorkingDir("static", "fonts"), ".ttf"); err != nil {
  311. log.Fatal("读取字体文件时出错 -> ", err)
  312. }
  313. if err := web.LoadAppConfig("ini", conf.ConfigurationFile); err != nil {
  314. log.Fatal("An error occurred:", err)
  315. }
  316. if conf.LogFile == "" {
  317. logPath, err := filepath.Abs(web.AppConfig.DefaultString("log_path", conf.WorkingDir("runtime", "logs")))
  318. if err == nil {
  319. conf.LogFile = logPath
  320. } else {
  321. conf.LogFile = conf.WorkingDir("runtime", "logs")
  322. }
  323. }
  324. conf.AutoLoadDelay = web.AppConfig.DefaultInt("config_auto_delay", 0)
  325. uploads := conf.WorkingDir("uploads")
  326. _ = os.MkdirAll(uploads, 0666)
  327. web.BConfig.WebConfig.StaticDir["/static"] = filepath.Join(conf.WorkingDirectory, "static")
  328. web.BConfig.WebConfig.StaticDir["/uploads"] = uploads
  329. web.BConfig.WebConfig.ViewsPath = conf.WorkingDir("views")
  330. web.BConfig.WebConfig.Session.SessionCookieSameSite = http.SameSiteDefaultMode
  331. var upload_file_size = conf.GetUploadFileSize()
  332. if upload_file_size > web.BConfig.MaxUploadSize {
  333. web.BConfig.MaxUploadSize = upload_file_size
  334. }
  335. fonts := conf.WorkingDir("static", "fonts")
  336. if !filetil.FileExists(fonts) {
  337. log.Fatal("Font path not exist.")
  338. }
  339. if err := gocaptcha.ReadFonts(filepath.Join(conf.WorkingDirectory, "static", "fonts"), ".ttf"); err != nil {
  340. log.Fatal("读取字体失败 ->", err)
  341. }
  342. RegisterDataBase()
  343. RegisterCache()
  344. RegisterModel()
  345. RegisterLogger(conf.LogFile)
  346. ModifyPassword()
  347. }
  348. // 注册缓存管道
  349. func RegisterCache() {
  350. isOpenCache := web.AppConfig.DefaultBool("cache", false)
  351. if !isOpenCache {
  352. cache.Init(&cache.NullCache{})
  353. return
  354. }
  355. logs.Info("正常初始化缓存配置.")
  356. cacheProvider, _ := web.AppConfig.String("cache_provider")
  357. if cacheProvider == "file" {
  358. cacheFilePath := web.AppConfig.DefaultString("cache_file_path", "./runtime/cache/")
  359. if strings.HasPrefix(cacheFilePath, "./") {
  360. cacheFilePath = filepath.Join(conf.WorkingDirectory, string(cacheFilePath[1:]))
  361. }
  362. fileCache := beegoCache.NewFileCache()
  363. fileConfig := make(map[string]string, 0)
  364. fileConfig["CachePath"] = cacheFilePath
  365. fileConfig["DirectoryLevel"] = web.AppConfig.DefaultString("cache_file_dir_level", "2")
  366. fileConfig["EmbedExpiry"] = web.AppConfig.DefaultString("cache_file_expiry", "120")
  367. fileConfig["FileSuffix"] = web.AppConfig.DefaultString("cache_file_suffix", ".bin")
  368. bc, err := json.Marshal(&fileConfig)
  369. if err != nil {
  370. logs.Error("初始化file缓存失败:", err)
  371. os.Exit(1)
  372. }
  373. _ = fileCache.StartAndGC(string(bc))
  374. cache.Init(fileCache)
  375. } else if cacheProvider == "memory" {
  376. cacheInterval := web.AppConfig.DefaultInt("cache_memory_interval", 60)
  377. memory := beegoCache.NewMemoryCache()
  378. beegoCache.DefaultEvery = cacheInterval
  379. cache.Init(memory)
  380. } else if cacheProvider == "redis" {
  381. //设置Redis前缀
  382. if key := web.AppConfig.DefaultString("cache_redis_prefix", ""); key != "" {
  383. redis.DefaultKey = key
  384. }
  385. var redisConfig struct {
  386. Conn string `json:"conn"`
  387. Password string `json:"password"`
  388. DbNum string `json:"dbNum"`
  389. }
  390. redisConfig.DbNum = "0"
  391. redisConfig.Conn = web.AppConfig.DefaultString("cache_redis_host", "")
  392. if pwd := web.AppConfig.DefaultString("cache_redis_password", ""); pwd != "" {
  393. redisConfig.Password = pwd
  394. }
  395. if dbNum := web.AppConfig.DefaultInt("cache_redis_db", 0); dbNum > 0 {
  396. redisConfig.DbNum = strconv.Itoa(dbNum)
  397. }
  398. bc, err := json.Marshal(&redisConfig)
  399. if err != nil {
  400. logs.Error("初始化Redis缓存失败:", err)
  401. os.Exit(1)
  402. }
  403. redisCache, err := beegoCache.NewCache("redis", string(bc))
  404. if err != nil {
  405. logs.Error("初始化Redis缓存失败:", err)
  406. os.Exit(1)
  407. }
  408. cache.Init(redisCache)
  409. } else if cacheProvider == "memcache" {
  410. var memcacheConfig struct {
  411. Conn string `json:"conn"`
  412. }
  413. memcacheConfig.Conn = web.AppConfig.DefaultString("cache_memcache_host", "")
  414. bc, err := json.Marshal(&memcacheConfig)
  415. if err != nil {
  416. logs.Error("初始化 Memcache 缓存失败 ->", err)
  417. os.Exit(1)
  418. }
  419. memcache, err := beegoCache.NewCache("memcache", string(bc))
  420. if err != nil {
  421. logs.Error("初始化 Memcache 缓存失败 ->", err)
  422. os.Exit(1)
  423. }
  424. cache.Init(memcache)
  425. } else {
  426. cache.Init(&cache.NullCache{})
  427. logs.Warn("不支持的缓存管道,缓存将禁用 ->", cacheProvider)
  428. return
  429. }
  430. logs.Info("缓存初始化完成.")
  431. }
  432. // 自动加载配置文件.修改了监听端口号和数据库配置无法自动生效.
  433. func RegisterAutoLoadConfig() {
  434. if conf.AutoLoadDelay > 0 {
  435. watcher, err := fsnotify.NewWatcher()
  436. if err != nil {
  437. logs.Error("创建配置文件监控器失败 ->", err)
  438. }
  439. go func() {
  440. for {
  441. select {
  442. case ev := <-watcher.Event:
  443. //如果是修改了配置文件
  444. if ev.IsModify() {
  445. if err := web.LoadAppConfig("ini", conf.ConfigurationFile); err != nil {
  446. logs.Error("An error occurred ->", err)
  447. continue
  448. }
  449. RegisterCache()
  450. RegisterLogger("")
  451. logs.Info("配置文件已加载 ->", conf.ConfigurationFile)
  452. } else if ev.IsRename() {
  453. _ = watcher.WatchFlags(conf.ConfigurationFile, fsnotify.FSN_MODIFY|fsnotify.FSN_RENAME)
  454. }
  455. logs.Info(ev.String())
  456. case err := <-watcher.Error:
  457. logs.Error("配置文件监控器错误 ->", err)
  458. }
  459. }
  460. }()
  461. err = watcher.WatchFlags(conf.ConfigurationFile, fsnotify.FSN_MODIFY|fsnotify.FSN_RENAME)
  462. if err != nil {
  463. logs.Error("监控配置文件失败 ->", err)
  464. }
  465. }
  466. }
  467. // 注册错误处理方法.
  468. func RegisterError() {
  469. web.ErrorHandler("404", func(writer http.ResponseWriter, request *http.Request) {
  470. var buf bytes.Buffer
  471. data := make(map[string]interface{})
  472. data["ErrorCode"] = 404
  473. data["ErrorMessage"] = "页面未找到或已删除"
  474. if err := web.ExecuteViewPathTemplate(&buf, "errors/error.tpl", web.BConfig.WebConfig.ViewsPath, data); err == nil {
  475. _, _ = fmt.Fprint(writer, buf.String())
  476. } else {
  477. _, _ = fmt.Fprint(writer, data["ErrorMessage"])
  478. }
  479. })
  480. web.ErrorHandler("401", func(writer http.ResponseWriter, request *http.Request) {
  481. var buf bytes.Buffer
  482. data := make(map[string]interface{})
  483. data["ErrorCode"] = 401
  484. data["ErrorMessage"] = "请与 Web 服务器的管理员联系,以确认您是否具有访问所请求资源的权限。"
  485. if err := web.ExecuteViewPathTemplate(&buf, "errors/error.tpl", web.BConfig.WebConfig.ViewsPath, data); err == nil {
  486. _, _ = fmt.Fprint(writer, buf.String())
  487. } else {
  488. _, _ = fmt.Fprint(writer, data["ErrorMessage"])
  489. }
  490. })
  491. }
  492. func init() {
  493. if configPath, err := filepath.Abs(conf.ConfigurationFile); err == nil {
  494. conf.ConfigurationFile = configPath
  495. }
  496. if err := gocaptcha.ReadFonts(conf.WorkingDir("static", "fonts"), ".ttf"); err != nil {
  497. log.Fatal("读取字体文件失败 ->", err)
  498. }
  499. gob.Register(models.Member{})
  500. if p, err := filepath.Abs(os.Args[0]); err == nil {
  501. conf.WorkingDirectory = filepath.Dir(p)
  502. }
  503. }