diff --git a/web/job/stats_notify_job.go b/web/job/stats_notify_job.go index f23ff0a9..365f41ae 100644 --- a/web/job/stats_notify_job.go +++ b/web/job/stats_notify_job.go @@ -1,12 +1,6 @@ package job import ( - "fmt" - "net" - "os" - "time" - "x-ui/logger" - "x-ui/util/common" "x-ui/web/service" ) @@ -32,56 +26,5 @@ func (j *StatsNotifyJob) Run() { if !j.xrayService.IsXrayRunning() { return } - var info string - //get hostname - name, err := os.Hostname() - if err != nil { - fmt.Println("get hostname error:", err) - return - } - info = fmt.Sprintf("Hostname:%s\r\n", name) - //get ip address - var ip string - netInterfaces, err := net.Interfaces() - if err != nil { - fmt.Println("net.Interfaces failed, err:", err.Error()) - return - } - - for i := 0; i < len(netInterfaces); i++ { - if (netInterfaces[i].Flags & net.FlagUp) != 0 { - addrs, _ := netInterfaces[i].Addrs() - - for _, address := range addrs { - if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { - if ipnet.IP.To4() != nil { - ip = ipnet.IP.String() - break - } else { - ip = ipnet.IP.String() - break - } - } - } - } - } - info += fmt.Sprintf("IP:%s\r\n \r\n", ip) - - // 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: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 { - info += "Expire date:unlimited\r\n \r\n" - } else { - info += fmt.Sprintf("Expire date:%s\r\n \r\n", time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05")) - } - } - j.tgbotService.SendMsgToTgbotAdmins(info) + j.tgbotService.SendReport() } diff --git a/web/service/inbound.go b/web/service/inbound.go index a020b01e..91db8720 100644 --- a/web/service/inbound.go +++ b/web/service/inbound.go @@ -501,33 +501,16 @@ func (s *InboundService) ResetClientTraffic(id int, clientEmail string) error { } return nil } -func (s *InboundService) GetClientTrafficById(uuid string) (traffic *xray.ClientTraffic, err error) { +func (s *InboundService) GetClientTrafficTgBot(tguname string) (traffic []*xray.ClientTraffic, err error) { db := database.GetDB() - inbound := &model.Inbound{} - traffic = &xray.ClientTraffic{} + var traffics []*xray.ClientTraffic - err = db.Model(model.Inbound{}).Where("settings like ?", "%"+uuid+"%").First(inbound).Error + err = db.Model(xray.ClientTraffic{}).Where("email like ?", "%@"+tguname).Find(&traffics).Error if err != nil { if err == gorm.ErrRecordNotFound { logger.Warning(err) return nil, err } } - traffic.InboundId = inbound.Id - - // get settings clients - settings := map[string][]model.Client{} - json.Unmarshal([]byte(inbound.Settings), &settings) - clients := settings["clients"] - for _, client := range clients { - if uuid == client.ID { - traffic.Email = client.Email - } - } - err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error - if err != nil { - logger.Warning(err) - return nil, err - } - return traffic, err + return traffics, err } diff --git a/web/service/tgbot.go b/web/service/tgbot.go index 74c380df..15ca47c7 100644 --- a/web/service/tgbot.go +++ b/web/service/tgbot.go @@ -2,10 +2,12 @@ package service import ( "fmt" + "net" "os" "strconv" "strings" "time" + "x-ui/config" "x-ui/logger" "x-ui/util/common" @@ -16,12 +18,6 @@ var bot *tgbotapi.BotAPI var adminIds []int64 var isRunning bool -var numericKeyboard = tgbotapi.NewInlineKeyboardMarkup( - tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData("Get Usage", "get_usage"), - ), -) - type LoginStatus byte const ( @@ -32,6 +28,8 @@ const ( type Tgbot struct { inboundService InboundService settingService SettingService + serverService ServerService + lastStatus *Status } func (t *Tgbot) NewTgbot() *Tgbot { @@ -95,78 +93,201 @@ func (t *Tgbot) OnReceive() { updates := bot.GetUpdatesChan(u) for update := range updates { + tgId := update.FromChat().ID + chatId := update.FromChat().ChatConfig().ChatID + isAdmin := checkAdmin(tgId) 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. - callback := tgbotapi.NewCallback(update.CallbackQuery.ID, update.CallbackQuery.Data) - 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" - } - if _, err := bot.Send(msg); err != nil { - logger.Warning(err) - } + t.asnwerCallback(update.CallbackQuery, isAdmin) + } + } else { + if update.Message.IsCommand() { + t.answerCommand(update.Message, chatId, isAdmin) + } else { + t.aswerChat(update.Message.Text, chatId, isAdmin) } - - continue - } - - if !update.Message.IsCommand() { // ignore any non-command Messages - continue - } - - // 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?" - msg.ReplyMarkup = numericKeyboard - - case "status": - msg.Text = "bot is ok." - - case "usage": - msg.Text = t.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) } } } -func (t *Tgbot) SendMsgToTgbot(tgid int64, msg string) { - info := tgbotapi.NewMessage(tgid, msg) - _, err := bot.Send(info) +func (t *Tgbot) answerCommand(message *tgbotapi.Message, chatId int64, isAdmin bool) { + msg := "" + // Extract the command from the Message. + switch message.Command() { + case "help": + msg = "This bot is providing you some specefic data from the server.\n\n Please choose:" + case "start": + msg = "Hello " + message.From.FirstName + " :)" + if isAdmin { + hostname, _ := os.Hostname() + msg += "\nWelcome to " + hostname + " management bot" + } + msg += "\n\nI can do some magics for you, please choose:" + case "status": + msg = "bot is ok." + default: + msg = "Unknown command" + } + t.SendAnswer(chatId, msg, isAdmin) +} + +func (t *Tgbot) aswerChat(message string, chatId int64, isAdmin bool) { + t.SendAnswer(chatId, "Unknown message", isAdmin) +} + +func (t *Tgbot) asnwerCallback(callbackQuery *tgbotapi.CallbackQuery, isAdmin bool) { + // Respond to the callback query, telling Telegram to show the user + // a message with the data received. + callback := tgbotapi.NewCallback(callbackQuery.ID, callbackQuery.Data) + if _, err := bot.Request(callback); err != nil { + logger.Warning(err) + } + + switch callbackQuery.Data { + case "get_usage": + t.SendMsgToTgbot(callbackQuery.From.ID, t.getServerUsage()) + case "inbounds": + t.SendMsgToTgbot(callbackQuery.From.ID, t.getInboundUsages()) + case "get_backup": + t.sendBackup(callbackQuery.From.ID) + case "client_traffic": + t.getClientUsage(callbackQuery.From.ID, callbackQuery.From.UserName) + } +} + +func checkAdmin(tgId int64) bool { + for _, adminId := range adminIds { + if adminId == tgId { + return true + } + } + return false +} + +func (t *Tgbot) SendAnswer(chatId int64, msg string, isAdmin bool) { + var numericKeyboard = tgbotapi.NewInlineKeyboardMarkup( + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("Server Usage", "get_usage"), + tgbotapi.NewInlineKeyboardButtonData("Get DB Backup", "get_backup"), + ), + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("Get Inbounds", "inbounds"), + tgbotapi.NewInlineKeyboardButtonData("Disabled Inbounds", "dis_inbounds"), + ), + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("Exhausted soon", "exhausted_soon"), + tgbotapi.NewInlineKeyboardButtonData("User info", "user_info"), + ), + ) + var numericKeyboardClient = tgbotapi.NewInlineKeyboardMarkup( + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("Get Usage", "client_traffic"), + ), + ) + msgConfig := tgbotapi.NewMessage(chatId, msg) + msgConfig.ParseMode = "HTML" + if isAdmin { + msgConfig.ReplyMarkup = numericKeyboard + } else { + msgConfig.ReplyMarkup = numericKeyboardClient + } + _, err := bot.Send(msgConfig) if err != nil { logger.Warning("Error sending telegram message :", err) } } +func (t *Tgbot) SendMsgToTgbot(tgid int64, msg string) { + var allMessages []string + limit := 1000 + // paging message if it is big + if len(msg) > limit { + messages := strings.Split(msg, "\r\n \r\n") + lastIndex := -1 + for _, message := range messages { + if (len(allMessages) == 0) || (len(allMessages[lastIndex])+len(message) > limit) { + allMessages = append(allMessages, message) + lastIndex++ + } else { + allMessages[lastIndex] += "\r\n \r\n" + message + } + } + } else { + allMessages = append(allMessages, msg) + } + for _, message := range allMessages { + info := tgbotapi.NewMessage(tgid, message) + info.ParseMode = "HTML" + _, err := bot.Send(info) + if err != nil { + logger.Warning("Error sending telegram message :", err) + } + time.Sleep(500 * time.Millisecond) + } +} + func (t *Tgbot) SendMsgToTgbotAdmins(msg string) { for _, adminId := range adminIds { t.SendMsgToTgbot(adminId, msg) } } +func (t *Tgbot) getServerUsage() string { + var info string + //get hostname + name, err := os.Hostname() + if err != nil { + logger.Error("get hostname error:", err) + name = "" + } + info = fmt.Sprintf("Hostname:%s\r\n", name) + //get ip address + var ip string + var ipv6 string + netInterfaces, err := net.Interfaces() + if err != nil { + logger.Error("net.Interfaces failed, err:", err.Error()) + info += "IP: Unknown\r\n \r\n" + } else { + for i := 0; i < len(netInterfaces); i++ { + if (netInterfaces[i].Flags & net.FlagUp) != 0 { + addrs, _ := netInterfaces[i].Addrs() + + for _, address := range addrs { + if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { + if ipnet.IP.To4() != nil { + ip += ipnet.IP.String() + " " + } else if ipnet.IP.To16() != nil && !ipnet.IP.IsLinkLocalUnicast() { + ipv6 += ipnet.IP.String() + " " + } + } + } + } + } + info += fmt.Sprintf("IP:%s\r\nIPv6:%s\r\n", ip, ipv6) + } + + // get latest status of server + t.lastStatus = t.serverService.GetStatus(t.lastStatus) + info += fmt.Sprintf("Server Uptime: %d days\r\n", int(t.lastStatus.Uptime/86400)) + info += fmt.Sprintf("Server Load: %.1f, %.1f, %.1f\r\n", t.lastStatus.Loads[0], t.lastStatus.Loads[1], t.lastStatus.Loads[2]) + info += fmt.Sprintf("Server Memory: %s/%s\r\n", common.FormatTraffic(int64(t.lastStatus.Mem.Current)), common.FormatTraffic(int64(t.lastStatus.Mem.Total))) + info += fmt.Sprintf("TcpCount: %d\r\n", t.lastStatus.TcpCount) + info += fmt.Sprintf("UdpCount: %d\r\n", t.lastStatus.UdpCount) + info += fmt.Sprintf("Total traffic: %s: ↑%s,↓%s\r\n", common.FormatTraffic(int64(t.lastStatus.NetTraffic.Sent+t.lastStatus.NetTraffic.Recv)), common.FormatTraffic(int64(t.lastStatus.NetTraffic.Sent)), common.FormatTraffic(int64(t.lastStatus.NetTraffic.Recv))) + info += fmt.Sprintf("Xray status: %s", t.lastStatus.Xray.State) + + return info +} + +func (t *Tgbot) SendReport() { + info := t.getServerUsage() + t.SendMsgToTgbotAdmins(info) + inbounds := t.getInboundUsages() + t.SendMsgToTgbotAdmins(inbounds) + +} + func (t *Tgbot) UserLoginNotify(username string, ip string, time string, status LoginStatus) { if username == "" || ip == "" || time == "" { logger.Warning("UserLoginNotify failed,invalid info") @@ -190,27 +311,68 @@ func (t *Tgbot) UserLoginNotify(username string, ip string, time string, status t.SendMsgToTgbotAdmins(msg) } -func (t *Tgbot) getClientUsage(id string) string { - traffic, err := t.inboundService.GetClientTrafficById(id) +func (t *Tgbot) getInboundUsages() string { + info := "" + // get traffic + inbouds, err := t.inboundService.GetAllInbounds() + if err != nil { + logger.Warning("GetAllInbounds run failed:", err) + info += "Failed to get inbounds" + } else { + // 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("Inbound:%s\r\nPort:%d\r\nTraffic: %s (↑%s,↓%s)\r\n", inbound.Remark, inbound.Port, common.FormatTraffic((inbound.Up + inbound.Down)), common.FormatTraffic(inbound.Up), common.FormatTraffic(inbound.Down)) + if inbound.ExpiryTime == 0 { + info += "Expire date:unlimited\r\n \r\n" + } else { + info += fmt.Sprintf("Expire date:%s\r\n \r\n", time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05")) + } + } + } + return info +} + +func (t *Tgbot) getClientUsage(chatId int64, tgUserName string) { + traffics, err := t.inboundService.GetClientTrafficTgBot(tgUserName) if err != nil { logger.Warning(err) - return "something wrong!" + msg := "Something went wrong!" + t.SendMsgToTgbot(chatId, msg) + return } - expiryTime := "" - if traffic.ExpiryTime == 0 { - expiryTime = "unlimited" - } else { - expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05") + if len(traffics) == 0 { + msg := "Your configuration is not found!\nPlease ask your Admin to use your telegram username in your configuration(s).\n\nYour username: @" + tgUserName + "" + t.SendMsgToTgbot(chatId, msg) } - total := "" - if traffic.Total == 0 { - total = "unlimited" - } else { - total = common.FormatTraffic((traffic.Total)) + for _, traffic := range traffics { + expiryTime := "" + if traffic.ExpiryTime == 0 { + expiryTime = "unlimited" + } else { + expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05") + } + total := "" + if traffic.Total == 0 { + total = "unlimited" + } else { + total = 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) + t.SendMsgToTgbot(chatId, output) + } + t.SendAnswer(chatId, "Please choose:", false) +} + +func (t *Tgbot) sendBackup(chatId int64) { + sendingTime := time.Now().Format("2006-01-02 15:04:05") + t.SendMsgToTgbot(chatId, "Backup time: "+sendingTime) + file := tgbotapi.FilePath(config.GetDBPath()) + msg := tgbotapi.NewDocument(chatId, file) + _, err := bot.Send(msg) + if err != nil { + logger.Warning("Error in uploading backup: ", err) } - 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) - - return output }