Fix formats

This commit is contained in:
Alireza Ahmadi
2023-02-16 10:38:42 +01:00
parent 1700e85d06
commit 35de896e5e
12 changed files with 87 additions and 88 deletions

View File

@@ -1,3 +1,4 @@
//go:build darwin
// +build darwin // +build darwin
package sys package sys

View File

@@ -1,3 +1,4 @@
//go:build linux
// +build linux // +build linux
package sys package sys

View File

@@ -3,6 +3,7 @@ package controller
import ( import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
type APIController struct { type APIController struct {
BaseController BaseController
@@ -26,11 +27,9 @@ func (a *APIController) initRouter(g *gin.RouterGroup) {
g.POST("/del/:id", a.delInbound) g.POST("/del/:id", a.delInbound)
g.POST("/update/:id", a.updateInbound) g.POST("/update/:id", a.updateInbound)
a.inboundController = NewInboundController(g) a.inboundController = NewInboundController(g)
} }
func (a *APIController) inbounds(c *gin.Context) { func (a *APIController) inbounds(c *gin.Context) {
a.inboundController.getInbounds(c) a.inboundController.getInbounds(c)
} }

View File

@@ -12,7 +12,7 @@ type BaseController struct {
func (a *BaseController) checkLogin(c *gin.Context) { func (a *BaseController) checkLogin(c *gin.Context) {
if !session.IsLogin(c) { if !session.IsLogin(c) {
if isAjax(c) { if isAjax(c) {
pureJsonMsg(c, false, I18n(c , "pages.login.loginAgain")) pureJsonMsg(c, false, I18n(c, "pages.login.loginAgain"))
} else { } else {
c.Redirect(http.StatusTemporaryRedirect, c.GetString("base_path")) 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{ message, _ := i18n(name)
anyfunc, _ := c.Get("I18n")
i18n, _ := anyfunc.(func(key string, params ...string) (string, error))
message, _ := i18n(name) return message
return message;
} }

View File

@@ -46,7 +46,7 @@ func (a *IndexController) login(c *gin.Context) {
var form LoginForm var form LoginForm
err := c.ShouldBind(&form) err := c.ShouldBind(&form)
if err != nil { if err != nil {
pureJsonMsg(c, false, I18n(c , "pages.login.toasts.invalidFormData")) pureJsonMsg(c, false, I18n(c, "pages.login.toasts.invalidFormData"))
return return
} }
if form.Username == "" { if form.Username == "" {
@@ -54,7 +54,7 @@ func (a *IndexController) login(c *gin.Context) {
return return
} }
if form.Password == "" { if form.Password == "" {
pureJsonMsg(c, false, I18n(c , "pages.login.toasts.emptyPassword")) pureJsonMsg(c, false, I18n(c, "pages.login.toasts.emptyPassword"))
return return
} }
user := a.userService.CheckUser(form.Username, form.Password) user := a.userService.CheckUser(form.Username, form.Password)
@@ -62,7 +62,7 @@ func (a *IndexController) login(c *gin.Context) {
if user == nil { if user == nil {
job.NewStatsNotifyJob().UserLoginNotify(form.Username, getRemoteIp(c), timeStr, 0) job.NewStatsNotifyJob().UserLoginNotify(form.Username, getRemoteIp(c), timeStr, 0)
logger.Infof("wrong username or password: \"%s\" \"%s\"", form.Username, form.Password) 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 return
} else { } else {
logger.Infof("%s login success,Ip Address:%s\n", form.Username, getRemoteIp(c)) 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) err = session.SetLoginUser(c, user)
logger.Info("user", user.Id, "login success") 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) { func (a *IndexController) logout(c *gin.Context) {

View File

@@ -68,7 +68,7 @@ func (a *ServerController) getXrayVersion(c *gin.Context) {
versions, err := a.serverService.GetXrayVersions() versions, err := a.serverService.GetXrayVersions()
if err != nil { if err != nil {
jsonMsg(c, I18n(c , "getVersion"), err) jsonMsg(c, I18n(c, "getVersion"), err)
return return
} }
@@ -81,5 +81,5 @@ func (a *ServerController) getXrayVersion(c *gin.Context) {
func (a *ServerController) installXray(c *gin.Context) { func (a *ServerController) installXray(c *gin.Context) {
version := c.Param("version") version := c.Param("version")
err := a.serverService.UpdateXray(version) err := a.serverService.UpdateXray(version)
jsonMsg(c, I18n(c , "install") + " xray", err) jsonMsg(c, I18n(c, "install")+" xray", err)
} }

View File

@@ -40,7 +40,7 @@ func (a *SettingController) initRouter(g *gin.RouterGroup) {
func (a *SettingController) getAllSetting(c *gin.Context) { func (a *SettingController) getAllSetting(c *gin.Context) {
allSetting, err := a.settingService.GetAllSetting() allSetting, err := a.settingService.GetAllSetting()
if err != nil { if err != nil {
jsonMsg(c, I18n(c , "pages.setting.toasts.getSetting"), err) jsonMsg(c, I18n(c, "pages.setting.toasts.getSetting"), err)
return return
} }
jsonObj(c, allSetting, nil) jsonObj(c, allSetting, nil)
@@ -50,27 +50,27 @@ func (a *SettingController) updateSetting(c *gin.Context) {
allSetting := &entity.AllSetting{} allSetting := &entity.AllSetting{}
err := c.ShouldBind(allSetting) err := c.ShouldBind(allSetting)
if err != nil { if err != nil {
jsonMsg(c, I18n(c , "pages.setting.toasts.modifySetting"), err) jsonMsg(c, I18n(c, "pages.setting.toasts.modifySetting"), err)
return return
} }
err = a.settingService.UpdateAllSetting(allSetting) 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) { func (a *SettingController) updateUser(c *gin.Context) {
form := &updateUserForm{} form := &updateUserForm{}
err := c.ShouldBind(form) err := c.ShouldBind(form)
if err != nil { if err != nil {
jsonMsg(c, I18n(c , "pages.setting.toasts.modifySetting"), err) jsonMsg(c, I18n(c, "pages.setting.toasts.modifySetting"), err)
return return
} }
user := session.GetLoginUser(c) user := session.GetLoginUser(c)
if user.Username != form.OldUsername || user.Password != form.OldPassword { 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 return
} }
if form.NewUsername == "" || form.NewPassword == "" { 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 return
} }
err = a.userService.UpdateUser(user.Id, form.NewUsername, form.NewPassword) 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 user.Password = form.NewPassword
session.SetLoginUser(c, user) 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) { func (a *SettingController) restartPanel(c *gin.Context) {
err := a.panelService.RestartPanel(time.Second * 3) err := a.panelService.RestartPanel(time.Second * 3)
jsonMsg(c, I18n(c , "pages.setting.restartPanel"), err) jsonMsg(c, I18n(c, "pages.setting.restartPanel"), err)
} }

View File

@@ -46,12 +46,12 @@ func jsonMsgObj(c *gin.Context, msg string, obj interface{}, err error) {
if err == nil { if err == nil {
m.Success = true m.Success = true
if msg != "" { if msg != "" {
m.Msg = msg + I18n(c , "success") m.Msg = msg + I18n(c, "success")
} }
} else { } else {
m.Success = false m.Success = false
m.Msg = msg + I18n(c , "fail") + ": " + err.Error() m.Msg = msg + I18n(c, "fail") + ": " + err.Error()
logger.Warning(msg + I18n(c , "fail") + ": ", err) logger.Warning(msg+I18n(c, "fail")+": ", err)
} }
c.JSON(http.StatusOK, m) c.JSON(http.StatusOK, m)
} }

View File

@@ -8,6 +8,7 @@ import (
"x-ui/logger" "x-ui/logger"
"x-ui/util/common" "x-ui/util/common"
"x-ui/web/service" "x-ui/web/service"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
) )
@@ -54,7 +55,7 @@ func (j *StatsNotifyJob) SendMsgToTgbot(msg string) {
bot.Send(info) 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() { func (j *StatsNotifyJob) Run() {
if !j.xrayService.IsXrayRunning() { if !j.xrayService.IsXrayRunning() {
return return
@@ -94,14 +95,14 @@ func (j *StatsNotifyJob) Run() {
} }
info += fmt.Sprintf("IP:%s\r\n \r\n", ip) info += fmt.Sprintf("IP:%s\r\n \r\n", ip)
//get traffic // get traffic
inbouds, err := j.inboundService.GetAllInbounds() inbouds, err := j.inboundService.GetAllInbounds()
if err != nil { if err != nil {
logger.Warning("StatsNotifyJob run failed:", err) logger.Warning("StatsNotifyJob run failed:", err)
return return
} }
//NOTE:If there no any sessions here,need to notify here // NOTE:If there no any sessions here,need to notify here
//TODO:分节点推送,自动转化格式 // TODO:Sub-node push, automatic conversion format
for _, inbound := range inbouds { 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))) 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 { if inbound.ExpiryTime == 0 {
@@ -119,7 +120,7 @@ func (j *StatsNotifyJob) UserLoginNotify(username string, ip string, time string
return return
} }
var msg string var msg string
//get hostname // Get hostname
name, err := os.Hostname() name, err := os.Hostname()
if err != nil { if err != nil {
fmt.Println("get hostname error:", err) fmt.Println("get hostname error:", err)
@@ -136,11 +137,10 @@ func (j *StatsNotifyJob) UserLoginNotify(username string, ip string, time string
j.SendMsgToTgbot(msg) j.SendMsgToTgbot(msg)
} }
var numericKeyboard = tgbotapi.NewInlineKeyboardMarkup( var numericKeyboard = tgbotapi.NewInlineKeyboardMarkup(
tgbotapi.NewInlineKeyboardRow( tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData("Get Usage", "get_usage"), tgbotapi.NewInlineKeyboardButtonData("Get Usage", "get_usage"),
), ),
) )
func (j *StatsNotifyJob) OnReceive() *StatsNotifyJob { func (j *StatsNotifyJob) OnReceive() *StatsNotifyJob {
@@ -156,13 +156,13 @@ func (j *StatsNotifyJob) OnReceive() *StatsNotifyJob {
} }
bot.Debug = false bot.Debug = false
u := tgbotapi.NewUpdate(0) 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 { if update.CallbackQuery != nil {
// Respond to the callback query, telling Telegram to show the user // Respond to the callback query, telling Telegram to show the user
// a message with the data received. // a message with the data received.
@@ -170,60 +170,60 @@ func (j *StatsNotifyJob) OnReceive() *StatsNotifyJob {
if _, err := bot.Request(callback); err != nil { if _, err := bot.Request(callback); err != nil {
logger.Warning(err) logger.Warning(err)
} }
// And finally, send a message containing the data received. // And finally, send a message containing the data received.
msg := tgbotapi.NewMessage(update.CallbackQuery.Message.Chat.ID, "") msg := tgbotapi.NewMessage(update.CallbackQuery.Message.Chat.ID, "")
switch update.CallbackQuery.Data { switch update.CallbackQuery.Data {
case "get_usage": case "get_usage":
msg.Text = "for get your usage send command like this : \n <code>/usage uuid | id</code> \n example : <code>/usage fc3239ed-8f3b-4151-ff51-b183d5182142</code>" msg.Text = "for get your usage send command like this : \n <code>/usage uuid | id</code> \n example : <code>/usage fc3239ed-8f3b-4151-ff51-b183d5182142</code>"
msg.ParseMode = "HTML" msg.ParseMode = "HTML"
} }
if _, err := bot.Send(msg); err != nil { if _, err := bot.Send(msg); err != nil {
logger.Warning(err) 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, if !update.Message.IsCommand() { // ignore any non-command Messages
// so we leave it empty. continue
msg := tgbotapi.NewMessage(update.Message.Chat.ID, "") }
// Extract the command from the Message. // Create a new MessageConfig. We don't have text yet,
switch update.Message.Command() { // so we leave it empty.
case "help": msg := tgbotapi.NewMessage(update.Message.Chat.ID, "")
msg.Text = "What you need?"
// Extract the command from the Message.
switch update.Message.Command() {
case "help":
msg.Text = "What you need?"
msg.ReplyMarkup = numericKeyboard msg.ReplyMarkup = numericKeyboard
case "start": case "start":
msg.Text = "Hi :) \n What you need?" msg.Text = "Hi :) \n What you need?"
msg.ReplyMarkup = numericKeyboard msg.ReplyMarkup = numericKeyboard
case "status": case "status":
msg.Text = "bot is ok." msg.Text = "bot is ok."
case "usage": case "usage":
msg.Text = j.getClientUsage(update.Message.CommandArguments()) msg.Text = j.getClientUsage(update.Message.CommandArguments())
default: default:
msg.Text = "I don't know that command, /help" msg.Text = "I don't know that command, /help"
msg.ReplyMarkup = numericKeyboard msg.ReplyMarkup = numericKeyboard
} }
if _, err := bot.Send(msg); err != nil { if _, err := bot.Send(msg); err != nil {
logger.Warning(err) logger.Warning(err)
} }
} }
return j return j
} }
func (j *StatsNotifyJob) getClientUsage(id string) string { func (j *StatsNotifyJob) getClientUsage(id string) string {
traffic , err := j.inboundService.GetClientTrafficById(id) traffic, err := j.inboundService.GetClientTrafficById(id)
if err != nil { if err != nil {
logger.Warning(err) logger.Warning(err)
return "something wrong!" return "something wrong!"
@@ -241,8 +241,8 @@ func (j *StatsNotifyJob) getClientUsage(id string) string {
total = fmt.Sprintf("%s", common.FormatTraffic((traffic.Total))) 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", 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)), traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
total, expiryTime) total, expiryTime)
return output return output
} }

View File

@@ -28,11 +28,10 @@ func (j *XrayTrafficJob) Run() {
if err != nil { if err != nil {
logger.Warning("add traffic failed:", err) logger.Warning("add traffic failed:", err)
} }
err = j.inboundService.AddClientTraffic(clientTraffics) err = j.inboundService.AddClientTraffic(clientTraffics)
if err != nil { if err != nil {
logger.Warning("add client traffic failed:", err) logger.Warning("add client traffic failed:", err)
} }
} }

View File

@@ -298,19 +298,19 @@ func (s *Server) startTask() {
if err != nil { if err != nil {
logger.Warning("start xray failed:", err) logger.Warning("start xray failed:", err)
} }
// 每 30 秒检查一次 xray 是否在运行 // Check whether xray is running every 30 seconds
s.cron.AddJob("@every 30s", job.NewCheckXrayRunningJob()) s.cron.AddJob("@every 30s", job.NewCheckXrayRunningJob())
go func() { go func() {
time.Sleep(time.Second * 5) 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()) 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()) s.cron.AddJob("@every 30s", job.NewCheckInboundJob())
// 每一天提示一次流量情况,上海时间8点30 // Make a traffic condition every day, 8:30
var entry cron.EntryID var entry cron.EntryID
isTgbotenabled, err := s.settingService.GetTgbotenabled() isTgbotenabled, err := s.settingService.GetTgbotenabled()
if (err == nil) && (isTgbotenabled) { if (err == nil) && (isTgbotenabled) {
@@ -320,7 +320,7 @@ func (s *Server) startTask() {
runtime = "@daily" runtime = "@daily"
} }
logger.Infof("Tg notify enabled,run at %s", runtime) 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 { if err != nil {
logger.Warning("Add NewStatsNotifyJob error", err) logger.Warning("Add NewStatsNotifyJob error", err)
return return
@@ -333,7 +333,7 @@ func (s *Server) startTask() {
} }
func (s *Server) Start() (err error) { func (s *Server) Start() (err error) {
//这是一个匿名函数,没没有函数名 //This is an anonymous function, no function name
defer func() { defer func() {
if err != nil { if err != nil {
s.Stop() s.Stop()

View File

@@ -1,12 +1,12 @@
package xray package xray
type ClientTraffic struct { type ClientTraffic struct {
Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"` Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
InboundId int `json:"inboundId" form:"inboundId"` InboundId int `json:"inboundId" form:"inboundId"`
Enable bool `json:"enable" form:"enable"` Enable bool `json:"enable" form:"enable"`
Email string `json:"email" form:"email" gorm:"unique"` Email string `json:"email" form:"email" gorm:"unique"`
Up int64 `json:"up" form:"up"` Up int64 `json:"up" form:"up"`
Down int64 `json:"down" form:"down"` Down int64 `json:"down" form:"down"`
ExpiryTime int64 `json:"expiryTime" form:"expiryTime"` ExpiryTime int64 `json:"expiryTime" form:"expiryTime"`
Total int64 `json:"total" form:"total"` Total int64 `json:"total" form:"total"`
} }