command.go 16 KB

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