command.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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. }
  126. // RegisterLogger 注册日志
  127. func RegisterLogger(log string) {
  128. logs.SetLogFuncCall(true)
  129. _ = logs.SetLogger("console")
  130. logs.EnableFuncCallDepth(true)
  131. if web.AppConfig.DefaultBool("log_is_async", true) {
  132. logs.Async(1e3)
  133. }
  134. if log == "" {
  135. logPath, err := filepath.Abs(web.AppConfig.DefaultString("log_path", conf.WorkingDir("runtime", "logs")))
  136. if err == nil {
  137. log = logPath
  138. } else {
  139. log = conf.WorkingDir("runtime", "logs")
  140. }
  141. }
  142. logPath := filepath.Join(log, "log.log")
  143. if _, err := os.Stat(log); os.IsNotExist(err) {
  144. _ = os.MkdirAll(log, 0755)
  145. }
  146. config := make(map[string]interface{}, 1)
  147. config["filename"] = logPath
  148. config["perm"] = "0755"
  149. config["rotate"] = true
  150. if maxLines := web.AppConfig.DefaultInt("log_maxlines", 1000000); maxLines > 0 {
  151. config["maxLines"] = maxLines
  152. }
  153. if maxSize := web.AppConfig.DefaultInt("log_maxsize", 1<<28); maxSize > 0 {
  154. config["maxsize"] = maxSize
  155. }
  156. if !web.AppConfig.DefaultBool("log_daily", true) {
  157. config["daily"] = false
  158. }
  159. if maxDays := web.AppConfig.DefaultInt("log_maxdays", 7); maxDays > 0 {
  160. config["maxdays"] = maxDays
  161. }
  162. if level := web.AppConfig.DefaultString("log_level", "Trace"); level != "" {
  163. switch level {
  164. case "Emergency":
  165. config["level"] = logs.LevelEmergency
  166. case "Alert":
  167. config["level"] = logs.LevelAlert
  168. case "Critical":
  169. config["level"] = logs.LevelCritical
  170. case "Error":
  171. config["level"] = logs.LevelError
  172. case "Warning":
  173. config["level"] = logs.LevelWarning
  174. case "Notice":
  175. config["level"] = logs.LevelNotice
  176. case "Informational":
  177. config["level"] = logs.LevelInformational
  178. case "Debug":
  179. config["level"] = logs.LevelDebug
  180. }
  181. }
  182. b, err := json.Marshal(config)
  183. if err != nil {
  184. logs.Error("初始化文件日志时出错 ->", err)
  185. _ = logs.SetLogger("file", `{"filename":"`+logPath+`"}`)
  186. } else {
  187. _ = logs.SetLogger(logs.AdapterFile, string(b))
  188. }
  189. logs.SetLogFuncCall(true)
  190. }
  191. // RunCommand 注册orm命令行工具
  192. func RegisterCommand() {
  193. if len(os.Args) >= 2 && os.Args[1] == "install" {
  194. ResolveCommand(os.Args[2:])
  195. Install()
  196. } else if len(os.Args) >= 2 && os.Args[1] == "version" {
  197. CheckUpdate()
  198. os.Exit(0)
  199. }
  200. }
  201. // 注册模板函数
  202. func RegisterFunction() {
  203. err := web.AddFuncMap("config", models.GetOptionValue)
  204. if err != nil {
  205. logs.Error("注册函数 config 出错 ->", err)
  206. os.Exit(-1)
  207. }
  208. err = web.AddFuncMap("cdn", func(p string) string {
  209. cdn := web.AppConfig.DefaultString("cdn", "")
  210. if strings.HasPrefix(p, "http://") || strings.HasPrefix(p, "https://") {
  211. return p
  212. }
  213. //如果没有设置cdn,则使用baseURL拼接
  214. if cdn == "" {
  215. baseUrl := web.AppConfig.DefaultString("baseurl", "")
  216. if strings.HasPrefix(p, "/") && strings.HasSuffix(baseUrl, "/") {
  217. return baseUrl + p[1:]
  218. }
  219. if !strings.HasPrefix(p, "/") && !strings.HasSuffix(baseUrl, "/") {
  220. return baseUrl + "/" + p
  221. }
  222. return baseUrl + p
  223. }
  224. if strings.HasPrefix(p, "/") && strings.HasSuffix(cdn, "/") {
  225. return cdn + string(p[1:])
  226. }
  227. if !strings.HasPrefix(p, "/") && !strings.HasSuffix(cdn, "/") {
  228. return cdn + "/" + p
  229. }
  230. return cdn + p
  231. })
  232. if err != nil {
  233. logs.Error("注册函数 cdn 出错 ->", err)
  234. os.Exit(-1)
  235. }
  236. err = web.AddFuncMap("cdnjs", conf.URLForWithCdnJs)
  237. if err != nil {
  238. logs.Error("注册函数 cdnjs 出错 ->", err)
  239. os.Exit(-1)
  240. }
  241. err = web.AddFuncMap("cdncss", conf.URLForWithCdnCss)
  242. if err != nil {
  243. logs.Error("注册函数 cdncss 出错 ->", err)
  244. os.Exit(-1)
  245. }
  246. err = web.AddFuncMap("cdnimg", conf.URLForWithCdnImage)
  247. if err != nil {
  248. logs.Error("注册函数 cdnimg 出错 ->", err)
  249. os.Exit(-1)
  250. }
  251. //重写url生成,支持配置域名以及域名前缀
  252. err = web.AddFuncMap("urlfor", conf.URLFor)
  253. if err != nil {
  254. logs.Error("注册函数 urlfor 出错 ->", err)
  255. os.Exit(-1)
  256. }
  257. //读取配置值(未作任何转换)
  258. err = web.AddFuncMap("conf", conf.CONF)
  259. if err != nil {
  260. logs.Error("注册函数 conf 出错 ->", err)
  261. os.Exit(-1)
  262. }
  263. err = web.AddFuncMap("date_format", func(t time.Time, format string) string {
  264. return t.Local().Format(format)
  265. })
  266. if err != nil {
  267. logs.Error("注册函数 date_format 出错 ->", err)
  268. os.Exit(-1)
  269. }
  270. err = web.AddFuncMap("i18n", i18n.Tr)
  271. if err != nil {
  272. logs.Error("注册函数 i18n 出错 ->", err)
  273. os.Exit(-1)
  274. }
  275. langs := strings.Split("en-us|zh-cn", "|")
  276. for _, lang := range langs {
  277. if err := i18n.SetMessage(lang, "conf/lang/"+lang+".ini"); err != nil {
  278. logs.Error("Fail to set message file: " + err.Error())
  279. return
  280. }
  281. }
  282. }
  283. // 解析命令
  284. func ResolveCommand(args []string) {
  285. flagSet := flag.NewFlagSet("MinDoc command: ", flag.ExitOnError)
  286. flagSet.StringVar(&conf.ConfigurationFile, "config", "", "MinDoc configuration file.")
  287. flagSet.StringVar(&conf.WorkingDirectory, "dir", "", "MinDoc working directory.")
  288. flagSet.StringVar(&conf.LogFile, "log", "", "MinDoc log file path.")
  289. if err := flagSet.Parse(args); err != nil {
  290. log.Fatal("解析命令失败 ->", err)
  291. }
  292. if conf.WorkingDirectory == "" {
  293. if p, err := filepath.Abs(os.Args[0]); err == nil {
  294. conf.WorkingDirectory = filepath.Dir(p)
  295. }
  296. }
  297. if conf.ConfigurationFile == "" {
  298. conf.ConfigurationFile = conf.WorkingDir("conf", "app.conf")
  299. config := conf.WorkingDir("conf", "app.conf.example")
  300. if !filetil.FileExists(conf.ConfigurationFile) && filetil.FileExists(config) {
  301. _ = filetil.CopyFile(conf.ConfigurationFile, config)
  302. }
  303. }
  304. if err := gocaptcha.ReadFonts(conf.WorkingDir("static", "fonts"), ".ttf"); err != nil {
  305. log.Fatal("读取字体文件时出错 -> ", err)
  306. }
  307. if err := web.LoadAppConfig("ini", conf.ConfigurationFile); err != nil {
  308. log.Fatal("An error occurred:", err)
  309. }
  310. if conf.LogFile == "" {
  311. logPath, err := filepath.Abs(web.AppConfig.DefaultString("log_path", conf.WorkingDir("runtime", "logs")))
  312. if err == nil {
  313. conf.LogFile = logPath
  314. } else {
  315. conf.LogFile = conf.WorkingDir("runtime", "logs")
  316. }
  317. }
  318. conf.AutoLoadDelay = web.AppConfig.DefaultInt("config_auto_delay", 0)
  319. uploads := conf.WorkingDir("uploads")
  320. _ = os.MkdirAll(uploads, 0666)
  321. web.BConfig.WebConfig.StaticDir["/static"] = filepath.Join(conf.WorkingDirectory, "static")
  322. web.BConfig.WebConfig.StaticDir["/uploads"] = uploads
  323. web.BConfig.WebConfig.ViewsPath = conf.WorkingDir("views")
  324. web.BConfig.WebConfig.Session.SessionCookieSameSite = http.SameSiteDefaultMode
  325. var upload_file_size = conf.GetUploadFileSize()
  326. if upload_file_size > web.BConfig.MaxUploadSize {
  327. web.BConfig.MaxUploadSize = upload_file_size
  328. }
  329. fonts := conf.WorkingDir("static", "fonts")
  330. if !filetil.FileExists(fonts) {
  331. log.Fatal("Font path not exist.")
  332. }
  333. if err := gocaptcha.ReadFonts(filepath.Join(conf.WorkingDirectory, "static", "fonts"), ".ttf"); err != nil {
  334. log.Fatal("读取字体失败 ->", err)
  335. }
  336. RegisterDataBase()
  337. RegisterCache()
  338. RegisterModel()
  339. RegisterLogger(conf.LogFile)
  340. ModifyPassword()
  341. }
  342. // 注册缓存管道
  343. func RegisterCache() {
  344. isOpenCache := web.AppConfig.DefaultBool("cache", false)
  345. if !isOpenCache {
  346. cache.Init(&cache.NullCache{})
  347. return
  348. }
  349. logs.Info("正常初始化缓存配置.")
  350. cacheProvider, _ := web.AppConfig.String("cache_provider")
  351. if cacheProvider == "file" {
  352. cacheFilePath := web.AppConfig.DefaultString("cache_file_path", "./runtime/cache/")
  353. if strings.HasPrefix(cacheFilePath, "./") {
  354. cacheFilePath = filepath.Join(conf.WorkingDirectory, string(cacheFilePath[1:]))
  355. }
  356. fileCache := beegoCache.NewFileCache()
  357. fileConfig := make(map[string]string, 0)
  358. fileConfig["CachePath"] = cacheFilePath
  359. fileConfig["DirectoryLevel"] = web.AppConfig.DefaultString("cache_file_dir_level", "2")
  360. fileConfig["EmbedExpiry"] = web.AppConfig.DefaultString("cache_file_expiry", "120")
  361. fileConfig["FileSuffix"] = web.AppConfig.DefaultString("cache_file_suffix", ".bin")
  362. bc, err := json.Marshal(&fileConfig)
  363. if err != nil {
  364. logs.Error("初始化file缓存失败:", err)
  365. os.Exit(1)
  366. }
  367. _ = fileCache.StartAndGC(string(bc))
  368. cache.Init(fileCache)
  369. } else if cacheProvider == "memory" {
  370. cacheInterval := web.AppConfig.DefaultInt("cache_memory_interval", 60)
  371. memory := beegoCache.NewMemoryCache()
  372. beegoCache.DefaultEvery = cacheInterval
  373. cache.Init(memory)
  374. } else if cacheProvider == "redis" {
  375. //设置Redis前缀
  376. if key := web.AppConfig.DefaultString("cache_redis_prefix", ""); key != "" {
  377. redis.DefaultKey = key
  378. }
  379. var redisConfig struct {
  380. Conn string `json:"conn"`
  381. Password string `json:"password"`
  382. DbNum string `json:"dbNum"`
  383. }
  384. redisConfig.DbNum = "0"
  385. redisConfig.Conn = web.AppConfig.DefaultString("cache_redis_host", "")
  386. if pwd := web.AppConfig.DefaultString("cache_redis_password", ""); pwd != "" {
  387. redisConfig.Password = pwd
  388. }
  389. if dbNum := web.AppConfig.DefaultInt("cache_redis_db", 0); dbNum > 0 {
  390. redisConfig.DbNum = strconv.Itoa(dbNum)
  391. }
  392. bc, err := json.Marshal(&redisConfig)
  393. if err != nil {
  394. logs.Error("初始化Redis缓存失败:", err)
  395. os.Exit(1)
  396. }
  397. redisCache, err := beegoCache.NewCache("redis", string(bc))
  398. if err != nil {
  399. logs.Error("初始化Redis缓存失败:", err)
  400. os.Exit(1)
  401. }
  402. cache.Init(redisCache)
  403. } else if cacheProvider == "memcache" {
  404. var memcacheConfig struct {
  405. Conn string `json:"conn"`
  406. }
  407. memcacheConfig.Conn = web.AppConfig.DefaultString("cache_memcache_host", "")
  408. bc, err := json.Marshal(&memcacheConfig)
  409. if err != nil {
  410. logs.Error("初始化 Memcache 缓存失败 ->", err)
  411. os.Exit(1)
  412. }
  413. memcache, err := beegoCache.NewCache("memcache", string(bc))
  414. if err != nil {
  415. logs.Error("初始化 Memcache 缓存失败 ->", err)
  416. os.Exit(1)
  417. }
  418. cache.Init(memcache)
  419. } else {
  420. cache.Init(&cache.NullCache{})
  421. logs.Warn("不支持的缓存管道,缓存将禁用 ->", cacheProvider)
  422. return
  423. }
  424. logs.Info("缓存初始化完成.")
  425. }
  426. // 自动加载配置文件.修改了监听端口号和数据库配置无法自动生效.
  427. func RegisterAutoLoadConfig() {
  428. if conf.AutoLoadDelay > 0 {
  429. watcher, err := fsnotify.NewWatcher()
  430. if err != nil {
  431. logs.Error("创建配置文件监控器失败 ->", err)
  432. }
  433. go func() {
  434. for {
  435. select {
  436. case ev := <-watcher.Event:
  437. //如果是修改了配置文件
  438. if ev.IsModify() {
  439. if err := web.LoadAppConfig("ini", conf.ConfigurationFile); err != nil {
  440. logs.Error("An error occurred ->", err)
  441. continue
  442. }
  443. RegisterCache()
  444. RegisterLogger("")
  445. logs.Info("配置文件已加载 ->", conf.ConfigurationFile)
  446. } else if ev.IsRename() {
  447. _ = watcher.WatchFlags(conf.ConfigurationFile, fsnotify.FSN_MODIFY|fsnotify.FSN_RENAME)
  448. }
  449. logs.Info(ev.String())
  450. case err := <-watcher.Error:
  451. logs.Error("配置文件监控器错误 ->", err)
  452. }
  453. }
  454. }()
  455. err = watcher.WatchFlags(conf.ConfigurationFile, fsnotify.FSN_MODIFY|fsnotify.FSN_RENAME)
  456. if err != nil {
  457. logs.Error("监控配置文件失败 ->", err)
  458. }
  459. }
  460. }
  461. // 注册错误处理方法.
  462. func RegisterError() {
  463. web.ErrorHandler("404", func(writer http.ResponseWriter, request *http.Request) {
  464. var buf bytes.Buffer
  465. data := make(map[string]interface{})
  466. data["ErrorCode"] = 404
  467. data["ErrorMessage"] = "页面未找到或已删除"
  468. if err := web.ExecuteViewPathTemplate(&buf, "errors/error.tpl", web.BConfig.WebConfig.ViewsPath, data); err == nil {
  469. _, _ = fmt.Fprint(writer, buf.String())
  470. } else {
  471. _, _ = fmt.Fprint(writer, data["ErrorMessage"])
  472. }
  473. })
  474. web.ErrorHandler("401", func(writer http.ResponseWriter, request *http.Request) {
  475. var buf bytes.Buffer
  476. data := make(map[string]interface{})
  477. data["ErrorCode"] = 401
  478. data["ErrorMessage"] = "请与 Web 服务器的管理员联系,以确认您是否具有访问所请求资源的权限。"
  479. if err := web.ExecuteViewPathTemplate(&buf, "errors/error.tpl", web.BConfig.WebConfig.ViewsPath, data); err == nil {
  480. _, _ = fmt.Fprint(writer, buf.String())
  481. } else {
  482. _, _ = fmt.Fprint(writer, data["ErrorMessage"])
  483. }
  484. })
  485. }
  486. func init() {
  487. if configPath, err := filepath.Abs(conf.ConfigurationFile); err == nil {
  488. conf.ConfigurationFile = configPath
  489. }
  490. if err := gocaptcha.ReadFonts(conf.WorkingDir("static", "fonts"), ".ttf"); err != nil {
  491. log.Fatal("读取字体文件失败 ->", err)
  492. }
  493. gob.Register(models.Member{})
  494. if p, err := filepath.Abs(os.Args[0]); err == nil {
  495. conf.WorkingDirectory = filepath.Dir(p)
  496. }
  497. }