tgbot_report.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. package tgbot
  2. import (
  3. "context"
  4. "fmt"
  5. "net"
  6. "os"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "github.com/mhsanaei/3x-ui/v3/internal/config"
  11. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  12. "github.com/mhsanaei/3x-ui/v3/internal/eventbus"
  13. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  14. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  15. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  16. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  17. "github.com/mymmrac/telego"
  18. tu "github.com/mymmrac/telego/telegoutil"
  19. )
  20. // SendReport sends a periodic report to admin chats.
  21. func (t *Tgbot) SendReport() {
  22. runTime, err := t.settingService.GetTgbotRuntime()
  23. if err == nil && len(runTime) > 0 {
  24. msg := ""
  25. msg += t.I18nBot("tgbot.messages.report", "RunTime=="+runTime)
  26. msg += t.I18nBot("tgbot.messages.datetime", "DateTime=="+time.Now().Format("2006-01-02 15:04:05"))
  27. t.SendMsgToTgbotAdmins(msg)
  28. }
  29. info := t.sendServerUsage()
  30. t.SendMsgToTgbotAdmins(info)
  31. t.sendExhaustedToAdmins()
  32. t.notifyExhausted()
  33. backupEnable, err := t.settingService.GetTgBotBackup()
  34. if err == nil && backupEnable {
  35. t.SendBackupToAdmins()
  36. }
  37. }
  38. // SendBackupToAdmins sends a database backup to admin chats.
  39. func (t *Tgbot) SendBackupToAdmins() {
  40. if !t.IsRunning() {
  41. return
  42. }
  43. dbData, err := t.serverService.GetDb()
  44. if err != nil {
  45. logger.Error("Error in getting db backup: ", err)
  46. }
  47. dbFilename := t.serverService.BackupFilename("")
  48. for i, adminId := range adminIds {
  49. t.sendBackupData(adminId, dbData, dbFilename)
  50. // Add delay between sends to avoid Telegram rate limits
  51. if i < len(adminIds)-1 {
  52. time.Sleep(1 * time.Second)
  53. }
  54. }
  55. }
  56. // sendExhaustedToAdmins sends notifications about exhausted clients to admins.
  57. func (t *Tgbot) sendExhaustedToAdmins() {
  58. if !t.IsRunning() {
  59. return
  60. }
  61. for _, adminId := range adminIds {
  62. t.getExhausted(adminId)
  63. }
  64. }
  65. // getServerUsage retrieves and formats server usage information.
  66. func (t *Tgbot) getServerUsage(chatId int64, messageID ...int) string {
  67. info := t.prepareServerUsageInfo()
  68. keyboard := tu.InlineKeyboard(tu.InlineKeyboardRow(
  69. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(t.encodeQuery("usage_refresh"))))
  70. if len(messageID) > 0 {
  71. t.editMessageTgBot(chatId, messageID[0], info, keyboard)
  72. } else {
  73. t.SendMsgToTgbot(chatId, info, keyboard)
  74. }
  75. return info
  76. }
  77. // Send server usage without an inline keyboard
  78. func (t *Tgbot) sendServerUsage() string {
  79. info := t.prepareServerUsageInfo()
  80. return info
  81. }
  82. // prepareServerUsageInfo prepares the server usage information string.
  83. func (t *Tgbot) prepareServerUsageInfo() string {
  84. // Check if we have cached data first
  85. if cachedStats, found := t.getCachedServerStats(); found {
  86. return cachedStats
  87. }
  88. info, ipv4, ipv6 := "", "", ""
  89. // get latest status of server with caching
  90. if cachedStatus, found := t.getCachedStatus(); found {
  91. t.lastStatus = cachedStatus
  92. } else {
  93. t.lastStatus = t.serverService.GetStatus(t.lastStatus)
  94. t.setCachedStatus(t.lastStatus)
  95. }
  96. var onlines []string
  97. if process := service.XrayProcess(); process != nil {
  98. onlines = process.GetOnlineClients()
  99. }
  100. info += t.I18nBot("tgbot.messages.hostname", "Hostname=="+hostname)
  101. info += t.I18nBot("tgbot.messages.version", "Version=="+config.GetPanelVersion())
  102. info += t.I18nBot("tgbot.messages.xrayVersion", "XrayVersion=="+fmt.Sprint(t.lastStatus.Xray.Version))
  103. // get ip address
  104. netInterfaces, err := net.Interfaces()
  105. if err != nil {
  106. logger.Error("net.Interfaces failed, err: ", err.Error())
  107. info += t.I18nBot("tgbot.messages.ip", "IP=="+t.I18nBot("tgbot.unknown"))
  108. info += "\r\n"
  109. } else {
  110. for i := range netInterfaces {
  111. if (netInterfaces[i].Flags & net.FlagUp) != 0 {
  112. addrs, _ := netInterfaces[i].Addrs()
  113. for _, address := range addrs {
  114. if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
  115. if ipnet.IP.To4() != nil {
  116. ipv4 += ipnet.IP.String() + " "
  117. } else if ipnet.IP.To16() != nil && !ipnet.IP.IsLinkLocalUnicast() {
  118. ipv6 += ipnet.IP.String() + " "
  119. }
  120. }
  121. }
  122. }
  123. }
  124. info += t.I18nBot("tgbot.messages.ipv4", "IPv4=="+ipv4)
  125. info += t.I18nBot("tgbot.messages.ipv6", "IPv6=="+ipv6)
  126. }
  127. info += t.I18nBot("tgbot.messages.serverUpTime", "UpTime=="+strconv.FormatUint(t.lastStatus.Uptime/86400, 10), "Unit=="+t.I18nBot("tgbot.days"))
  128. info += t.I18nBot("tgbot.messages.serverLoad", "Load1=="+strconv.FormatFloat(t.lastStatus.Loads[0], 'f', 2, 64), "Load2=="+strconv.FormatFloat(t.lastStatus.Loads[1], 'f', 2, 64), "Load3=="+strconv.FormatFloat(t.lastStatus.Loads[2], 'f', 2, 64))
  129. info += t.I18nBot("tgbot.messages.serverMemory", "Current=="+common.FormatTraffic(int64(t.lastStatus.Mem.Current)), "Total=="+common.FormatTraffic(int64(t.lastStatus.Mem.Total)))
  130. info += t.I18nBot("tgbot.messages.onlinesCount", "Count=="+fmt.Sprint(len(onlines)))
  131. info += t.I18nBot("tgbot.messages.tcpCount", "Count=="+strconv.Itoa(t.lastStatus.TcpCount))
  132. info += t.I18nBot("tgbot.messages.udpCount", "Count=="+strconv.Itoa(t.lastStatus.UdpCount))
  133. info += t.I18nBot("tgbot.messages.traffic", "Total=="+common.FormatTraffic(int64(t.lastStatus.NetTraffic.Sent+t.lastStatus.NetTraffic.Recv)), "Upload=="+common.FormatTraffic(int64(t.lastStatus.NetTraffic.Sent)), "Download=="+common.FormatTraffic(int64(t.lastStatus.NetTraffic.Recv)))
  134. info += t.I18nBot("tgbot.messages.xrayStatus", "State=="+fmt.Sprint(t.lastStatus.Xray.State))
  135. // Cache the complete server stats
  136. t.setCachedServerStats(info)
  137. return info
  138. }
  139. // UserLoginNotify publishes a login event to the event bus.
  140. func (t *Tgbot) UserLoginNotify(attempt LoginAttempt) {
  141. if attempt.Username == "" || attempt.IP == "" || attempt.Time == "" {
  142. logger.Warning("UserLoginNotify failed, invalid info!")
  143. return
  144. }
  145. if EventBus == nil {
  146. return
  147. }
  148. status := "fail"
  149. if attempt.Status == LoginSuccess {
  150. status = "success"
  151. }
  152. EventBus.Publish(eventbus.Event{
  153. Type: eventbus.EventLoginAttempt,
  154. Source: attempt.IP,
  155. Data: &eventbus.LoginEventData{
  156. Username: attempt.Username,
  157. IP: attempt.IP,
  158. Time: attempt.Time,
  159. Status: status,
  160. Reason: attempt.Reason,
  161. },
  162. })
  163. }
  164. // getExhausted retrieves and sends information about exhausted clients.
  165. func (t *Tgbot) getExhausted(chatId int64) {
  166. trDiff := int64(0)
  167. exDiff := int64(0)
  168. now := time.Now().Unix() * 1000
  169. var exhaustedInbounds []model.Inbound
  170. var exhaustedClients []xray.ClientTraffic
  171. var disabledInbounds []model.Inbound
  172. var disabledClients []xray.ClientTraffic
  173. TrafficThreshold, err := t.settingService.GetTrafficDiff()
  174. if err == nil && TrafficThreshold > 0 {
  175. trDiff = int64(TrafficThreshold) * 1073741824
  176. }
  177. ExpireThreshold, err := t.settingService.GetExpireDiff()
  178. if err == nil && ExpireThreshold > 0 {
  179. exDiff = int64(ExpireThreshold) * 86400000
  180. }
  181. inbounds, err := t.inboundService.GetAllInbounds()
  182. if err != nil {
  183. logger.Warning("Unable to load Inbounds", err)
  184. }
  185. seenClients := make(map[string]bool)
  186. for _, inbound := range inbounds {
  187. if inbound.Enable {
  188. if (inbound.ExpiryTime > 0 && (inbound.ExpiryTime-now < exDiff)) ||
  189. (inbound.Total > 0 && (inbound.Total-(inbound.Up+inbound.Down) < trDiff)) {
  190. exhaustedInbounds = append(exhaustedInbounds, *inbound)
  191. }
  192. if len(inbound.ClientStats) > 0 {
  193. for _, client := range inbound.ClientStats {
  194. if seenClients[client.Email] {
  195. continue
  196. }
  197. seenClients[client.Email] = true
  198. if client.Enable {
  199. if (client.ExpiryTime > 0 && (client.ExpiryTime-now < exDiff)) ||
  200. (client.Total > 0 && (client.Total-(client.Up+client.Down) < trDiff)) {
  201. exhaustedClients = append(exhaustedClients, client)
  202. }
  203. } else {
  204. disabledClients = append(disabledClients, client)
  205. }
  206. }
  207. }
  208. } else {
  209. disabledInbounds = append(disabledInbounds, *inbound)
  210. }
  211. }
  212. // Inbounds
  213. output := ""
  214. output += t.I18nBot("tgbot.messages.exhaustedCount", "Type=="+t.I18nBot("tgbot.inbounds"))
  215. output += t.I18nBot("tgbot.messages.disabled", "Disabled=="+strconv.Itoa(len(disabledInbounds)))
  216. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+strconv.Itoa(len(exhaustedInbounds)))
  217. if len(exhaustedInbounds) > 0 {
  218. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+t.I18nBot("tgbot.inbounds"))
  219. for _, inbound := range exhaustedInbounds {
  220. output += t.I18nBot("tgbot.messages.inbound", "Remark=="+inbound.Remark)
  221. output += t.I18nBot("tgbot.messages.port", "Port=="+strconv.Itoa(inbound.Port))
  222. output += t.I18nBot("tgbot.messages.traffic", "Total=="+common.FormatTraffic((inbound.Up+inbound.Down)), "Upload=="+common.FormatTraffic(inbound.Up), "Download=="+common.FormatTraffic(inbound.Down))
  223. if inbound.ExpiryTime == 0 {
  224. output += t.I18nBot("tgbot.messages.expire", "Time=="+t.I18nBot("tgbot.unlimited"))
  225. } else {
  226. output += t.I18nBot("tgbot.messages.expire", "Time=="+time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  227. }
  228. output += "\r\n"
  229. }
  230. }
  231. // Clients
  232. exhaustedCC := len(exhaustedClients)
  233. output += t.I18nBot("tgbot.messages.exhaustedCount", "Type=="+t.I18nBot("tgbot.clients"))
  234. output += t.I18nBot("tgbot.messages.disabled", "Disabled=="+strconv.Itoa(len(disabledClients)))
  235. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+strconv.Itoa(exhaustedCC))
  236. if exhaustedCC > 0 {
  237. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+t.I18nBot("tgbot.clients"))
  238. var buttons []telego.InlineKeyboardButton
  239. for _, traffic := range exhaustedClients {
  240. output += t.clientInfoMsg(&traffic, true, false, false, true, true, false)
  241. output += "\r\n"
  242. buttons = append(buttons, tu.InlineKeyboardButton(traffic.Email).WithCallbackData(t.encodeQuery("client_get_usage "+traffic.Email)))
  243. }
  244. cols := 0
  245. if exhaustedCC < 11 {
  246. cols = 1
  247. } else {
  248. cols = 2
  249. }
  250. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  251. keyboard := tu.InlineKeyboardGrid(tu.InlineKeyboardCols(cols, buttons...))
  252. t.SendMsgToTgbot(chatId, output, keyboard)
  253. } else {
  254. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  255. t.SendMsgToTgbot(chatId, output)
  256. }
  257. }
  258. // notifyExhausted sends notifications for exhausted clients.
  259. func (t *Tgbot) notifyExhausted() {
  260. trDiff := int64(0)
  261. exDiff := int64(0)
  262. now := time.Now().Unix() * 1000
  263. TrafficThreshold, err := t.settingService.GetTrafficDiff()
  264. if err == nil && TrafficThreshold > 0 {
  265. trDiff = int64(TrafficThreshold) * 1073741824
  266. }
  267. ExpireThreshold, err := t.settingService.GetExpireDiff()
  268. if err == nil && ExpireThreshold > 0 {
  269. exDiff = int64(ExpireThreshold) * 86400000
  270. }
  271. inbounds, err := t.inboundService.GetAllInbounds()
  272. if err != nil {
  273. logger.Warning("Unable to load Inbounds", err)
  274. }
  275. var chatIDsDone []int64
  276. for _, inbound := range inbounds {
  277. if inbound.Enable {
  278. if len(inbound.ClientStats) > 0 {
  279. clients, err := t.inboundService.GetClients(inbound)
  280. if err == nil {
  281. for _, client := range clients {
  282. if client.TgID != 0 {
  283. chatID := client.TgID
  284. if !int64Contains(chatIDsDone, chatID) && !checkAdmin(chatID) {
  285. var disabledClients []xray.ClientTraffic
  286. var exhaustedClients []xray.ClientTraffic
  287. traffics, err := t.inboundService.GetClientTrafficTgBot(client.TgID)
  288. if err == nil && len(traffics) > 0 {
  289. var output strings.Builder
  290. output.WriteString(t.I18nBot("tgbot.messages.exhaustedCount", "Type=="+t.I18nBot("tgbot.clients")))
  291. for _, traffic := range traffics {
  292. if traffic.Enable {
  293. if (traffic.ExpiryTime > 0 && (traffic.ExpiryTime-now < exDiff)) ||
  294. (traffic.Total > 0 && (traffic.Total-(traffic.Up+traffic.Down) < trDiff)) {
  295. exhaustedClients = append(exhaustedClients, *traffic)
  296. }
  297. } else {
  298. disabledClients = append(disabledClients, *traffic)
  299. }
  300. }
  301. if len(exhaustedClients) > 0 {
  302. output.WriteString(t.I18nBot("tgbot.messages.disabled", "Disabled=="+strconv.Itoa(len(disabledClients))))
  303. if len(disabledClients) > 0 {
  304. output.WriteString(t.I18nBot("tgbot.clients"))
  305. output.WriteString(":\r\n")
  306. for _, traffic := range disabledClients {
  307. output.WriteString(" ")
  308. output.WriteString(traffic.Email)
  309. }
  310. output.WriteString("\r\n")
  311. }
  312. output.WriteString("\r\n")
  313. output.WriteString(t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+strconv.Itoa(len(exhaustedClients))))
  314. for _, traffic := range exhaustedClients {
  315. output.WriteString(t.clientInfoMsg(&traffic, true, false, false, true, true, false))
  316. output.WriteString("\r\n")
  317. }
  318. t.SendMsgToTgbot(chatID, output.String())
  319. }
  320. chatIDsDone = append(chatIDsDone, chatID)
  321. }
  322. }
  323. }
  324. }
  325. }
  326. }
  327. }
  328. }
  329. }
  330. // onlineClients retrieves and sends information about online clients.
  331. func (t *Tgbot) onlineClients(chatId int64, messageID ...int) {
  332. process := service.XrayProcess()
  333. if process == nil || !process.IsRunning() {
  334. return
  335. }
  336. onlines := process.GetOnlineClients()
  337. onlinesCount := len(onlines)
  338. output := t.I18nBot("tgbot.messages.onlinesCount", "Count=="+fmt.Sprint(onlinesCount))
  339. keyboard := tu.InlineKeyboard(tu.InlineKeyboardRow(
  340. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(t.encodeQuery("onlines_refresh"))))
  341. if onlinesCount > 0 {
  342. var buttons []telego.InlineKeyboardButton
  343. for _, online := range onlines {
  344. label := online
  345. if _, inbound, err := t.inboundService.GetClientInboundByEmail(online); err == nil && inbound != nil && inbound.Remark != "" {
  346. label = online + " - " + inbound.Remark
  347. }
  348. buttons = append(buttons, tu.InlineKeyboardButton(label).WithCallbackData(t.encodeQuery("client_get_usage "+online)))
  349. }
  350. cols := 0
  351. if onlinesCount < 21 {
  352. cols = 2
  353. } else if onlinesCount < 61 {
  354. cols = 3
  355. } else {
  356. cols = 4
  357. }
  358. keyboard.InlineKeyboard = append(keyboard.InlineKeyboard, tu.InlineKeyboardCols(cols, buttons...)...)
  359. }
  360. if len(messageID) > 0 {
  361. t.editMessageTgBot(chatId, messageID[0], output, keyboard)
  362. } else {
  363. t.SendMsgToTgbot(chatId, output, keyboard)
  364. }
  365. }
  366. // sendBackup sends a backup of the database and configuration files.
  367. func (t *Tgbot) sendBackup(chatId int64) {
  368. dbData, err := t.serverService.GetDb()
  369. if err != nil {
  370. logger.Error("Error in getting db backup: ", err)
  371. }
  372. t.sendBackupData(chatId, dbData, t.serverService.BackupFilename(""))
  373. }
  374. func (t *Tgbot) sendBackupData(chatId int64, dbData []byte, dbFilename string) {
  375. output := t.I18nBot("tgbot.messages.hostname", "Hostname=="+hostname)
  376. output += t.I18nBot("tgbot.messages.backupTime", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  377. t.SendMsgToTgbot(chatId, output)
  378. // Send database backup (SQLite file, or a pg_dump archive on PostgreSQL)
  379. if dbData != nil {
  380. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  381. document := tu.Document(
  382. tu.ID(chatId),
  383. tu.FileFromBytes(dbData, dbFilename),
  384. )
  385. _, err := bot.SendDocument(ctx, document)
  386. cancel()
  387. if err != nil {
  388. logger.Error("Error in uploading backup: ", err)
  389. }
  390. }
  391. // Small delay between file sends
  392. time.Sleep(500 * time.Millisecond)
  393. // Send config.json backup
  394. file, err := os.Open(xray.GetConfigPath())
  395. if err == nil {
  396. defer file.Close()
  397. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  398. defer cancel()
  399. document := tu.Document(
  400. tu.ID(chatId),
  401. tu.File(file),
  402. )
  403. _, err = bot.SendDocument(ctx, document)
  404. if err != nil {
  405. logger.Error("Error in uploading config.json: ", err)
  406. }
  407. } else {
  408. logger.Error("Error in opening config.json file for backup: ", err)
  409. }
  410. }
  411. // sendBanLogs sends the ban logs to the specified chat.
  412. func (t *Tgbot) sendBanLogs(chatId int64, dt bool) {
  413. if dt {
  414. output := t.I18nBot("tgbot.messages.hostname", "Hostname=="+hostname)
  415. output += t.I18nBot("tgbot.messages.datetime", "DateTime=="+time.Now().Format("2006-01-02 15:04:05"))
  416. t.SendMsgToTgbot(chatId, output)
  417. }
  418. file, err := os.Open(xray.GetIPLimitBannedPrevLogPath())
  419. if err == nil {
  420. // Check if the file is non-empty before attempting to upload
  421. fileInfo, _ := file.Stat()
  422. if fileInfo.Size() > 0 {
  423. document := tu.Document(
  424. tu.ID(chatId),
  425. tu.File(file),
  426. )
  427. _, err = bot.SendDocument(context.Background(), document)
  428. if err != nil {
  429. logger.Error("Error in uploading IPLimitBannedPrevLog: ", err)
  430. }
  431. } else {
  432. logger.Warning("IPLimitBannedPrevLog file is empty, not uploading.")
  433. }
  434. file.Close()
  435. } else {
  436. logger.Error("Error in opening IPLimitBannedPrevLog file for backup: ", err)
  437. }
  438. file, err = os.Open(xray.GetIPLimitBannedLogPath())
  439. if err == nil {
  440. // Check if the file is non-empty before attempting to upload
  441. fileInfo, _ := file.Stat()
  442. if fileInfo.Size() > 0 {
  443. document := tu.Document(
  444. tu.ID(chatId),
  445. tu.File(file),
  446. )
  447. _, err = bot.SendDocument(context.Background(), document)
  448. if err != nil {
  449. logger.Error("Error in uploading IPLimitBannedLog: ", err)
  450. }
  451. } else {
  452. logger.Warning("IPLimitBannedLog file is empty, not uploading.")
  453. }
  454. file.Close()
  455. } else {
  456. logger.Error("Error in opening IPLimitBannedLog file for backup: ", err)
  457. }
  458. }