1
0

command.go 16 KB

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