update.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package console
  2. import (
  3. _ "embed"
  4. "fmt"
  5. "mtp20access/global"
  6. "net/http"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "regexp"
  11. "runtime"
  12. "strings"
  13. "github.com/gin-gonic/gin"
  14. )
  15. //go:embed upmtpgo.sh
  16. var strShell string
  17. var IsUpdateing = false
  18. // MakeUpdateScript 生成脚本
  19. func MakeUpdateScript(c *gin.Context) {
  20. if IsUpdateing {
  21. c.String(http.StatusOK, "正在升级中...")
  22. return
  23. }
  24. if runtime.GOOS == "windows" {
  25. c.String(http.StatusOK, "windows不支持, 仅支持linux下执行")
  26. return
  27. }
  28. // logger.GetLogger().Debug("*********************auto update*******************************")
  29. IsUpdateing = true
  30. defer func() {
  31. IsUpdateing = false
  32. }()
  33. filename := c.DefaultQuery("filename", "")
  34. if createsh() {
  35. c.String(http.StatusOK, "正在执行升级, 升级会保留原有的config.yaml,且重启服务。注意:请勿刷新本页面。")
  36. rx := regexp.MustCompile(`mtp20_access_*\.zip`) // mtp20_access_20221009092417.zip
  37. names := rx.FindStringSubmatch(filename)
  38. // 正则表达式检查文件名是否符合规范
  39. if len(names) > 0 && names[0] == filename {
  40. fmt.Println("filename:", filename)
  41. cmd := exec.Command("sh", "./update.sh", filename)
  42. fmt.Println("cmd param:", cmd.Args)
  43. cmd.Run()
  44. } else {
  45. _ = exec.Command("sh", "./update.sh").Run()
  46. }
  47. } else {
  48. c.String(http.StatusBadRequest, "创建脚本失败, 可能是权限不足")
  49. }
  50. }
  51. // 生成update.sh文件
  52. func createsh() bool {
  53. global.M2A_LOG.Info("4444444444")
  54. dir := ""
  55. if str, err := filepath.Abs(filepath.Dir(os.Args[0])); err == nil {
  56. dir = strings.Replace(str, "\\", "/", -1)
  57. } else {
  58. return false
  59. }
  60. global.M2A_LOG.Info("555555555555")
  61. // 创建文件
  62. if f, err := os.OpenFile(dir+"/update.sh", os.O_RDWR|os.O_TRUNC|os.O_CREATE, 0666); err == nil {
  63. f.Write([]byte(strShell))
  64. f.Close()
  65. } else {
  66. return false
  67. }
  68. global.M2A_LOG.Info("66666666666")
  69. return true
  70. }