diff options
| author | MHSanaei <33454419+MHSanaei@users.noreply.github.com> | 2023-03-23 22:52:50 +0300 |
|---|---|---|
| committer | MHSanaei <33454419+MHSanaei@users.noreply.github.com> | 2023-03-23 22:52:50 +0300 |
| commit | 5ef8a5a37ec7e6b7df710fa61b0324ab5a6617ab (patch) | |
| tree | 8356d79072560de703f6dbc1d26fa5d51a6d5ac1 /web/service | |
| parent | c49a9e877cb8481a98564b45f3462f8f73189f6e (diff) | |
old designv1.0.9
Diffstat (limited to 'web/service')
| -rw-r--r-- | web/service/inbound.go | 297 | ||||
| -rw-r--r-- | web/service/server.go | 4 | ||||
| -rw-r--r-- | web/service/setting.go | 56 | ||||
| -rw-r--r-- | web/service/tgbot.go | 546 | ||||
| -rw-r--r-- | web/service/xray.go | 2 |
5 files changed, 64 insertions, 841 deletions
diff --git a/web/service/inbound.go b/web/service/inbound.go index b6f4f031..b3f3265b 100644 --- a/web/service/inbound.go +++ b/web/service/inbound.go @@ -54,7 +54,7 @@ func (s *InboundService) getClients(inbound *model.Inbound) ([]model.Client, err settings := map[string][]model.Client{} json.Unmarshal([]byte(inbound.Settings), &settings) if settings == nil { - return nil, fmt.Errorf("setting is null") + return nil, fmt.Errorf("Setting is null") } clients := settings["clients"] @@ -125,18 +125,11 @@ func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, err return inbound, common.NewError("Duplicate email:", existEmail) } - clients, err := s.getClients(inbound) - if err != nil { - return inbound, err - } - db := database.GetDB() err = db.Save(inbound).Error if err == nil { - for _, client := range clients { - s.AddClientStat(inbound.Id, &client) - } + s.UpdateClientStat(inbound.Id, inbound.Settings) } return inbound, err } @@ -175,24 +168,6 @@ func (s *InboundService) AddInbounds(inbounds []*model.Inbound) error { func (s *InboundService) DelInbound(id int) error { db := database.GetDB() - err := db.Where("inbound_id = ?", id).Delete(xray.ClientTraffic{}).Error - if err != nil { - return err - } - inbound, err := s.GetInbound(id) - if err != nil { - return err - } - clients, err := s.getClients(inbound) - if err != nil { - return err - } - for _, client := range clients { - err := s.DelClientIPs(db, client.Email) - if err != nil { - return err - } - } return db.Delete(model.Inbound{}, id).Error } @@ -241,128 +216,11 @@ func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, oldInbound.Sniffing = inbound.Sniffing oldInbound.Tag = fmt.Sprintf("inbound-%v", inbound.Port) + s.UpdateClientStat(inbound.Id, inbound.Settings) db := database.GetDB() return inbound, db.Save(oldInbound).Error } -func (s *InboundService) AddInboundClient(inbound *model.Inbound) error { - existEmail, err := s.checkEmailExistForInbound(inbound) - if err != nil { - return err - } - - if existEmail != "" { - return common.NewError("Duplicate email:", existEmail) - } - - clients, err := s.getClients(inbound) - if err != nil { - return err - } - - oldInbound, err := s.GetInbound(inbound.Id) - if err != nil { - return err - } - - oldClients, err := s.getClients(oldInbound) - if err != nil { - return err - } - - oldInbound.Settings = inbound.Settings - - if len(clients[len(clients)-1].Email) > 0 { - s.AddClientStat(inbound.Id, &clients[len(clients)-1]) - } - for i := len(oldClients); i < len(clients); i++ { - if len(clients[i].Email) > 0 { - s.AddClientStat(inbound.Id, &clients[i]) - } - } - db := database.GetDB() - return db.Save(oldInbound).Error -} - -func (s *InboundService) DelInboundClient(inbound *model.Inbound, email string) error { - db := database.GetDB() - err := s.DelClientStat(db, email) - if err != nil { - logger.Error("Delete stats Data Error") - return err - } - - oldInbound, err := s.GetInbound(inbound.Id) - if err != nil { - logger.Error("Load Old Data Error") - return err - } - - oldInbound.Settings = inbound.Settings - - err = s.DelClientIPs(db, email) - if err != nil { - logger.Error("Error in delete client IPs") - return err - } - - return db.Save(oldInbound).Error -} - -func (s *InboundService) UpdateInboundClient(inbound *model.Inbound, index int) error { - existEmail, err := s.checkEmailExistForInbound(inbound) - if err != nil { - return err - } - if existEmail != "" { - return common.NewError("Duplicate email:", existEmail) - } - - clients, err := s.getClients(inbound) - if err != nil { - return err - } - - oldInbound, err := s.GetInbound(inbound.Id) - if err != nil { - return err - } - - oldClients, err := s.getClients(oldInbound) - if err != nil { - return err - } - - oldInbound.Settings = inbound.Settings - - db := database.GetDB() - - if len(clients[index].Email) > 0 { - if len(oldClients[index].Email) > 0 { - err = s.UpdateClientStat(oldClients[index].Email, &clients[index]) - if err != nil { - return err - } - err = s.UpdateClientIPs(db, oldClients[index].Email, clients[index].Email) - if err != nil { - return err - } - } else { - s.AddClientStat(inbound.Id, &clients[index]) - } - } else { - err = s.DelClientStat(db, oldClients[index].Email) - if err != nil { - return err - } - err = s.DelClientIPs(db, oldClients[index].Email) - if err != nil { - return err - } - } - return db.Save(oldInbound).Error -} - func (s *InboundService) AddTraffic(traffics []*xray.Traffic) (err error) { if len(traffics) == 0 { return nil @@ -425,12 +283,10 @@ func (s *InboundService) AddClientTraffic(traffics []*xray.ClientTraffic) (err e } continue } - err = txInbound.Where("id=?", client.InboundId).First(inbound).Error if err != nil { if err == gorm.ErrRecordNotFound { logger.Warning(err, traffic.Email) - } continue } @@ -444,7 +300,7 @@ func (s *InboundService) AddClientTraffic(traffics []*xray.ClientTraffic) (err e traffic.Total = client.TotalGB } } - if tx.Where("inbound_id = ? and email = ?", inbound.Id, traffic.Email). + if tx.Where("inbound_id = ?", inbound.Id).Where("email = ?", traffic.Email). UpdateColumns(map[string]interface{}{ "enable": true, "expiry_time": traffic.ExpiryTime, @@ -483,102 +339,82 @@ func (s *InboundService) DisableInvalidClients() (int64, error) { count := result.RowsAffected return count, err } -func (s *InboundService) AddClientStat(inboundId int, client *model.Client) error { +func (s *InboundService) UpdateClientStat(inboundId int, inboundSettings string) error { db := database.GetDB() - clientTraffic := xray.ClientTraffic{} - clientTraffic.InboundId = inboundId - clientTraffic.Email = client.Email - clientTraffic.Total = client.TotalGB - clientTraffic.ExpiryTime = client.ExpiryTime - clientTraffic.Enable = true - clientTraffic.Up = 0 - clientTraffic.Down = 0 - result := db.Create(&clientTraffic) - err := result.Error - if err != nil { - return err - } - return nil -} -func (s *InboundService) UpdateClientStat(email string, client *model.Client) error { - db := database.GetDB() + // get settings clients + settings := map[string][]model.Client{} + json.Unmarshal([]byte(inboundSettings), &settings) + clients := settings["clients"] + for _, client := range clients { + result := db.Model(xray.ClientTraffic{}). + Where("inbound_id = ? and email = ?", inboundId, client.Email). + Updates(map[string]interface{}{"enable": true, "total": client.TotalGB, "expiry_time": client.ExpiryTime}) + if result.RowsAffected == 0 { + clientTraffic := xray.ClientTraffic{} + clientTraffic.InboundId = inboundId + clientTraffic.Email = client.Email + clientTraffic.Total = client.TotalGB + clientTraffic.ExpiryTime = client.ExpiryTime + clientTraffic.Enable = true + clientTraffic.Up = 0 + clientTraffic.Down = 0 + db.Create(&clientTraffic) + } + err := result.Error + if err != nil { + return err + } - result := db.Model(xray.ClientTraffic{}). - Where("email = ?", email). - Updates(map[string]interface{}{ - "enable": true, - "email": client.Email, - "total": client.TotalGB, - "expiry_time": client.ExpiryTime}) - err := result.Error - if err != nil { - return err } return nil } - -func (s *InboundService) UpdateClientIPs(tx *gorm.DB, oldEmail string, newEmail string) error { - return tx.Model(model.InboundClientIps{}).Where("client_email = ?", oldEmail).Update("client_email", newEmail).Error -} - func (s *InboundService) DelClientStat(tx *gorm.DB, email string) error { return tx.Where("email = ?", email).Delete(xray.ClientTraffic{}).Error } - -func (s *InboundService) DelClientIPs(tx *gorm.DB, email string) error { - logger.Warning(email) - return tx.Where("client_email = ?", email).Delete(model.InboundClientIps{}).Error +func (s *InboundService) GetInboundClientIps(clientEmail string) (string, error) { + db := database.GetDB() + InboundClientIps := &model.InboundClientIps{} + err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error + if err != nil { + return "", err + } + return InboundClientIps.Ips, nil } - -func (s *InboundService) ResetClientTraffic(id int, clientEmail string) error { +func (s *InboundService) ClearClientIps(clientEmail string) (error) { db := database.GetDB() - result := db.Model(xray.ClientTraffic{}). - Where("inbound_id = ? and email = ?", id, clientEmail). - Updates(map[string]interface{}{"enable": true, "up": 0, "down": 0}) - + result := db.Model(model.InboundClientIps{}). + Where("client_email = ?", clientEmail). + Update("ips", "") err := result.Error + if err != nil { return err } return nil } -func (s *InboundService) GetClientTrafficTgBot(tguname string) (traffic []*xray.ClientTraffic, err error) { +func (s *InboundService) ResetClientTraffic(clientEmail string) error { db := database.GetDB() - var traffics []*xray.ClientTraffic - 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 - } - } - return traffics, err -} + result := db.Model(xray.ClientTraffic{}). + Where("email = ?", clientEmail). + Updates(map[string]interface{}{"up": 0, "down": 0}) -func (s *InboundService) GetClientTrafficByEmail(email string) (traffic []*xray.ClientTraffic, err error) { - db := database.GetDB() - var traffics []*xray.ClientTraffic + err := result.Error - err = db.Model(xray.ClientTraffic{}).Where("email like ?", "%"+email+"%").Find(&traffics).Error if err != nil { - if err == gorm.ErrRecordNotFound { - logger.Warning(err) - return nil, err - } + return err } - return traffics, err + return nil } - -func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.ClientTraffic, err error) { +func (s *InboundService) GetClientTrafficById(uuid string) (traffic *xray.ClientTraffic, err error) { db := database.GetDB() inbound := &model.Inbound{} traffic = &xray.ClientTraffic{} - err = db.Model(model.Inbound{}).Where("settings like ?", "%\""+query+"\"%").First(inbound).Error + err = db.Model(model.Inbound{}).Where("settings like ?", "%"+uuid+"%").First(inbound).Error if err != nil { if err == gorm.ErrRecordNotFound { logger.Warning(err) @@ -592,18 +428,10 @@ func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.Client json.Unmarshal([]byte(inbound.Settings), &settings) clients := settings["clients"] for _, client := range clients { - if client.ID == query && client.Email != "" { - traffic.Email = client.Email - break - } - if client.Password == query && client.Email != "" { + if uuid == client.ID { traffic.Email = client.Email - break } } - if traffic.Email == "" { - return nil, err - } err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error if err != nil { logger.Warning(err) @@ -611,26 +439,3 @@ func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.Client } return traffic, err } - -func (s *InboundService) GetInboundClientIps(clientEmail string) (string, error) { - db := database.GetDB() - InboundClientIps := &model.InboundClientIps{} - err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error - if err != nil { - return "", err - } - return InboundClientIps.Ips, nil -} -func (s *InboundService) ClearClientIps(clientEmail string) error { - db := database.GetDB() - - result := db.Model(model.InboundClientIps{}). - Where("client_email = ?", clientEmail). - Update("ips", "") - err := result.Error - - if err != nil { - return err - } - return nil -} diff --git a/web/service/server.go b/web/service/server.go index 6737bef2..31716b9f 100644 --- a/web/service/server.go +++ b/web/service/server.go @@ -143,7 +143,7 @@ func (s *ServerService) GetStatus(lastStatus *Status) *Status { } else { logger.Warning("can not find io counters") } - + status.TcpCount, err = sys.GetTCPCount() if err != nil { logger.Warning("get tcp connections failed:", err) @@ -153,7 +153,7 @@ func (s *ServerService) GetStatus(lastStatus *Status) *Status { if err != nil { logger.Warning("get udp connections failed:", err) } - + if s.xrayService.IsXrayRunning() { status.Xray.State = Running status.Xray.ErrorMsg = "" diff --git a/web/service/setting.go b/web/service/setting.go index c30bb929..4d9231b3 100644 --- a/web/service/setting.go +++ b/web/service/setting.go @@ -31,12 +31,8 @@ var defaultValueMap = map[string]string{ "timeLocation": "Asia/Tehran", "tgBotEnable": "false", "tgBotToken": "", - "tgBotChatId": "", - "tgRunTime": "@daily", - "tgBotBackup": "false", - "tgExpireDiff": "0", - "tgTrafficDiff": "0", - "tgCpu": "0", + "tgBotChatId": "0", + "tgRunTime": "", } type SettingService struct { @@ -206,60 +202,28 @@ func (s *SettingService) SetTgBotToken(token string) error { return s.setString("tgBotToken", token) } -func (s *SettingService) GetTgBotChatId() (string, error) { - return s.getString("tgBotChatId") +func (s *SettingService) GetTgBotChatId() (int, error) { + return s.getInt("tgBotChatId") } -func (s *SettingService) SetTgBotChatId(chatIds string) error { - return s.setString("tgBotChatId", chatIds) -} - -func (s *SettingService) GetTgbotenabled() (bool, error) { - return s.getBool("tgBotEnable") +func (s *SettingService) SetTgBotChatId(chatId int) error { + return s.setInt("tgBotChatId", chatId) } func (s *SettingService) SetTgbotenabled(value bool) error { return s.setBool("tgBotEnable", value) } -func (s *SettingService) GetTgbotRuntime() (string, error) { - return s.getString("tgRunTime") +func (s *SettingService) GetTgbotenabled() (bool, error) { + return s.getBool("tgBotEnable") } func (s *SettingService) SetTgbotRuntime(time string) error { return s.setString("tgRunTime", time) } -func (s *SettingService) GetTgBotBackup() (bool, error) { - return s.getBool("tgBotBackup") -} - -func (s *SettingService) SetTgBotBackup(value bool) error { - return s.setBool("tgBotBackup", value) -} - -func (s *SettingService) GetTgExpireDiff() (int, error) { - return s.getInt("tgExpireDiff") -} - -func (s *SettingService) SetTgExpireDiff(value int) error { - return s.setInt("tgExpireDiff", value) -} - -func (s *SettingService) GetTgTrafficDiff() (int, error) { - return s.getInt("tgTrafficDiff") -} - -func (s *SettingService) SetTgTrafficDiff(value int) error { - return s.setInt("tgTrafficDiff", value) -} - -func (s *SettingService) GetTgCpu() (int, error) { - return s.getInt("tgCpu") -} - -func (s *SettingService) SetTgCpu(value int) error { - return s.setInt("tgCpu", value) +func (s *SettingService) GetTgbotRuntime() (string, error) { + return s.getString("tgRunTime") } func (s *SettingService) GetPort() (int, error) { diff --git a/web/service/tgbot.go b/web/service/tgbot.go deleted file mode 100644 index e7c9f97a..00000000 --- a/web/service/tgbot.go +++ /dev/null @@ -1,546 +0,0 @@ -package service - -import ( - "fmt" - "net" - "os" - "strconv" - "strings" - "time" - "x-ui/config" - "x-ui/database/model" - "x-ui/logger" - "x-ui/util/common" - "x-ui/xray" - - tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" -) - -var bot *tgbotapi.BotAPI -var adminIds []int64 -var isRunning bool - -type LoginStatus byte - -const ( - LoginSuccess LoginStatus = 1 - LoginFail LoginStatus = 0 -) - -type Tgbot struct { - inboundService InboundService - settingService SettingService - serverService ServerService - lastStatus *Status -} - -func (t *Tgbot) NewTgbot() *Tgbot { - return new(Tgbot) -} - -func (t *Tgbot) Start() error { - tgBottoken, err := t.settingService.GetTgBotToken() - if err != nil || tgBottoken == "" { - logger.Warning("Get TgBotToken failed:", err) - return err - } - - tgBotid, err := t.settingService.GetTgBotChatId() - if err != nil { - logger.Warning("Get GetTgBotChatId failed:", err) - return err - } - - for _, adminId := range strings.Split(tgBotid, ",") { - id, err := strconv.Atoi(adminId) - if err != nil { - logger.Warning("Failed to get IDs from GetTgBotChatId:", err) - return err - } - adminIds = append(adminIds, int64(id)) - } - - bot, err = tgbotapi.NewBotAPI(tgBottoken) - if err != nil { - fmt.Println("Get tgbot's api error:", err) - return err - } - bot.Debug = false - - // listen for TG bot income messages - if !isRunning { - logger.Info("Starting Telegram receiver ...") - go t.OnReceive() - isRunning = true - } - - return nil -} - -func (t *Tgbot) IsRunnging() bool { - return isRunning -} - -func (t *Tgbot) Stop() { - bot.StopReceivingUpdates() - logger.Info("Stop Telegram receiver ...") - isRunning = false - adminIds = nil -} - -func (t *Tgbot) OnReceive() { - u := tgbotapi.NewUpdate(0) - u.Timeout = 10 - - 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 { - t.asnwerCallback(update.CallbackQuery, isAdmin) - } - } else { - if update.Message.IsCommand() { - t.answerCommand(update.Message, chatId, isAdmin) - } else { - t.aswerChat(update.Message.Text, chatId, isAdmin) - } - } - } -} - -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 <i>" + message.From.FirstName + "</i> 👋" - if isAdmin { - hostname, _ := os.Hostname() - msg += "\nWelcome to <b>" + hostname + "</b> management bot" - } - msg += "\n\nI can do some magics for you, please choose:" - case "status": - msg = "bot is ok ✅" - case "usage": - if isAdmin { - t.searchClient(chatId, message.CommandArguments()) - } else { - t.searchForClient(chatId, message.CommandArguments()) - } - 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 "exhausted_soon": - t.SendMsgToTgbot(callbackQuery.From.ID, t.getExhausted()) - case "get_backup": - t.sendBackup(callbackQuery.From.ID) - case "client_traffic": - t.getClientUsage(callbackQuery.From.ID, callbackQuery.From.UserName) - case "client_commands": - t.SendMsgToTgbot(callbackQuery.From.ID, "To search for statistics, just use folowing command:\r\n \r\n<code>/usage [UID|Passowrd]</code>\r\n \r\nUse UID for vmess and vless and Password for Trojan.") - case "commands": - t.SendMsgToTgbot(callbackQuery.From.ID, "To search for a client email, just use folowing command:\r\n \r\n<code>/usage email</code>") - } -} - -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("Exhausted soon", "exhausted_soon"), - ), - tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData("Commands", "commands"), - ), - ) - var numericKeyboardClient = tgbotapi.NewInlineKeyboardMarkup( - tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData("Get Usage", "client_traffic"), - tgbotapi.NewInlineKeyboardButtonData("Commands", "client_commands"), - ), - ) - 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 := 2000 - // 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) SendReport() { - runTime, err := t.settingService.GetTgbotRuntime() - if err == nil && len(runTime) > 0 { - t.SendMsgToTgbotAdmins("🕰 Scheduled reports: " + runTime + "\r\nDate-Time: " + time.Now().Format("2006-01-02 15:04:05")) - } - info := t.getServerUsage() - t.SendMsgToTgbotAdmins(info) - exhausted := t.getExhausted() - t.SendMsgToTgbotAdmins(exhausted) - backupEnable, err := t.settingService.GetTgBotBackup() - if err == nil && backupEnable { - for _, adminId := range adminIds { - t.sendBackup(int64(adminId)) - } - } -} - -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\n🌐IPv6: %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("🚦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) UserLoginNotify(username string, ip string, time string, status LoginStatus) { - if username == "" || ip == "" || time == "" { - logger.Warning("UserLoginNotify failed,invalid info") - return - } - var msg string - // Get hostname - name, err := os.Hostname() - if err != nil { - logger.Warning("get hostname error:", err) - return - } - if status == LoginSuccess { - msg = fmt.Sprintf("✅ Successfully logged-in to the panel\r\nHostname:%s\r\n", name) - } else if status == LoginFail { - msg = fmt.Sprintf("❗ Login to the panel was unsuccessful\r\nHostname:%s\r\n", name) - } - msg += fmt.Sprintf("⏰ Time:%s\r\n", time) - msg += fmt.Sprintf("🆔 Username:%s\r\n", username) - msg += fmt.Sprintf("🌐 IP:%s\r\n", ip) - t.SendMsgToTgbotAdmins(msg) -} - -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\n", inbound.Remark, inbound.Port) - info += fmt.Sprintf("Traffic: %s (↑%s,↓%s)\r\n", 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) - msg := "❌ Something went wrong!" - t.SendMsgToTgbot(chatId, msg) - return - } - 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: <b>@" + tgUserName + "</b>" - t.SendMsgToTgbot(chatId, msg) - } - 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) searchClient(chatId int64, email string) { - traffics, err := t.inboundService.GetClientTrafficByEmail(email) - if err != nil { - logger.Warning(err) - msg := "❌ Something went wrong!" - t.SendMsgToTgbot(chatId, msg) - return - } - if len(traffics) == 0 { - msg := "No result!" - t.SendMsgToTgbot(chatId, msg) - return - } - 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) - } -} - -func (t *Tgbot) searchForClient(chatId int64, query string) { - traffic, err := t.inboundService.SearchClientTraffic(query) - if err != nil { - logger.Warning(err) - msg := "❌ Something went wrong!" - t.SendMsgToTgbot(chatId, msg) - return - } - if traffic == nil { - msg := "No result!" - 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") - } - 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) -} - -func (t *Tgbot) getExhausted() string { - trDiff := int64(0) - exDiff := int64(0) - now := time.Now().Unix() * 1000 - var exhaustedInbounds []model.Inbound - var exhaustedClients []xray.ClientTraffic - var disabledInbounds []model.Inbound - var disabledClients []xray.ClientTraffic - output := "" - TrafficThreshold, err := t.settingService.GetTgTrafficDiff() - if err == nil && TrafficThreshold > 0 { - trDiff = int64(TrafficThreshold) * 1073741824 - } - ExpireThreshold, err := t.settingService.GetTgExpireDiff() - if err == nil && ExpireThreshold > 0 { - exDiff = int64(ExpireThreshold) * 84600 - } - inbounds, err := t.inboundService.GetAllInbounds() - if err != nil { - logger.Warning("Unable to load Inbounds", err) - } - for _, inbound := range inbounds { - if inbound.Enable { - if (inbound.ExpiryTime > 0 && (now-inbound.ExpiryTime < exDiff)) || - (inbound.Total > 0 && (inbound.Total-inbound.Up+inbound.Down < trDiff)) { - exhaustedInbounds = append(exhaustedInbounds, *inbound) - } - if len(inbound.ClientStats) > 0 { - for _, client := range inbound.ClientStats { - if client.Enable { - if (client.ExpiryTime > 0 && (now-client.ExpiryTime < exDiff)) || - (client.Total > 0 && (client.Total-client.Up+client.Down < trDiff)) { - exhaustedClients = append(exhaustedClients, client) - } - } else { - disabledClients = append(disabledClients, client) - } - } - } - } else { - disabledInbounds = append(disabledInbounds, *inbound) - } - } - output += fmt.Sprintf("Exhausted Inbounds count:\r\n🛑 Disabled: %d\r\n🔜 Exhaust soon: %d\r\n \r\n", len(disabledInbounds), len(exhaustedInbounds)) - if len(disabledInbounds)+len(exhaustedInbounds) > 0 { - output += "Exhausted Inbounds:\r\n" - for _, inbound := range exhaustedInbounds { - output += 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 { - output += "Expire date: ♾Unlimited\r\n \r\n" - } else { - output += fmt.Sprintf("Expire date:%s\r\n \r\n", time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05")) - } - } - } - output += fmt.Sprintf("Exhausted Clients count:\r\n🛑 Disabled: %d\r\n🔜 Exhaust soon: %d\r\n \r\n", len(disabledClients), len(exhaustedClients)) - if len(disabledClients)+len(exhaustedClients) > 0 { - output += "Exhausted Clients:\r\n" - for _, traffic := range exhaustedClients { - 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),
|
