diff --git a/util/sys/sys_darwin.go b/util/sys/sys_darwin.go index d61a38a2..801bf692 100644 --- a/util/sys/sys_darwin.go +++ b/util/sys/sys_darwin.go @@ -1,3 +1,4 @@ +//go:build darwin // +build darwin package sys diff --git a/util/sys/sys_linux.go b/util/sys/sys_linux.go index 843d9b00..bcb7046e 100644 --- a/util/sys/sys_linux.go +++ b/util/sys/sys_linux.go @@ -1,3 +1,4 @@ +//go:build linux // +build linux package sys diff --git a/web/controller/api.go b/web/controller/api.go index 84ac9c20..23a51d67 100644 --- a/web/controller/api.go +++ b/web/controller/api.go @@ -3,6 +3,7 @@ package controller import ( "github.com/gin-gonic/gin" ) + type APIController struct { BaseController @@ -26,11 +27,9 @@ func (a *APIController) initRouter(g *gin.RouterGroup) { g.POST("/del/:id", a.delInbound) g.POST("/update/:id", a.updateInbound) - a.inboundController = NewInboundController(g) } - func (a *APIController) inbounds(c *gin.Context) { a.inboundController.getInbounds(c) } diff --git a/web/controller/base.go b/web/controller/base.go index 6ed2f0ef..a9659bd2 100644 --- a/web/controller/base.go +++ b/web/controller/base.go @@ -12,7 +12,7 @@ type BaseController struct { func (a *BaseController) checkLogin(c *gin.Context) { if !session.IsLogin(c) { if isAjax(c) { - pureJsonMsg(c, false, I18n(c , "pages.login.loginAgain")) + pureJsonMsg(c, false, I18n(c, "pages.login.loginAgain")) } else { c.Redirect(http.StatusTemporaryRedirect, c.GetString("base_path")) } @@ -22,12 +22,11 @@ func (a *BaseController) checkLogin(c *gin.Context) { } } +func I18n(c *gin.Context, name string) string { + anyfunc, _ := c.Get("I18n") + i18n, _ := anyfunc.(func(key string, params ...string) (string, error)) -func I18n(c *gin.Context , name string) string{ - anyfunc, _ := c.Get("I18n") - i18n, _ := anyfunc.(func(key string, params ...string) (string, error)) + message, _ := i18n(name) - message, _ := i18n(name) - - return message; + return message } diff --git a/web/controller/index.go b/web/controller/index.go index e0be6076..71a1a34a 100644 --- a/web/controller/index.go +++ b/web/controller/index.go @@ -46,7 +46,7 @@ func (a *IndexController) login(c *gin.Context) { var form LoginForm err := c.ShouldBind(&form) if err != nil { - pureJsonMsg(c, false, I18n(c , "pages.login.toasts.invalidFormData")) + pureJsonMsg(c, false, I18n(c, "pages.login.toasts.invalidFormData")) return } if form.Username == "" { @@ -54,7 +54,7 @@ func (a *IndexController) login(c *gin.Context) { return } if form.Password == "" { - pureJsonMsg(c, false, I18n(c , "pages.login.toasts.emptyPassword")) + pureJsonMsg(c, false, I18n(c, "pages.login.toasts.emptyPassword")) return } user := a.userService.CheckUser(form.Username, form.Password) @@ -62,7 +62,7 @@ func (a *IndexController) login(c *gin.Context) { if user == nil { job.NewStatsNotifyJob().UserLoginNotify(form.Username, getRemoteIp(c), timeStr, 0) logger.Infof("wrong username or password: \"%s\" \"%s\"", form.Username, form.Password) - pureJsonMsg(c, false, I18n(c , "pages.login.toasts.wrongUsernameOrPassword")) + pureJsonMsg(c, false, I18n(c, "pages.login.toasts.wrongUsernameOrPassword")) return } else { logger.Infof("%s login success,Ip Address:%s\n", form.Username, getRemoteIp(c)) @@ -71,7 +71,7 @@ func (a *IndexController) login(c *gin.Context) { err = session.SetLoginUser(c, user) logger.Info("user", user.Id, "login success") - jsonMsg(c, I18n(c , "pages.login.toasts.successLogin"), err) + jsonMsg(c, I18n(c, "pages.login.toasts.successLogin"), err) } func (a *IndexController) logout(c *gin.Context) { diff --git a/web/controller/server.go b/web/controller/server.go index d59b3400..2dd40a0a 100644 --- a/web/controller/server.go +++ b/web/controller/server.go @@ -68,7 +68,7 @@ func (a *ServerController) getXrayVersion(c *gin.Context) { versions, err := a.serverService.GetXrayVersions() if err != nil { - jsonMsg(c, I18n(c , "getVersion"), err) + jsonMsg(c, I18n(c, "getVersion"), err) return } @@ -81,5 +81,5 @@ func (a *ServerController) getXrayVersion(c *gin.Context) { func (a *ServerController) installXray(c *gin.Context) { version := c.Param("version") err := a.serverService.UpdateXray(version) - jsonMsg(c, I18n(c , "install") + " xray", err) + jsonMsg(c, I18n(c, "install")+" xray", err) } diff --git a/web/controller/setting.go b/web/controller/setting.go index f500c76d..922544fe 100644 --- a/web/controller/setting.go +++ b/web/controller/setting.go @@ -40,7 +40,7 @@ func (a *SettingController) initRouter(g *gin.RouterGroup) { func (a *SettingController) getAllSetting(c *gin.Context) { allSetting, err := a.settingService.GetAllSetting() if err != nil { - jsonMsg(c, I18n(c , "pages.setting.toasts.getSetting"), err) + jsonMsg(c, I18n(c, "pages.setting.toasts.getSetting"), err) return } jsonObj(c, allSetting, nil) @@ -50,27 +50,27 @@ func (a *SettingController) updateSetting(c *gin.Context) { allSetting := &entity.AllSetting{} err := c.ShouldBind(allSetting) if err != nil { - jsonMsg(c, I18n(c , "pages.setting.toasts.modifySetting"), err) + jsonMsg(c, I18n(c, "pages.setting.toasts.modifySetting"), err) return } err = a.settingService.UpdateAllSetting(allSetting) - jsonMsg(c, I18n(c , "pages.setting.toasts.modifySetting"), err) + jsonMsg(c, I18n(c, "pages.setting.toasts.modifySetting"), err) } func (a *SettingController) updateUser(c *gin.Context) { form := &updateUserForm{} err := c.ShouldBind(form) if err != nil { - jsonMsg(c, I18n(c , "pages.setting.toasts.modifySetting"), err) + jsonMsg(c, I18n(c, "pages.setting.toasts.modifySetting"), err) return } user := session.GetLoginUser(c) if user.Username != form.OldUsername || user.Password != form.OldPassword { - jsonMsg(c, I18n(c , "pages.setting.toasts.modifyUser"), errors.New(I18n(c , "pages.setting.toasts.originalUserPassIncorrect"))) + jsonMsg(c, I18n(c, "pages.setting.toasts.modifyUser"), errors.New(I18n(c, "pages.setting.toasts.originalUserPassIncorrect"))) return } if form.NewUsername == "" || form.NewPassword == "" { - jsonMsg(c,I18n(c , "pages.setting.toasts.modifyUser"), errors.New(I18n(c , "pages.setting.toasts.userPassMustBeNotEmpty"))) + jsonMsg(c, I18n(c, "pages.setting.toasts.modifyUser"), errors.New(I18n(c, "pages.setting.toasts.userPassMustBeNotEmpty"))) return } err = a.userService.UpdateUser(user.Id, form.NewUsername, form.NewPassword) @@ -79,10 +79,10 @@ func (a *SettingController) updateUser(c *gin.Context) { user.Password = form.NewPassword session.SetLoginUser(c, user) } - jsonMsg(c, I18n(c , "pages.setting.toasts.modifyUser"), err) + jsonMsg(c, I18n(c, "pages.setting.toasts.modifyUser"), err) } func (a *SettingController) restartPanel(c *gin.Context) { err := a.panelService.RestartPanel(time.Second * 3) - jsonMsg(c, I18n(c , "pages.setting.restartPanel"), err) + jsonMsg(c, I18n(c, "pages.setting.restartPanel"), err) } diff --git a/web/controller/util.go b/web/controller/util.go index 2bd2fa55..20ae1ea4 100644 --- a/web/controller/util.go +++ b/web/controller/util.go @@ -46,12 +46,12 @@ func jsonMsgObj(c *gin.Context, msg string, obj interface{}, err error) { if err == nil { m.Success = true if msg != "" { - m.Msg = msg + I18n(c , "success") + m.Msg = msg + I18n(c, "success") } } else { m.Success = false - m.Msg = msg + I18n(c , "fail") + ": " + err.Error() - logger.Warning(msg + I18n(c , "fail") + ": ", err) + m.Msg = msg + I18n(c, "fail") + ": " + err.Error() + logger.Warning(msg+I18n(c, "fail")+": ", err) } c.JSON(http.StatusOK, m) } diff --git a/web/job/stats_notify_job.go b/web/job/stats_notify_job.go index 5209e204..92963127 100644 --- a/web/job/stats_notify_job.go +++ b/web/job/stats_notify_job.go @@ -8,6 +8,7 @@ import ( "x-ui/logger" "x-ui/util/common" "x-ui/web/service" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" ) @@ -54,7 +55,7 @@ func (j *StatsNotifyJob) SendMsgToTgbot(msg string) { bot.Send(info) } -//Here run is a interface method of Job interface +// Here run is a interface method of Job interface func (j *StatsNotifyJob) Run() { if !j.xrayService.IsXrayRunning() { return @@ -94,14 +95,14 @@ func (j *StatsNotifyJob) Run() { } info += fmt.Sprintf("IP:%s\r\n \r\n", ip) - //get traffic + // get traffic inbouds, err := j.inboundService.GetAllInbounds() if err != nil { logger.Warning("StatsNotifyJob run failed:", err) return } - //NOTE:If there no any sessions here,need to notify here - //TODO:分节点推送,自动转化格式 + // NOTE:If there no any sessions here,need to notify here + // TODO:Sub-node push, automatic conversion format for _, inbound := range inbouds { info += fmt.Sprintf("Node name:%s\r\nPort:%d\r\nUpload↑:%s\r\nDownload↓:%s\r\nTotal:%s\r\n", inbound.Remark, inbound.Port, common.FormatTraffic(inbound.Up), common.FormatTraffic(inbound.Down), common.FormatTraffic((inbound.Up + inbound.Down))) if inbound.ExpiryTime == 0 { @@ -119,7 +120,7 @@ func (j *StatsNotifyJob) UserLoginNotify(username string, ip string, time string return } var msg string - //get hostname + // Get hostname name, err := os.Hostname() if err != nil { fmt.Println("get hostname error:", err) @@ -136,11 +137,10 @@ func (j *StatsNotifyJob) UserLoginNotify(username string, ip string, time string j.SendMsgToTgbot(msg) } - var numericKeyboard = tgbotapi.NewInlineKeyboardMarkup( - tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData("Get Usage", "get_usage"), - ), + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("Get Usage", "get_usage"), + ), ) func (j *StatsNotifyJob) OnReceive() *StatsNotifyJob { @@ -156,13 +156,13 @@ func (j *StatsNotifyJob) OnReceive() *StatsNotifyJob { } bot.Debug = false u := tgbotapi.NewUpdate(0) - u.Timeout = 10 + u.Timeout = 10 - updates := bot.GetUpdatesChan(u) + updates := bot.GetUpdatesChan(u) + + for update := range updates { + if update.Message == nil { - for update := range updates { - if update.Message == nil { - if update.CallbackQuery != nil { // Respond to the callback query, telling Telegram to show the user // a message with the data received. @@ -170,60 +170,60 @@ func (j *StatsNotifyJob) OnReceive() *StatsNotifyJob { if _, err := bot.Request(callback); err != nil { logger.Warning(err) } - + // And finally, send a message containing the data received. msg := tgbotapi.NewMessage(update.CallbackQuery.Message.Chat.ID, "") switch update.CallbackQuery.Data { - case "get_usage": - msg.Text = "for get your usage send command like this : \n /usage uuid | id \n example : /usage fc3239ed-8f3b-4151-ff51-b183d5182142" - msg.ParseMode = "HTML" - } + case "get_usage": + msg.Text = "for get your usage send command like this : \n /usage uuid | id \n example : /usage fc3239ed-8f3b-4151-ff51-b183d5182142" + msg.ParseMode = "HTML" + } if _, err := bot.Send(msg); err != nil { logger.Warning(err) } } - - continue - } - if !update.Message.IsCommand() { // ignore any non-command Messages - continue - } + continue + } - // Create a new MessageConfig. We don't have text yet, - // so we leave it empty. - msg := tgbotapi.NewMessage(update.Message.Chat.ID, "") + if !update.Message.IsCommand() { // ignore any non-command Messages + continue + } - // Extract the command from the Message. - switch update.Message.Command() { - case "help": - msg.Text = "What you need?" + // Create a new MessageConfig. We don't have text yet, + // so we leave it empty. + msg := tgbotapi.NewMessage(update.Message.Chat.ID, "") + + // Extract the command from the Message. + switch update.Message.Command() { + case "help": + msg.Text = "What you need?" msg.ReplyMarkup = numericKeyboard - case "start": - msg.Text = "Hi :) \n What you need?" + case "start": + msg.Text = "Hi :) \n What you need?" msg.ReplyMarkup = numericKeyboard - case "status": - msg.Text = "bot is ok." + case "status": + msg.Text = "bot is ok." - case "usage": - msg.Text = j.getClientUsage(update.Message.CommandArguments()) - default: - msg.Text = "I don't know that command, /help" + case "usage": + msg.Text = j.getClientUsage(update.Message.CommandArguments()) + default: + msg.Text = "I don't know that command, /help" msg.ReplyMarkup = numericKeyboard - } + } - if _, err := bot.Send(msg); err != nil { - logger.Warning(err) - } - } + if _, err := bot.Send(msg); err != nil { + logger.Warning(err) + } + } return j } func (j *StatsNotifyJob) getClientUsage(id string) string { - traffic , err := j.inboundService.GetClientTrafficById(id) + traffic, err := j.inboundService.GetClientTrafficById(id) if err != nil { logger.Warning(err) return "something wrong!" @@ -241,8 +241,8 @@ func (j *StatsNotifyJob) getClientUsage(id string) string { total = fmt.Sprintf("%s", common.FormatTraffic((traffic.Total))) } output := fmt.Sprintf("💡 Active: %t\r\n📧 Email: %s\r\n🔼 Upload↑: %s\r\n🔽 Download↓: %s\r\n🔄 Total: %s / %s\r\n📅 Expire in: %s\r\n", - traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)), - total, expiryTime) - + traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)), + total, expiryTime) + return output } diff --git a/web/job/xray_traffic_job.go b/web/job/xray_traffic_job.go index 97f85c24..3acdf44a 100644 --- a/web/job/xray_traffic_job.go +++ b/web/job/xray_traffic_job.go @@ -28,11 +28,10 @@ func (j *XrayTrafficJob) Run() { if err != nil { logger.Warning("add traffic failed:", err) } - + err = j.inboundService.AddClientTraffic(clientTraffics) if err != nil { logger.Warning("add client traffic failed:", err) } - } diff --git a/web/web.go b/web/web.go index aec9ebb3..5cc100c5 100644 --- a/web/web.go +++ b/web/web.go @@ -298,19 +298,19 @@ func (s *Server) startTask() { if err != nil { logger.Warning("start xray failed:", err) } - // 每 30 秒检查一次 xray 是否在运行 + // Check whether xray is running every 30 seconds s.cron.AddJob("@every 30s", job.NewCheckXrayRunningJob()) go func() { time.Sleep(time.Second * 5) - // 每 10 秒统计一次流量,首次启动延迟 5 秒,与重启 xray 的时间错开 + // Statistics every 10 seconds, start the delay for 5 seconds for the first time, and staggered with the time to restart xray s.cron.AddJob("@every 10s", job.NewXrayTrafficJob()) }() - // 每 30 秒检查一次 inbound 流量超出和到期的情况 + // Check the inbound traffic every 30 seconds that the traffic exceeds and expires s.cron.AddJob("@every 30s", job.NewCheckInboundJob()) - // 每一天提示一次流量情况,上海时间8点30 + // Make a traffic condition every day, 8:30 var entry cron.EntryID isTgbotenabled, err := s.settingService.GetTgbotenabled() if (err == nil) && (isTgbotenabled) { @@ -320,7 +320,7 @@ func (s *Server) startTask() { runtime = "@daily" } logger.Infof("Tg notify enabled,run at %s", runtime) - entry, err = s.cron.AddJob(runtime, job.NewStatsNotifyJob()) + _, err = s.cron.AddJob(runtime, job.NewStatsNotifyJob()) if err != nil { logger.Warning("Add NewStatsNotifyJob error", err) return @@ -333,7 +333,7 @@ func (s *Server) startTask() { } func (s *Server) Start() (err error) { - //这是一个匿名函数,没没有函数名 + //This is an anonymous function, no function name defer func() { if err != nil { s.Stop() diff --git a/xray/client_traffic.go b/xray/client_traffic.go index 4df6a502..d1302da4 100644 --- a/xray/client_traffic.go +++ b/xray/client_traffic.go @@ -1,12 +1,12 @@ package xray type ClientTraffic struct { - Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"` - InboundId int `json:"inboundId" form:"inboundId"` + Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"` + InboundId int `json:"inboundId" form:"inboundId"` Enable bool `json:"enable" form:"enable"` - Email string `json:"email" form:"email" gorm:"unique"` - Up int64 `json:"up" form:"up"` - Down int64 `json:"down" form:"down"` + Email string `json:"email" form:"email" gorm:"unique"` + Up int64 `json:"up" form:"up"` + Down int64 `json:"down" form:"down"` ExpiryTime int64 `json:"expiryTime" form:"expiryTime"` Total int64 `json:"total" form:"total"` }