tgbot_report.go 17 KB

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