inbound.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package controller
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. "strconv"
  6. "x-ui/database/model"
  7. "x-ui/logger"
  8. "x-ui/web/global"
  9. "x-ui/web/service"
  10. "x-ui/web/session"
  11. )
  12. type InboundController struct {
  13. inboundService service.InboundService
  14. xrayService service.XrayService
  15. }
  16. func NewInboundController(g *gin.RouterGroup) *InboundController {
  17. a := &InboundController{}
  18. a.initRouter(g)
  19. a.startTask()
  20. return a
  21. }
  22. func (a *InboundController) initRouter(g *gin.RouterGroup) {
  23. g = g.Group("/inbound")
  24. g.POST("/list", a.getInbounds)
  25. g.POST("/add", a.addInbound)
  26. g.POST("/del/:id", a.delInbound)
  27. g.POST("/update/:id", a.updateInbound)
  28. }
  29. func (a *InboundController) startTask() {
  30. webServer := global.GetWebServer()
  31. c := webServer.GetCron()
  32. c.AddFunc("@every 10s", func() {
  33. if a.xrayService.IsNeedRestartAndSetFalse() {
  34. err := a.xrayService.RestartXray(false)
  35. if err != nil {
  36. logger.Error("restart xray failed:", err)
  37. }
  38. }
  39. })
  40. }
  41. func (a *InboundController) getInbounds(c *gin.Context) {
  42. user := session.GetLoginUser(c)
  43. inbounds, err := a.inboundService.GetInbounds(user.Id)
  44. if err != nil {
  45. jsonMsg(c, "获取", err)
  46. return
  47. }
  48. jsonObj(c, inbounds, nil)
  49. }
  50. func (a *InboundController) addInbound(c *gin.Context) {
  51. inbound := &model.Inbound{}
  52. err := c.ShouldBind(inbound)
  53. if err != nil {
  54. jsonMsg(c, "添加", err)
  55. return
  56. }
  57. user := session.GetLoginUser(c)
  58. inbound.UserId = user.Id
  59. inbound.Enable = true
  60. inbound.Tag = fmt.Sprintf("inbound-%v", inbound.Port)
  61. err = a.inboundService.AddInbound(inbound)
  62. jsonMsg(c, "添加", err)
  63. if err == nil {
  64. a.xrayService.SetToNeedRestart()
  65. }
  66. }
  67. func (a *InboundController) delInbound(c *gin.Context) {
  68. id, err := strconv.Atoi(c.Param("id"))
  69. if err != nil {
  70. jsonMsg(c, "删除", err)
  71. return
  72. }
  73. err = a.inboundService.DelInbound(id)
  74. jsonMsg(c, "删除", err)
  75. if err == nil {
  76. a.xrayService.SetToNeedRestart()
  77. }
  78. }
  79. func (a *InboundController) updateInbound(c *gin.Context) {
  80. id, err := strconv.Atoi(c.Param("id"))
  81. if err != nil {
  82. jsonMsg(c, "修改", err)
  83. return
  84. }
  85. inbound := &model.Inbound{
  86. Id: id,
  87. }
  88. err = c.ShouldBind(inbound)
  89. if err != nil {
  90. jsonMsg(c, "修改", err)
  91. return
  92. }
  93. err = a.inboundService.UpdateInbound(inbound)
  94. jsonMsg(c, "修改", err)
  95. if err == nil {
  96. a.xrayService.SetToNeedRestart()
  97. }
  98. }