1
0

tgbot.go 143 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841
  1. package service
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "embed"
  6. "encoding/base64"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "html"
  11. "io"
  12. "math/big"
  13. "net"
  14. "net/http"
  15. "net/url"
  16. "os"
  17. "regexp"
  18. "strconv"
  19. "strings"
  20. "sync"
  21. "time"
  22. "github.com/mhsanaei/3x-ui/v2/config"
  23. "github.com/mhsanaei/3x-ui/v2/database"
  24. "github.com/mhsanaei/3x-ui/v2/database/model"
  25. "github.com/mhsanaei/3x-ui/v2/logger"
  26. "github.com/mhsanaei/3x-ui/v2/util/common"
  27. "github.com/mhsanaei/3x-ui/v2/web/global"
  28. "github.com/mhsanaei/3x-ui/v2/web/locale"
  29. "github.com/mhsanaei/3x-ui/v2/xray"
  30. "github.com/google/uuid"
  31. "github.com/mymmrac/telego"
  32. th "github.com/mymmrac/telego/telegohandler"
  33. tu "github.com/mymmrac/telego/telegoutil"
  34. "github.com/skip2/go-qrcode"
  35. "github.com/valyala/fasthttp"
  36. "github.com/valyala/fasthttp/fasthttpproxy"
  37. )
  38. var (
  39. bot *telego.Bot
  40. // botCancel stores the function to cancel the context, stopping Long Polling gracefully.
  41. botCancel context.CancelFunc
  42. // tgBotMutex protects concurrent access to botCancel variable
  43. tgBotMutex sync.Mutex
  44. // botWG waits for the OnReceive Long Polling goroutine to finish.
  45. botWG sync.WaitGroup
  46. botHandler *th.BotHandler
  47. adminIds []int64
  48. isRunning bool
  49. hostname string
  50. hashStorage *global.HashStorage
  51. // Performance improvements
  52. messageWorkerPool chan struct{} // Semaphore for limiting concurrent message processing
  53. optimizedHTTPClient *http.Client // HTTP client with connection pooling and timeouts
  54. // Simple cache for frequently accessed data
  55. statusCache struct {
  56. data *Status
  57. timestamp time.Time
  58. mutex sync.RWMutex
  59. }
  60. serverStatsCache struct {
  61. data string
  62. timestamp time.Time
  63. mutex sync.RWMutex
  64. }
  65. // clients data to adding new client
  66. receiver_inbound_ID int
  67. client_Id string
  68. client_Flow string
  69. client_Email string
  70. client_LimitIP int
  71. client_TotalGB int64
  72. client_ExpiryTime int64
  73. client_Enable bool
  74. client_TgID string
  75. client_SubID string
  76. client_Comment string
  77. client_Reset int
  78. client_Security string
  79. client_ShPassword string
  80. client_TrPassword string
  81. client_Method string
  82. )
  83. var userStates = make(map[int64]string)
  84. // LoginStatus represents the result of a login attempt.
  85. type LoginStatus byte
  86. // Login status constants
  87. const (
  88. LoginSuccess LoginStatus = 1 // Login was successful
  89. LoginFail LoginStatus = 0 // Login failed
  90. EmptyTelegramUserID = int64(0) // Default value for empty Telegram user ID
  91. )
  92. // Tgbot provides business logic for Telegram bot integration.
  93. // It handles bot commands, user interactions, and status reporting via Telegram.
  94. type Tgbot struct {
  95. inboundService InboundService
  96. settingService SettingService
  97. serverService ServerService
  98. xrayService XrayService
  99. lastStatus *Status
  100. }
  101. // NewTgbot creates a new Tgbot instance.
  102. func (t *Tgbot) NewTgbot() *Tgbot {
  103. return new(Tgbot)
  104. }
  105. // I18nBot retrieves a localized message for the bot interface.
  106. func (t *Tgbot) I18nBot(name string, params ...string) string {
  107. return locale.I18n(locale.Bot, name, params...)
  108. }
  109. // GetHashStorage returns the hash storage instance for callback queries.
  110. func (t *Tgbot) GetHashStorage() *global.HashStorage {
  111. return hashStorage
  112. }
  113. // getCachedStatus returns cached server status if it's fresh enough (less than 5 seconds old)
  114. func (t *Tgbot) getCachedStatus() (*Status, bool) {
  115. statusCache.mutex.RLock()
  116. defer statusCache.mutex.RUnlock()
  117. if statusCache.data != nil && time.Since(statusCache.timestamp) < 5*time.Second {
  118. return statusCache.data, true
  119. }
  120. return nil, false
  121. }
  122. // setCachedStatus updates the status cache
  123. func (t *Tgbot) setCachedStatus(status *Status) {
  124. statusCache.mutex.Lock()
  125. defer statusCache.mutex.Unlock()
  126. statusCache.data = status
  127. statusCache.timestamp = time.Now()
  128. }
  129. // getCachedServerStats returns cached server stats if it's fresh enough (less than 10 seconds old)
  130. func (t *Tgbot) getCachedServerStats() (string, bool) {
  131. serverStatsCache.mutex.RLock()
  132. defer serverStatsCache.mutex.RUnlock()
  133. if serverStatsCache.data != "" && time.Since(serverStatsCache.timestamp) < 10*time.Second {
  134. return serverStatsCache.data, true
  135. }
  136. return "", false
  137. }
  138. // setCachedServerStats updates the server stats cache
  139. func (t *Tgbot) setCachedServerStats(stats string) {
  140. serverStatsCache.mutex.Lock()
  141. defer serverStatsCache.mutex.Unlock()
  142. serverStatsCache.data = stats
  143. serverStatsCache.timestamp = time.Now()
  144. }
  145. // Start initializes and starts the Telegram bot with the provided translation files.
  146. func (t *Tgbot) Start(i18nFS embed.FS) error {
  147. // Initialize localizer
  148. err := locale.InitLocalizer(i18nFS, &t.settingService)
  149. if err != nil {
  150. return err
  151. }
  152. // If Start is called again (e.g. during reload), ensure any previous long-polling
  153. // loop is stopped before creating a new bot / receiver.
  154. StopBot()
  155. // Initialize hash storage to store callback queries
  156. hashStorage = global.NewHashStorage(20 * time.Minute)
  157. // Initialize worker pool for concurrent message processing (max 10 concurrent handlers)
  158. messageWorkerPool = make(chan struct{}, 10)
  159. // Initialize optimized HTTP client with connection pooling
  160. optimizedHTTPClient = &http.Client{
  161. Timeout: 15 * time.Second,
  162. Transport: &http.Transport{
  163. MaxIdleConns: 100,
  164. MaxIdleConnsPerHost: 10,
  165. IdleConnTimeout: 30 * time.Second,
  166. DisableKeepAlives: false,
  167. },
  168. }
  169. t.SetHostname()
  170. // Get Telegram bot token
  171. tgBotToken, err := t.settingService.GetTgBotToken()
  172. if err != nil || tgBotToken == "" {
  173. logger.Warning("Failed to get Telegram bot token:", err)
  174. return err
  175. }
  176. // Get Telegram bot chat ID(s)
  177. tgBotID, err := t.settingService.GetTgBotChatId()
  178. if err != nil {
  179. logger.Warning("Failed to get Telegram bot chat ID:", err)
  180. return err
  181. }
  182. parsedAdminIds := make([]int64, 0)
  183. // Parse admin IDs from comma-separated string
  184. if tgBotID != "" {
  185. for _, adminID := range strings.Split(tgBotID, ",") {
  186. id, err := strconv.ParseInt(adminID, 10, 64)
  187. if err != nil {
  188. logger.Warning("Failed to parse admin ID from Telegram bot chat ID:", err)
  189. return err
  190. }
  191. parsedAdminIds = append(parsedAdminIds, int64(id))
  192. }
  193. }
  194. tgBotMutex.Lock()
  195. adminIds = parsedAdminIds
  196. tgBotMutex.Unlock()
  197. // Get Telegram bot proxy URL
  198. tgBotProxy, err := t.settingService.GetTgBotProxy()
  199. if err != nil {
  200. logger.Warning("Failed to get Telegram bot proxy URL:", err)
  201. }
  202. // Get Telegram bot API server URL
  203. tgBotAPIServer, err := t.settingService.GetTgBotAPIServer()
  204. if err != nil {
  205. logger.Warning("Failed to get Telegram bot API server URL:", err)
  206. }
  207. // Create new Telegram bot instance
  208. bot, err = t.NewBot(tgBotToken, tgBotProxy, tgBotAPIServer)
  209. if err != nil {
  210. logger.Error("Failed to initialize Telegram bot API:", err)
  211. return err
  212. }
  213. // After bot initialization, set up bot commands with localized descriptions
  214. err = bot.SetMyCommands(context.Background(), &telego.SetMyCommandsParams{
  215. Commands: []telego.BotCommand{
  216. {Command: "start", Description: t.I18nBot("tgbot.commands.startDesc")},
  217. {Command: "help", Description: t.I18nBot("tgbot.commands.helpDesc")},
  218. {Command: "status", Description: t.I18nBot("tgbot.commands.statusDesc")},
  219. {Command: "id", Description: t.I18nBot("tgbot.commands.idDesc")},
  220. },
  221. })
  222. if err != nil {
  223. logger.Warning("Failed to set bot commands:", err)
  224. }
  225. // Start receiving Telegram bot messages
  226. tgBotMutex.Lock()
  227. alreadyRunning := isRunning || botCancel != nil
  228. tgBotMutex.Unlock()
  229. if !alreadyRunning {
  230. logger.Info("Telegram bot receiver started")
  231. go t.OnReceive()
  232. }
  233. return nil
  234. }
  235. // createRobustFastHTTPClient creates a fasthttp.Client with proper connection handling
  236. func (t *Tgbot) createRobustFastHTTPClient(proxyUrl string) *fasthttp.Client {
  237. client := &fasthttp.Client{
  238. // Connection timeouts
  239. ReadTimeout: 30 * time.Second,
  240. WriteTimeout: 30 * time.Second,
  241. MaxIdleConnDuration: 60 * time.Second,
  242. MaxConnDuration: 0, // unlimited, but controlled by MaxIdleConnDuration
  243. MaxIdemponentCallAttempts: 3,
  244. ReadBufferSize: 4096,
  245. WriteBufferSize: 4096,
  246. MaxConnsPerHost: 100,
  247. MaxConnWaitTimeout: 10 * time.Second,
  248. DisableHeaderNamesNormalizing: false,
  249. DisablePathNormalizing: false,
  250. // Retry on connection errors
  251. RetryIf: func(request *fasthttp.Request) bool {
  252. // Retry on connection errors for GET requests
  253. return string(request.Header.Method()) == "GET" || string(request.Header.Method()) == "POST"
  254. },
  255. }
  256. // Set proxy if provided
  257. if proxyUrl != "" {
  258. client.Dial = fasthttpproxy.FasthttpSocksDialer(proxyUrl)
  259. }
  260. return client
  261. }
  262. // NewBot creates a new Telegram bot instance with optional proxy and API server settings.
  263. func (t *Tgbot) NewBot(token string, proxyUrl string, apiServerUrl string) (*telego.Bot, error) {
  264. // Validate proxy URL if provided
  265. if proxyUrl != "" {
  266. if !strings.HasPrefix(proxyUrl, "socks5://") {
  267. logger.Warning("Invalid socks5 URL, ignoring proxy")
  268. proxyUrl = "" // Clear invalid proxy
  269. } else {
  270. _, err := url.Parse(proxyUrl)
  271. if err != nil {
  272. logger.Warningf("Can't parse proxy URL, ignoring proxy: %v", err)
  273. proxyUrl = ""
  274. }
  275. }
  276. }
  277. // Validate API server URL if provided
  278. if apiServerUrl != "" {
  279. if !strings.HasPrefix(apiServerUrl, "http") {
  280. logger.Warning("Invalid http(s) URL for API server, using default")
  281. apiServerUrl = ""
  282. } else {
  283. _, err := url.Parse(apiServerUrl)
  284. if err != nil {
  285. logger.Warningf("Can't parse API server URL, using default: %v", err)
  286. apiServerUrl = ""
  287. }
  288. }
  289. }
  290. // Create robust fasthttp client
  291. client := t.createRobustFastHTTPClient(proxyUrl)
  292. // Build bot options
  293. var options []telego.BotOption
  294. options = append(options, telego.WithFastHTTPClient(client))
  295. if apiServerUrl != "" {
  296. options = append(options, telego.WithAPIServer(apiServerUrl))
  297. }
  298. return telego.NewBot(token, options...)
  299. }
  300. // IsRunning checks if the Telegram bot is currently running.
  301. func (t *Tgbot) IsRunning() bool {
  302. tgBotMutex.Lock()
  303. defer tgBotMutex.Unlock()
  304. return isRunning
  305. }
  306. // SetHostname sets the hostname for the bot.
  307. func (t *Tgbot) SetHostname() {
  308. host, err := os.Hostname()
  309. if err != nil {
  310. logger.Error("get hostname error:", err)
  311. hostname = ""
  312. return
  313. }
  314. hostname = host
  315. }
  316. // Stop safely stops the Telegram bot's Long Polling operation.
  317. // This method now calls the global StopBot function and cleans up other resources.
  318. func (t *Tgbot) Stop() {
  319. StopBot()
  320. logger.Info("Stop Telegram receiver ...")
  321. tgBotMutex.Lock()
  322. adminIds = nil
  323. tgBotMutex.Unlock()
  324. }
  325. // StopBot safely stops the Telegram bot's Long Polling operation by cancelling its context.
  326. // This is the global function called from main.go's signal handler and t.Stop().
  327. func StopBot() {
  328. // Don't hold the mutex while cancelling/waiting.
  329. tgBotMutex.Lock()
  330. cancel := botCancel
  331. botCancel = nil
  332. handler := botHandler
  333. botHandler = nil
  334. isRunning = false
  335. tgBotMutex.Unlock()
  336. if handler != nil {
  337. handler.Stop()
  338. }
  339. if cancel != nil {
  340. logger.Info("Sending cancellation signal to Telegram bot...")
  341. // Cancels the context passed to UpdatesViaLongPolling; this closes updates channel
  342. // and lets botHandler.Start() exit cleanly.
  343. cancel()
  344. botWG.Wait()
  345. logger.Info("Telegram bot successfully stopped.")
  346. }
  347. }
  348. // encodeQuery encodes the query string if it's longer than 64 characters.
  349. func (t *Tgbot) encodeQuery(query string) string {
  350. // NOTE: we only need to hash for more than 64 chars
  351. if len(query) <= 64 {
  352. return query
  353. }
  354. return hashStorage.SaveHash(query)
  355. }
  356. // decodeQuery decodes a hashed query string back to its original form.
  357. func (t *Tgbot) decodeQuery(query string) (string, error) {
  358. if !hashStorage.IsMD5(query) {
  359. return query, nil
  360. }
  361. decoded, exists := hashStorage.GetValue(query)
  362. if !exists {
  363. return "", common.NewError("hash not found in storage!")
  364. }
  365. return decoded, nil
  366. }
  367. // OnReceive starts the message receiving loop for the Telegram bot.
  368. func (t *Tgbot) OnReceive() {
  369. params := telego.GetUpdatesParams{
  370. Timeout: 20, // Reduced timeout to detect connection issues faster
  371. }
  372. // Strict singleton: never start a second long-polling loop.
  373. tgBotMutex.Lock()
  374. if botCancel != nil || isRunning {
  375. tgBotMutex.Unlock()
  376. logger.Warning("TgBot OnReceive called while already running; ignoring.")
  377. return
  378. }
  379. ctx, cancel := context.WithCancel(context.Background())
  380. botCancel = cancel
  381. isRunning = true
  382. // Add to WaitGroup before releasing the lock so StopBot() can't return
  383. // before this receiver goroutine is accounted for.
  384. botWG.Add(1)
  385. tgBotMutex.Unlock()
  386. // Get updates channel using the context with shorter timeout for better error recovery
  387. updates, _ := bot.UpdatesViaLongPolling(ctx, &params)
  388. go func() {
  389. defer botWG.Done()
  390. h, _ := th.NewBotHandler(bot, updates)
  391. tgBotMutex.Lock()
  392. botHandler = h
  393. tgBotMutex.Unlock()
  394. h.HandleMessage(func(ctx *th.Context, message telego.Message) error {
  395. delete(userStates, message.Chat.ID)
  396. t.SendMsgToTgbot(message.Chat.ID, t.I18nBot("tgbot.keyboardClosed"), tu.ReplyKeyboardRemove())
  397. return nil
  398. }, th.TextEqual(t.I18nBot("tgbot.buttons.closeKeyboard")))
  399. h.HandleMessage(func(ctx *th.Context, message telego.Message) error {
  400. // Use goroutine with worker pool for concurrent command processing
  401. go func() {
  402. messageWorkerPool <- struct{}{} // Acquire worker
  403. defer func() { <-messageWorkerPool }() // Release worker
  404. delete(userStates, message.Chat.ID)
  405. t.answerCommand(&message, message.Chat.ID, checkAdmin(message.From.ID))
  406. }()
  407. return nil
  408. }, th.AnyCommand())
  409. h.HandleCallbackQuery(func(ctx *th.Context, query telego.CallbackQuery) error {
  410. // Use goroutine with worker pool for concurrent callback processing
  411. go func() {
  412. messageWorkerPool <- struct{}{} // Acquire worker
  413. defer func() { <-messageWorkerPool }() // Release worker
  414. delete(userStates, query.Message.GetChat().ID)
  415. t.answerCallback(&query, checkAdmin(query.From.ID))
  416. }()
  417. return nil
  418. }, th.AnyCallbackQueryWithMessage())
  419. h.HandleMessage(func(ctx *th.Context, message telego.Message) error {
  420. if userState, exists := userStates[message.Chat.ID]; exists {
  421. switch userState {
  422. case "awaiting_id":
  423. if client_Id == strings.TrimSpace(message.Text) {
  424. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.using_default_value"), 3, tu.ReplyKeyboardRemove())
  425. delete(userStates, message.Chat.ID)
  426. inbound, _ := t.inboundService.GetInbound(receiver_inbound_ID)
  427. message_text, _ := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  428. t.addClient(message.Chat.ID, message_text)
  429. return nil
  430. }
  431. client_Id = strings.TrimSpace(message.Text)
  432. if t.isSingleWord(client_Id) {
  433. userStates[message.Chat.ID] = "awaiting_id"
  434. cancel_btn_markup := tu.InlineKeyboard(
  435. tu.InlineKeyboardRow(
  436. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.use_default")).WithCallbackData("add_client_default_info"),
  437. ),
  438. )
  439. t.SendMsgToTgbot(message.Chat.ID, t.I18nBot("tgbot.messages.incorrect_input"), cancel_btn_markup)
  440. } else {
  441. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.received_id"), 3, tu.ReplyKeyboardRemove())
  442. delete(userStates, message.Chat.ID)
  443. inbound, _ := t.inboundService.GetInbound(receiver_inbound_ID)
  444. message_text, _ := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  445. t.addClient(message.Chat.ID, message_text)
  446. }
  447. case "awaiting_password_tr":
  448. if client_TrPassword == strings.TrimSpace(message.Text) {
  449. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.using_default_value"), 3, tu.ReplyKeyboardRemove())
  450. delete(userStates, message.Chat.ID)
  451. return nil
  452. }
  453. client_TrPassword = strings.TrimSpace(message.Text)
  454. if t.isSingleWord(client_TrPassword) {
  455. userStates[message.Chat.ID] = "awaiting_password_tr"
  456. cancel_btn_markup := tu.InlineKeyboard(
  457. tu.InlineKeyboardRow(
  458. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.use_default")).WithCallbackData("add_client_default_info"),
  459. ),
  460. )
  461. t.SendMsgToTgbot(message.Chat.ID, t.I18nBot("tgbot.messages.incorrect_input"), cancel_btn_markup)
  462. } else {
  463. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.received_password"), 3, tu.ReplyKeyboardRemove())
  464. delete(userStates, message.Chat.ID)
  465. inbound, _ := t.inboundService.GetInbound(receiver_inbound_ID)
  466. message_text, _ := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  467. t.addClient(message.Chat.ID, message_text)
  468. }
  469. case "awaiting_password_sh":
  470. if client_ShPassword == strings.TrimSpace(message.Text) {
  471. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.using_default_value"), 3, tu.ReplyKeyboardRemove())
  472. delete(userStates, message.Chat.ID)
  473. return nil
  474. }
  475. client_ShPassword = strings.TrimSpace(message.Text)
  476. if t.isSingleWord(client_ShPassword) {
  477. userStates[message.Chat.ID] = "awaiting_password_sh"
  478. cancel_btn_markup := tu.InlineKeyboard(
  479. tu.InlineKeyboardRow(
  480. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.use_default")).WithCallbackData("add_client_default_info"),
  481. ),
  482. )
  483. t.SendMsgToTgbot(message.Chat.ID, t.I18nBot("tgbot.messages.incorrect_input"), cancel_btn_markup)
  484. } else {
  485. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.received_password"), 3, tu.ReplyKeyboardRemove())
  486. delete(userStates, message.Chat.ID)
  487. inbound, _ := t.inboundService.GetInbound(receiver_inbound_ID)
  488. message_text, _ := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  489. t.addClient(message.Chat.ID, message_text)
  490. }
  491. case "awaiting_email":
  492. if client_Email == strings.TrimSpace(message.Text) {
  493. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.using_default_value"), 3, tu.ReplyKeyboardRemove())
  494. delete(userStates, message.Chat.ID)
  495. return nil
  496. }
  497. client_Email = strings.TrimSpace(message.Text)
  498. if t.isSingleWord(client_Email) {
  499. userStates[message.Chat.ID] = "awaiting_email"
  500. cancel_btn_markup := tu.InlineKeyboard(
  501. tu.InlineKeyboardRow(
  502. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.use_default")).WithCallbackData("add_client_default_info"),
  503. ),
  504. )
  505. t.SendMsgToTgbot(message.Chat.ID, t.I18nBot("tgbot.messages.incorrect_input"), cancel_btn_markup)
  506. } else {
  507. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.received_email"), 3, tu.ReplyKeyboardRemove())
  508. delete(userStates, message.Chat.ID)
  509. inbound, _ := t.inboundService.GetInbound(receiver_inbound_ID)
  510. message_text, _ := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  511. t.addClient(message.Chat.ID, message_text)
  512. }
  513. case "awaiting_comment":
  514. if client_Comment == strings.TrimSpace(message.Text) {
  515. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.using_default_value"), 3, tu.ReplyKeyboardRemove())
  516. delete(userStates, message.Chat.ID)
  517. return nil
  518. }
  519. client_Comment = strings.TrimSpace(message.Text)
  520. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.received_comment"), 3, tu.ReplyKeyboardRemove())
  521. delete(userStates, message.Chat.ID)
  522. inbound, _ := t.inboundService.GetInbound(receiver_inbound_ID)
  523. message_text, _ := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  524. t.addClient(message.Chat.ID, message_text)
  525. }
  526. } else {
  527. if message.UsersShared != nil {
  528. if checkAdmin(message.From.ID) {
  529. for _, sharedUser := range message.UsersShared.Users {
  530. userID := sharedUser.UserID
  531. needRestart, err := t.inboundService.SetClientTelegramUserID(message.UsersShared.RequestID, userID)
  532. if needRestart {
  533. t.xrayService.SetToNeedRestart()
  534. }
  535. output := ""
  536. if err != nil {
  537. output += t.I18nBot("tgbot.messages.selectUserFailed")
  538. } else {
  539. output += t.I18nBot("tgbot.messages.userSaved")
  540. }
  541. t.SendMsgToTgbot(message.Chat.ID, output, tu.ReplyKeyboardRemove())
  542. }
  543. } else {
  544. t.SendMsgToTgbot(message.Chat.ID, t.I18nBot("tgbot.noResult"), tu.ReplyKeyboardRemove())
  545. }
  546. }
  547. }
  548. return nil
  549. }, th.AnyMessage())
  550. h.Start()
  551. }()
  552. }
  553. // answerCommand processes incoming command messages from Telegram users.
  554. func (t *Tgbot) answerCommand(message *telego.Message, chatId int64, isAdmin bool) {
  555. msg, onlyMessage := "", false
  556. command, _, commandArgs := tu.ParseCommand(message.Text)
  557. // Helper function to handle unknown commands.
  558. handleUnknownCommand := func() {
  559. msg += t.I18nBot("tgbot.commands.unknown")
  560. }
  561. // Handle the command.
  562. switch command {
  563. case "help":
  564. msg += t.I18nBot("tgbot.commands.help")
  565. msg += t.I18nBot("tgbot.commands.pleaseChoose")
  566. case "start":
  567. msg += t.I18nBot("tgbot.commands.start", "Firstname=="+html.EscapeString(message.From.FirstName))
  568. if isAdmin {
  569. msg += t.I18nBot("tgbot.commands.welcome", "Hostname=="+hostname)
  570. }
  571. msg += "\n\n" + t.I18nBot("tgbot.commands.pleaseChoose")
  572. case "status":
  573. onlyMessage = true
  574. msg += t.I18nBot("tgbot.commands.status")
  575. case "id":
  576. onlyMessage = true
  577. msg += t.I18nBot("tgbot.commands.getID", "ID=="+strconv.FormatInt(message.From.ID, 10))
  578. case "usage":
  579. onlyMessage = true
  580. if len(commandArgs) > 0 {
  581. if isAdmin {
  582. t.searchClient(chatId, commandArgs[0])
  583. } else {
  584. t.getClientUsage(chatId, int64(message.From.ID), commandArgs[0])
  585. }
  586. } else {
  587. msg += t.I18nBot("tgbot.commands.usage")
  588. }
  589. case "inbound":
  590. onlyMessage = true
  591. if isAdmin && len(commandArgs) > 0 {
  592. t.searchInbound(chatId, commandArgs[0])
  593. } else {
  594. handleUnknownCommand()
  595. }
  596. case "restart":
  597. onlyMessage = true
  598. if isAdmin {
  599. if len(commandArgs) == 0 {
  600. if t.xrayService.IsXrayRunning() {
  601. err := t.xrayService.RestartXray(true)
  602. if err != nil {
  603. msg += t.I18nBot("tgbot.commands.restartFailed", "Error=="+err.Error())
  604. } else {
  605. msg += t.I18nBot("tgbot.commands.restartSuccess")
  606. }
  607. } else {
  608. msg += t.I18nBot("tgbot.commands.xrayNotRunning")
  609. }
  610. } else {
  611. handleUnknownCommand()
  612. msg += t.I18nBot("tgbot.commands.restartUsage")
  613. }
  614. } else {
  615. handleUnknownCommand()
  616. }
  617. default:
  618. handleUnknownCommand()
  619. }
  620. if msg != "" {
  621. t.sendResponse(chatId, msg, onlyMessage, isAdmin)
  622. }
  623. }
  624. // sendResponse sends the response message based on the onlyMessage flag.
  625. func (t *Tgbot) sendResponse(chatId int64, msg string, onlyMessage, isAdmin bool) {
  626. if onlyMessage {
  627. t.SendMsgToTgbot(chatId, msg)
  628. } else {
  629. t.SendAnswer(chatId, msg, isAdmin)
  630. }
  631. }
  632. // randomLowerAndNum generates a random string of lowercase letters and numbers.
  633. func (t *Tgbot) randomLowerAndNum(length int) string {
  634. charset := "abcdefghijklmnopqrstuvwxyz0123456789"
  635. bytes := make([]byte, length)
  636. for i := range bytes {
  637. randomIndex, _ := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
  638. bytes[i] = charset[randomIndex.Int64()]
  639. }
  640. return string(bytes)
  641. }
  642. // randomShadowSocksPassword generates a random password for Shadowsocks.
  643. func (t *Tgbot) randomShadowSocksPassword() string {
  644. array := make([]byte, 32)
  645. _, err := rand.Read(array)
  646. if err != nil {
  647. return t.randomLowerAndNum(32)
  648. }
  649. return base64.StdEncoding.EncodeToString(array)
  650. }
  651. // answerCallback processes callback queries from inline keyboards.
  652. func (t *Tgbot) answerCallback(callbackQuery *telego.CallbackQuery, isAdmin bool) {
  653. chatId := callbackQuery.Message.GetChat().ID
  654. if isAdmin {
  655. // get query from hash storage
  656. decodedQuery, err := t.decodeQuery(callbackQuery.Data)
  657. if err != nil {
  658. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.noQuery"))
  659. return
  660. }
  661. dataArray := strings.Split(decodedQuery, " ")
  662. if len(dataArray) >= 2 && len(dataArray[1]) > 0 {
  663. email := dataArray[1]
  664. switch dataArray[0] {
  665. case "get_clients_for_sub":
  666. inboundId := dataArray[1]
  667. inboundIdInt, err := strconv.Atoi(inboundId)
  668. if err != nil {
  669. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  670. return
  671. }
  672. clientsKB, err := t.getInboundClientsFor(inboundIdInt, "client_sub_links")
  673. if err != nil {
  674. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  675. return
  676. }
  677. inbound, _ := t.inboundService.GetInbound(inboundIdInt)
  678. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.chooseClient", "Inbound=="+inbound.Remark), clientsKB)
  679. case "get_clients_for_individual":
  680. inboundId := dataArray[1]
  681. inboundIdInt, err := strconv.Atoi(inboundId)
  682. if err != nil {
  683. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  684. return
  685. }
  686. clientsKB, err := t.getInboundClientsFor(inboundIdInt, "client_individual_links")
  687. if err != nil {
  688. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  689. return
  690. }
  691. inbound, _ := t.inboundService.GetInbound(inboundIdInt)
  692. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.chooseClient", "Inbound=="+inbound.Remark), clientsKB)
  693. case "get_clients_for_qr":
  694. inboundId := dataArray[1]
  695. inboundIdInt, err := strconv.Atoi(inboundId)
  696. if err != nil {
  697. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  698. return
  699. }
  700. clientsKB, err := t.getInboundClientsFor(inboundIdInt, "client_qr_links")
  701. if err != nil {
  702. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  703. return
  704. }
  705. inbound, _ := t.inboundService.GetInbound(inboundIdInt)
  706. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.chooseClient", "Inbound=="+inbound.Remark), clientsKB)
  707. case "client_sub_links":
  708. t.sendClientSubLinks(chatId, email)
  709. return
  710. case "client_individual_links":
  711. t.sendClientIndividualLinks(chatId, email)
  712. return
  713. case "client_qr_links":
  714. t.sendClientQRLinks(chatId, email)
  715. return
  716. case "client_get_usage":
  717. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.messages.email", "Email=="+email))
  718. t.searchClient(chatId, email)
  719. case "client_refresh":
  720. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.clientRefreshSuccess", "Email=="+email))
  721. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  722. case "client_cancel":
  723. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.canceled", "Email=="+email))
  724. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  725. case "ips_refresh":
  726. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.IpRefreshSuccess", "Email=="+email))
  727. t.searchClientIps(chatId, email, callbackQuery.Message.GetMessageID())
  728. case "ips_cancel":
  729. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.canceled", "Email=="+email))
  730. t.searchClientIps(chatId, email, callbackQuery.Message.GetMessageID())
  731. case "tgid_refresh":
  732. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.TGIdRefreshSuccess", "Email=="+email))
  733. t.clientTelegramUserInfo(chatId, email, callbackQuery.Message.GetMessageID())
  734. case "tgid_cancel":
  735. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.canceled", "Email=="+email))
  736. t.clientTelegramUserInfo(chatId, email, callbackQuery.Message.GetMessageID())
  737. case "reset_traffic":
  738. inlineKeyboard := tu.InlineKeyboard(
  739. tu.InlineKeyboardRow(
  740. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancelReset")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  741. ),
  742. tu.InlineKeyboardRow(
  743. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmResetTraffic")).WithCallbackData(t.encodeQuery("reset_traffic_c "+email)),
  744. ),
  745. )
  746. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  747. case "reset_traffic_c":
  748. err := t.inboundService.ResetClientTrafficByEmail(email)
  749. if err == nil {
  750. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.resetTrafficSuccess", "Email=="+email))
  751. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  752. } else {
  753. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  754. }
  755. case "limit_traffic":
  756. inlineKeyboard := tu.InlineKeyboard(
  757. tu.InlineKeyboardRow(
  758. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  759. ),
  760. tu.InlineKeyboardRow(
  761. tu.InlineKeyboardButton(t.I18nBot("tgbot.unlimited")).WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 0")),
  762. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.custom")).WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" 0")),
  763. ),
  764. tu.InlineKeyboardRow(
  765. tu.InlineKeyboardButton("1 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 1")),
  766. tu.InlineKeyboardButton("5 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 5")),
  767. tu.InlineKeyboardButton("10 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 10")),
  768. ),
  769. tu.InlineKeyboardRow(
  770. tu.InlineKeyboardButton("20 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 20")),
  771. tu.InlineKeyboardButton("30 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 30")),
  772. tu.InlineKeyboardButton("40 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 40")),
  773. ),
  774. tu.InlineKeyboardRow(
  775. tu.InlineKeyboardButton("50 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 50")),
  776. tu.InlineKeyboardButton("60 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 60")),
  777. tu.InlineKeyboardButton("80 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 80")),
  778. ),
  779. tu.InlineKeyboardRow(
  780. tu.InlineKeyboardButton("100 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 100")),
  781. tu.InlineKeyboardButton("150 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 150")),
  782. tu.InlineKeyboardButton("200 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 200")),
  783. ),
  784. )
  785. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  786. case "limit_traffic_c":
  787. if len(dataArray) == 3 {
  788. limitTraffic, err := strconv.Atoi(dataArray[2])
  789. if err == nil {
  790. needRestart, err := t.inboundService.ResetClientTrafficLimitByEmail(email, limitTraffic)
  791. if needRestart {
  792. t.xrayService.SetToNeedRestart()
  793. }
  794. if err == nil {
  795. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.setTrafficLimitSuccess", "Email=="+email))
  796. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  797. return
  798. }
  799. }
  800. }
  801. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  802. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  803. case "limit_traffic_in":
  804. if len(dataArray) >= 3 {
  805. oldInputNumber, err := strconv.Atoi(dataArray[2])
  806. inputNumber := oldInputNumber
  807. if err == nil {
  808. if len(dataArray) == 4 {
  809. num, err := strconv.Atoi(dataArray[3])
  810. if err == nil {
  811. switch num {
  812. case -2:
  813. inputNumber = 0
  814. case -1:
  815. if inputNumber > 0 {
  816. inputNumber = (inputNumber / 10)
  817. }
  818. default:
  819. inputNumber = (inputNumber * 10) + num
  820. }
  821. }
  822. if inputNumber == oldInputNumber {
  823. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  824. return
  825. }
  826. if inputNumber >= 999999 {
  827. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  828. return
  829. }
  830. }
  831. inlineKeyboard := tu.InlineKeyboard(
  832. tu.InlineKeyboardRow(
  833. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  834. ),
  835. tu.InlineKeyboardRow(
  836. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmNumberAdd", "Num=="+strconv.Itoa(inputNumber))).WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" "+strconv.Itoa(inputNumber))),
  837. ),
  838. tu.InlineKeyboardRow(
  839. tu.InlineKeyboardButton("1").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 1")),
  840. tu.InlineKeyboardButton("2").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 2")),
  841. tu.InlineKeyboardButton("3").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 3")),
  842. ),
  843. tu.InlineKeyboardRow(
  844. tu.InlineKeyboardButton("4").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 4")),
  845. tu.InlineKeyboardButton("5").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 5")),
  846. tu.InlineKeyboardButton("6").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 6")),
  847. ),
  848. tu.InlineKeyboardRow(
  849. tu.InlineKeyboardButton("7").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 7")),
  850. tu.InlineKeyboardButton("8").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 8")),
  851. tu.InlineKeyboardButton("9").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 9")),
  852. ),
  853. tu.InlineKeyboardRow(
  854. tu.InlineKeyboardButton("🔄").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" -2")),
  855. tu.InlineKeyboardButton("0").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 0")),
  856. tu.InlineKeyboardButton("⬅️").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" -1")),
  857. ),
  858. )
  859. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  860. return
  861. }
  862. }
  863. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  864. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  865. case "add_client_limit_traffic_c":
  866. limitTraffic, _ := strconv.ParseInt(dataArray[1], 10, 64)
  867. client_TotalGB = limitTraffic * 1024 * 1024 * 1024
  868. messageId := callbackQuery.Message.GetMessageID()
  869. inbound, err := t.inboundService.GetInbound(receiver_inbound_ID)
  870. if err != nil {
  871. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  872. return
  873. }
  874. message_text, err := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  875. if err != nil {
  876. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  877. return
  878. }
  879. t.addClient(callbackQuery.Message.GetChat().ID, message_text, messageId)
  880. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  881. case "add_client_limit_traffic_in":
  882. if len(dataArray) >= 2 {
  883. oldInputNumber, err := strconv.Atoi(dataArray[1])
  884. inputNumber := oldInputNumber
  885. if err == nil {
  886. if len(dataArray) == 3 {
  887. num, err := strconv.Atoi(dataArray[2])
  888. if err == nil {
  889. switch num {
  890. case -2:
  891. inputNumber = 0
  892. case -1:
  893. if inputNumber > 0 {
  894. inputNumber = (inputNumber / 10)
  895. }
  896. default:
  897. inputNumber = (inputNumber * 10) + num
  898. }
  899. }
  900. if inputNumber == oldInputNumber {
  901. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  902. return
  903. }
  904. if inputNumber >= 999999 {
  905. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  906. return
  907. }
  908. }
  909. inlineKeyboard := tu.InlineKeyboard(
  910. tu.InlineKeyboardRow(
  911. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("add_client_default_traffic_exp")),
  912. ),
  913. tu.InlineKeyboardRow(
  914. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmNumberAdd", "Num=="+strconv.Itoa(inputNumber))).WithCallbackData(t.encodeQuery("add_client_limit_traffic_c "+strconv.Itoa(inputNumber))),
  915. ),
  916. tu.InlineKeyboardRow(
  917. tu.InlineKeyboardButton("1").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 1")),
  918. tu.InlineKeyboardButton("2").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 2")),
  919. tu.InlineKeyboardButton("3").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 3")),
  920. ),
  921. tu.InlineKeyboardRow(
  922. tu.InlineKeyboardButton("4").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 4")),
  923. tu.InlineKeyboardButton("5").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 5")),
  924. tu.InlineKeyboardButton("6").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 6")),
  925. ),
  926. tu.InlineKeyboardRow(
  927. tu.InlineKeyboardButton("7").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 7")),
  928. tu.InlineKeyboardButton("8").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 8")),
  929. tu.InlineKeyboardButton("9").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 9")),
  930. ),
  931. tu.InlineKeyboardRow(
  932. tu.InlineKeyboardButton("🔄").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" -2")),
  933. tu.InlineKeyboardButton("0").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 0")),
  934. tu.InlineKeyboardButton("⬅️").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" -1")),
  935. ),
  936. )
  937. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  938. return
  939. }
  940. }
  941. case "reset_exp":
  942. inlineKeyboard := tu.InlineKeyboard(
  943. tu.InlineKeyboardRow(
  944. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancelReset")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  945. ),
  946. tu.InlineKeyboardRow(
  947. tu.InlineKeyboardButton(t.I18nBot("tgbot.unlimited")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 0")),
  948. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.custom")).WithCallbackData(t.encodeQuery("reset_exp_in "+email+" 0")),
  949. ),
  950. tu.InlineKeyboardRow(
  951. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 7 "+t.I18nBot("tgbot.days")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 7")),
  952. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 10 "+t.I18nBot("tgbot.days")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 10")),
  953. ),
  954. tu.InlineKeyboardRow(
  955. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 14 "+t.I18nBot("tgbot.days")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 14")),
  956. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 20 "+t.I18nBot("tgbot.days")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 20")),
  957. ),
  958. tu.InlineKeyboardRow(
  959. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 1 "+t.I18nBot("tgbot.month")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 30")),
  960. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 3 "+t.I18nBot("tgbot.months")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 90")),
  961. ),
  962. tu.InlineKeyboardRow(
  963. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 6 "+t.I18nBot("tgbot.months")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 180")),
  964. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 12 "+t.I18nBot("tgbot.months")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 365")),
  965. ),
  966. )
  967. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  968. case "reset_exp_c":
  969. if len(dataArray) == 3 {
  970. days, err := strconv.ParseInt(dataArray[2], 10, 64)
  971. if err == nil {
  972. var date int64
  973. if days > 0 {
  974. traffic, err := t.inboundService.GetClientTrafficByEmail(email)
  975. if err != nil {
  976. logger.Warning(err)
  977. msg := t.I18nBot("tgbot.wentWrong")
  978. t.SendMsgToTgbot(chatId, msg)
  979. return
  980. }
  981. if traffic == nil {
  982. msg := t.I18nBot("tgbot.noResult")
  983. t.SendMsgToTgbot(chatId, msg)
  984. return
  985. }
  986. if traffic.ExpiryTime > 0 {
  987. if traffic.ExpiryTime-time.Now().Unix()*1000 < 0 {
  988. date = -int64(days * 24 * 60 * 60000)
  989. } else {
  990. date = traffic.ExpiryTime + int64(days*24*60*60000)
  991. }
  992. } else {
  993. date = traffic.ExpiryTime - int64(days*24*60*60000)
  994. }
  995. }
  996. needRestart, err := t.inboundService.ResetClientExpiryTimeByEmail(email, date)
  997. if needRestart {
  998. t.xrayService.SetToNeedRestart()
  999. }
  1000. if err == nil {
  1001. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.expireResetSuccess", "Email=="+email))
  1002. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  1003. return
  1004. }
  1005. }
  1006. }
  1007. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  1008. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  1009. case "reset_exp_in":
  1010. if len(dataArray) >= 3 {
  1011. oldInputNumber, err := strconv.Atoi(dataArray[2])
  1012. inputNumber := oldInputNumber
  1013. if err == nil {
  1014. if len(dataArray) == 4 {
  1015. num, err := strconv.Atoi(dataArray[3])
  1016. if err == nil {
  1017. switch num {
  1018. case -2:
  1019. inputNumber = 0
  1020. case -1:
  1021. if inputNumber > 0 {
  1022. inputNumber = (inputNumber / 10)
  1023. }
  1024. default:
  1025. inputNumber = (inputNumber * 10) + num
  1026. }
  1027. }
  1028. if inputNumber == oldInputNumber {
  1029. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  1030. return
  1031. }
  1032. if inputNumber >= 999999 {
  1033. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  1034. return
  1035. }
  1036. }
  1037. inlineKeyboard := tu.InlineKeyboard(
  1038. tu.InlineKeyboardRow(
  1039. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  1040. ),
  1041. tu.InlineKeyboardRow(
  1042. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmNumber", "Num=="+strconv.Itoa(inputNumber))).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" "+strconv.Itoa(inputNumber))),
  1043. ),
  1044. tu.InlineKeyboardRow(
  1045. tu.InlineKeyboardButton("1").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 1")),
  1046. tu.InlineKeyboardButton("2").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 2")),
  1047. tu.InlineKeyboardButton("3").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 3")),
  1048. ),
  1049. tu.InlineKeyboardRow(
  1050. tu.InlineKeyboardButton("4").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 4")),
  1051. tu.InlineKeyboardButton("5").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 5")),
  1052. tu.InlineKeyboardButton("6").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 6")),
  1053. ),
  1054. tu.InlineKeyboardRow(
  1055. tu.InlineKeyboardButton("7").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 7")),
  1056. tu.InlineKeyboardButton("8").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 8")),
  1057. tu.InlineKeyboardButton("9").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 9")),
  1058. ),
  1059. tu.InlineKeyboardRow(
  1060. tu.InlineKeyboardButton("🔄").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" -2")),
  1061. tu.InlineKeyboardButton("0").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 0")),
  1062. tu.InlineKeyboardButton("⬅️").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" -1")),
  1063. ),
  1064. )
  1065. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  1066. return
  1067. }
  1068. }
  1069. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  1070. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  1071. case "add_client_reset_exp_c":
  1072. client_ExpiryTime = 0
  1073. days, _ := strconv.ParseInt(dataArray[1], 10, 64)
  1074. var date int64
  1075. if client_ExpiryTime > 0 {
  1076. if client_ExpiryTime-time.Now().Unix()*1000 < 0 {
  1077. date = -int64(days * 24 * 60 * 60000)
  1078. } else {
  1079. date = client_ExpiryTime + int64(days*24*60*60000)
  1080. }
  1081. } else {
  1082. date = client_ExpiryTime - int64(days*24*60*60000)
  1083. }
  1084. client_ExpiryTime = date
  1085. messageId := callbackQuery.Message.GetMessageID()
  1086. inbound, err := t.inboundService.GetInbound(receiver_inbound_ID)
  1087. if err != nil {
  1088. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1089. return
  1090. }
  1091. message_text, err := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  1092. if err != nil {
  1093. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1094. return
  1095. }
  1096. t.addClient(callbackQuery.Message.GetChat().ID, message_text, messageId)
  1097. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  1098. case "add_client_reset_exp_in":
  1099. if len(dataArray) >= 2 {
  1100. oldInputNumber, err := strconv.Atoi(dataArray[1])
  1101. inputNumber := oldInputNumber
  1102. if err == nil {
  1103. if len(dataArray) == 3 {
  1104. num, err := strconv.Atoi(dataArray[2])
  1105. if err == nil {
  1106. switch num {
  1107. case -2:
  1108. inputNumber = 0
  1109. case -1:
  1110. if inputNumber > 0 {
  1111. inputNumber = (inputNumber / 10)
  1112. }
  1113. default:
  1114. inputNumber = (inputNumber * 10) + num
  1115. }
  1116. }
  1117. if inputNumber == oldInputNumber {
  1118. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  1119. return
  1120. }
  1121. if inputNumber >= 999999 {
  1122. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  1123. return
  1124. }
  1125. }
  1126. inlineKeyboard := tu.InlineKeyboard(
  1127. tu.InlineKeyboardRow(
  1128. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("add_client_default_traffic_exp")),
  1129. ),
  1130. tu.InlineKeyboardRow(
  1131. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmNumberAdd", "Num=="+strconv.Itoa(inputNumber))).WithCallbackData(t.encodeQuery("add_client_reset_exp_c "+strconv.Itoa(inputNumber))),
  1132. ),
  1133. tu.InlineKeyboardRow(
  1134. tu.InlineKeyboardButton("1").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 1")),
  1135. tu.InlineKeyboardButton("2").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 2")),
  1136. tu.InlineKeyboardButton("3").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 3")),
  1137. ),
  1138. tu.InlineKeyboardRow(
  1139. tu.InlineKeyboardButton("4").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 4")),
  1140. tu.InlineKeyboardButton("5").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 5")),
  1141. tu.InlineKeyboardButton("6").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 6")),
  1142. ),
  1143. tu.InlineKeyboardRow(
  1144. tu.InlineKeyboardButton("7").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 7")),
  1145. tu.InlineKeyboardButton("8").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 8")),
  1146. tu.InlineKeyboardButton("9").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 9")),
  1147. ),
  1148. tu.InlineKeyboardRow(
  1149. tu.InlineKeyboardButton("🔄").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" -2")),
  1150. tu.InlineKeyboardButton("0").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 0")),
  1151. tu.InlineKeyboardButton("⬅️").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" -1")),
  1152. ),
  1153. )
  1154. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  1155. return
  1156. }
  1157. }
  1158. case "ip_limit":
  1159. inlineKeyboard := tu.InlineKeyboard(
  1160. tu.InlineKeyboardRow(
  1161. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancelIpLimit")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  1162. ),
  1163. tu.InlineKeyboardRow(
  1164. tu.InlineKeyboardButton(t.I18nBot("tgbot.unlimited")).WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 0")),
  1165. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.custom")).WithCallbackData(t.encodeQuery("ip_limit_in "+email+" 0")),
  1166. ),
  1167. tu.InlineKeyboardRow(
  1168. tu.InlineKeyboardButton("1").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 1")),
  1169. tu.InlineKeyboardButton("2").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 2")),
  1170. ),
  1171. tu.InlineKeyboardRow(
  1172. tu.InlineKeyboardButton("3").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 3")),
  1173. tu.InlineKeyboardButton("4").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 4")),
  1174. ),
  1175. tu.InlineKeyboardRow(
  1176. tu.InlineKeyboardButton("5").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 5")),
  1177. tu.InlineKeyboardButton("6").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 6")),
  1178. tu.InlineKeyboardButton("7").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 7")),
  1179. ),
  1180. tu.InlineKeyboardRow(
  1181. tu.InlineKeyboardButton("8").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 8")),
  1182. tu.InlineKeyboardButton("9").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 9")),
  1183. tu.InlineKeyboardButton("10").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 10")),
  1184. ),
  1185. )
  1186. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  1187. case "ip_limit_c":
  1188. if len(dataArray) == 3 {
  1189. count, err := strconv.Atoi(dataArray[2])
  1190. if err == nil {
  1191. needRestart, err := t.inboundService.ResetClientIpLimitByEmail(email, count)
  1192. if needRestart {
  1193. t.xrayService.SetToNeedRestart()
  1194. }
  1195. if err == nil {
  1196. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.resetIpSuccess", "Email=="+email, "Count=="+strconv.Itoa(count)))
  1197. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  1198. return
  1199. }
  1200. }
  1201. }
  1202. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  1203. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  1204. case "ip_limit_in":
  1205. if len(dataArray) >= 3 {
  1206. oldInputNumber, err := strconv.Atoi(dataArray[2])
  1207. inputNumber := oldInputNumber
  1208. if err == nil {
  1209. if len(dataArray) == 4 {
  1210. num, err := strconv.Atoi(dataArray[3])
  1211. if err == nil {
  1212. switch num {
  1213. case -2:
  1214. inputNumber = 0
  1215. case -1:
  1216. if inputNumber > 0 {
  1217. inputNumber = (inputNumber / 10)
  1218. }
  1219. default:
  1220. inputNumber = (inputNumber * 10) + num
  1221. }
  1222. }
  1223. if inputNumber == oldInputNumber {
  1224. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  1225. return
  1226. }
  1227. if inputNumber >= 999999 {
  1228. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  1229. return
  1230. }
  1231. }
  1232. inlineKeyboard := tu.InlineKeyboard(
  1233. tu.InlineKeyboardRow(
  1234. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  1235. ),
  1236. tu.InlineKeyboardRow(
  1237. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmNumber", "Num=="+strconv.Itoa(inputNumber))).WithCallbackData(t.encodeQuery("ip_limit_c "+email+" "+strconv.Itoa(inputNumber))),
  1238. ),
  1239. tu.InlineKeyboardRow(
  1240. tu.InlineKeyboardButton("1").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 1")),
  1241. tu.InlineKeyboardButton("2").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 2")),
  1242. tu.InlineKeyboardButton("3").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 3")),
  1243. ),
  1244. tu.InlineKeyboardRow(
  1245. tu.InlineKeyboardButton("4").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 4")),
  1246. tu.InlineKeyboardButton("5").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 5")),
  1247. tu.InlineKeyboardButton("6").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 6")),
  1248. ),
  1249. tu.InlineKeyboardRow(
  1250. tu.InlineKeyboardButton("7").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 7")),
  1251. tu.InlineKeyboardButton("8").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 8")),
  1252. tu.InlineKeyboardButton("9").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 9")),
  1253. ),
  1254. tu.InlineKeyboardRow(
  1255. tu.InlineKeyboardButton("🔄").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" -2")),
  1256. tu.InlineKeyboardButton("0").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 0")),
  1257. tu.InlineKeyboardButton("⬅️").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" -1")),
  1258. ),
  1259. )
  1260. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  1261. return
  1262. }
  1263. }
  1264. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  1265. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  1266. case "add_client_ip_limit_c":
  1267. if len(dataArray) == 2 {
  1268. count, _ := strconv.Atoi(dataArray[1])
  1269. client_LimitIP = count
  1270. }
  1271. messageId := callbackQuery.Message.GetMessageID()
  1272. inbound, err := t.inboundService.GetInbound(receiver_inbound_ID)
  1273. if err != nil {
  1274. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1275. return
  1276. }
  1277. message_text, err := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  1278. if err != nil {
  1279. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1280. return
  1281. }
  1282. t.addClient(callbackQuery.Message.GetChat().ID, message_text, messageId)
  1283. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  1284. case "add_client_ip_limit_in":
  1285. if len(dataArray) >= 2 {
  1286. oldInputNumber, err := strconv.Atoi(dataArray[1])
  1287. inputNumber := oldInputNumber
  1288. if err == nil {
  1289. if len(dataArray) == 3 {
  1290. num, err := strconv.Atoi(dataArray[2])
  1291. if err == nil {
  1292. switch num {
  1293. case -2:
  1294. inputNumber = 0
  1295. case -1:
  1296. if inputNumber > 0 {
  1297. inputNumber = (inputNumber / 10)
  1298. }
  1299. default:
  1300. inputNumber = (inputNumber * 10) + num
  1301. }
  1302. }
  1303. if inputNumber == oldInputNumber {
  1304. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  1305. return
  1306. }
  1307. if inputNumber >= 999999 {
  1308. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  1309. return
  1310. }
  1311. }
  1312. inlineKeyboard := tu.InlineKeyboard(
  1313. tu.InlineKeyboardRow(
  1314. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("add_client_default_ip_limit")),
  1315. ),
  1316. tu.InlineKeyboardRow(
  1317. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmNumber", "Num=="+strconv.Itoa(inputNumber))).WithCallbackData(t.encodeQuery("add_client_ip_limit_c "+strconv.Itoa(inputNumber))),
  1318. ),
  1319. tu.InlineKeyboardRow(
  1320. tu.InlineKeyboardButton("1").WithCallbackData(t.encodeQuery("add_client_ip_limit_in "+strconv.Itoa(inputNumber)+" 1")),
  1321. tu.InlineKeyboardButton("2").WithCallbackData(t.encodeQuery("add_client_ip_limit_in "+strconv.Itoa(inputNumber)+" 2")),
  1322. tu.InlineKeyboardButton("3").WithCallbackData(t.encodeQuery("add_client_ip_limit_in "+strconv.Itoa(inputNumber)+" 3")),
  1323. ),
  1324. tu.InlineKeyboardRow(
  1325. tu.InlineKeyboardButton("4").WithCallbackData(t.encodeQuery("add_client_ip_limit_in "+strconv.Itoa(inputNumber)+" 4")),
  1326. tu.InlineKeyboardButton("5").WithCallbackData(t.encodeQuery("add_client_ip_limit_in "+strconv.Itoa(inputNumber)+" 5")),
  1327. tu.InlineKeyboardButton("6").WithCallbackData(t.encodeQuery("add_client_ip_limit_in "+strconv.Itoa(inputNumber)+" 6")),
  1328. ),
  1329. tu.InlineKeyboardRow(
  1330. tu.InlineKeyboardButton("7").WithCallbackData(t.encodeQuery("add_client_ip_limit_in "+strconv.Itoa(inputNumber)+" 7")),
  1331. tu.InlineKeyboardButton("8").WithCallbackData(t.encodeQuery("add_client_ip_limit_in "+strconv.Itoa(inputNumber)+" 8")),
  1332. tu.InlineKeyboardButton("9").WithCallbackData(t.encodeQuery("add_client_ip_limit_in "+strconv.Itoa(inputNumber)+" 9")),
  1333. ),
  1334. tu.InlineKeyboardRow(
  1335. tu.InlineKeyboardButton("🔄").WithCallbackData(t.encodeQuery("add_client_ip_limit_in "+strconv.Itoa(inputNumber)+" -2")),
  1336. tu.InlineKeyboardButton("0").WithCallbackData(t.encodeQuery("add_client_ip_limit_in "+strconv.Itoa(inputNumber)+" 0")),
  1337. tu.InlineKeyboardButton("⬅️").WithCallbackData(t.encodeQuery("add_client_ip_limit_in "+strconv.Itoa(inputNumber)+" -1")),
  1338. ),
  1339. )
  1340. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  1341. return
  1342. }
  1343. }
  1344. case "clear_ips":
  1345. inlineKeyboard := tu.InlineKeyboard(
  1346. tu.InlineKeyboardRow(
  1347. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("ips_cancel "+email)),
  1348. ),
  1349. tu.InlineKeyboardRow(
  1350. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmClearIps")).WithCallbackData(t.encodeQuery("clear_ips_c "+email)),
  1351. ),
  1352. )
  1353. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  1354. case "clear_ips_c":
  1355. err := t.inboundService.ClearClientIps(email)
  1356. if err == nil {
  1357. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.clearIpSuccess", "Email=="+email))
  1358. t.searchClientIps(chatId, email, callbackQuery.Message.GetMessageID())
  1359. } else {
  1360. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  1361. }
  1362. case "ip_log":
  1363. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.getIpLog", "Email=="+email))
  1364. t.searchClientIps(chatId, email)
  1365. case "tg_user":
  1366. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.getUserInfo", "Email=="+email))
  1367. t.clientTelegramUserInfo(chatId, email)
  1368. case "tgid_remove":
  1369. inlineKeyboard := tu.InlineKeyboard(
  1370. tu.InlineKeyboardRow(
  1371. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("tgid_cancel "+email)),
  1372. ),
  1373. tu.InlineKeyboardRow(
  1374. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmRemoveTGUser")).WithCallbackData(t.encodeQuery("tgid_remove_c "+email)),
  1375. ),
  1376. )
  1377. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  1378. case "tgid_remove_c":
  1379. traffic, err := t.inboundService.GetClientTrafficByEmail(email)
  1380. if err != nil || traffic == nil {
  1381. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  1382. return
  1383. }
  1384. needRestart, err := t.inboundService.SetClientTelegramUserID(traffic.Id, EmptyTelegramUserID)
  1385. if needRestart {
  1386. t.xrayService.SetToNeedRestart()
  1387. }
  1388. if err == nil {
  1389. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.removedTGUserSuccess", "Email=="+email))
  1390. t.clientTelegramUserInfo(chatId, email, callbackQuery.Message.GetMessageID())
  1391. } else {
  1392. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  1393. }
  1394. case "toggle_enable":
  1395. inlineKeyboard := tu.InlineKeyboard(
  1396. tu.InlineKeyboardRow(
  1397. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  1398. ),
  1399. tu.InlineKeyboardRow(
  1400. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmToggle")).WithCallbackData(t.encodeQuery("toggle_enable_c "+email)),
  1401. ),
  1402. )
  1403. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  1404. case "toggle_enable_c":
  1405. enabled, needRestart, err := t.inboundService.ToggleClientEnableByEmail(email)
  1406. if needRestart {
  1407. t.xrayService.SetToNeedRestart()
  1408. }
  1409. if err == nil {
  1410. if enabled {
  1411. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.enableSuccess", "Email=="+email))
  1412. } else {
  1413. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.disableSuccess", "Email=="+email))
  1414. }
  1415. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  1416. } else {
  1417. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  1418. }
  1419. case "get_clients":
  1420. inboundId := dataArray[1]
  1421. inboundIdInt, err := strconv.Atoi(inboundId)
  1422. if err != nil {
  1423. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1424. return
  1425. }
  1426. inbound, err := t.inboundService.GetInbound(inboundIdInt)
  1427. if err != nil {
  1428. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1429. return
  1430. }
  1431. clients, err := t.getInboundClients(inboundIdInt)
  1432. if err != nil {
  1433. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1434. return
  1435. }
  1436. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.chooseClient", "Inbound=="+inbound.Remark), clients)
  1437. case "add_client_to":
  1438. // assign default values to clients variables
  1439. client_Id = uuid.New().String()
  1440. client_Flow = ""
  1441. client_Email = t.randomLowerAndNum(8)
  1442. client_LimitIP = 0
  1443. client_TotalGB = 0
  1444. client_ExpiryTime = 0
  1445. client_Enable = true
  1446. client_TgID = ""
  1447. client_SubID = t.randomLowerAndNum(16)
  1448. client_Comment = ""
  1449. client_Reset = 0
  1450. client_Security = "auto"
  1451. client_ShPassword = t.randomShadowSocksPassword()
  1452. client_TrPassword = t.randomLowerAndNum(10)
  1453. client_Method = ""
  1454. inboundId := dataArray[1]
  1455. inboundIdInt, err := strconv.Atoi(inboundId)
  1456. if err != nil {
  1457. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1458. return
  1459. }
  1460. receiver_inbound_ID = inboundIdInt
  1461. inbound, err := t.inboundService.GetInbound(inboundIdInt)
  1462. if err != nil {
  1463. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1464. return
  1465. }
  1466. message_text, err := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  1467. if err != nil {
  1468. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1469. return
  1470. }
  1471. t.addClient(callbackQuery.Message.GetChat().ID, message_text)
  1472. }
  1473. return
  1474. } else {
  1475. switch callbackQuery.Data {
  1476. case "get_inbounds":
  1477. inbounds, err := t.getInbounds()
  1478. if err != nil {
  1479. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1480. return
  1481. }
  1482. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.allClients"))
  1483. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.chooseInbound"), inbounds)
  1484. case "admin_client_sub_links":
  1485. inbounds, err := t.getInboundsFor("get_clients_for_sub")
  1486. if err != nil {
  1487. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1488. return
  1489. }
  1490. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.chooseInbound"), inbounds)
  1491. case "admin_client_individual_links":
  1492. inbounds, err := t.getInboundsFor("get_clients_for_individual")
  1493. if err != nil {
  1494. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1495. return
  1496. }
  1497. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.chooseInbound"), inbounds)
  1498. case "admin_client_qr_links":
  1499. inbounds, err := t.getInboundsFor("get_clients_for_qr")
  1500. if err != nil {
  1501. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1502. return
  1503. }
  1504. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.chooseInbound"), inbounds)
  1505. }
  1506. }
  1507. }
  1508. switch callbackQuery.Data {
  1509. case "get_usage":
  1510. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.serverUsage"))
  1511. t.getServerUsage(chatId)
  1512. case "usage_refresh":
  1513. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  1514. t.getServerUsage(chatId, callbackQuery.Message.GetMessageID())
  1515. case "inbounds":
  1516. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.getInbounds"))
  1517. t.SendMsgToTgbot(chatId, t.getInboundUsages())
  1518. case "deplete_soon":
  1519. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.depleteSoon"))
  1520. t.getExhausted(chatId)
  1521. case "get_backup":
  1522. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.dbBackup"))
  1523. t.sendBackup(chatId)
  1524. case "get_banlogs":
  1525. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.getBanLogs"))
  1526. t.sendBanLogs(chatId, true)
  1527. case "client_traffic":
  1528. tgUserID := callbackQuery.From.ID
  1529. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.clientUsage"))
  1530. t.getClientUsage(chatId, tgUserID)
  1531. case "client_commands":
  1532. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.commands"))
  1533. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.commands.helpClientCommands"))
  1534. case "client_sub_links":
  1535. // show user's own clients to choose one for sub links
  1536. tgUserID := callbackQuery.From.ID
  1537. traffics, err := t.inboundService.GetClientTrafficTgBot(tgUserID)
  1538. if err != nil {
  1539. // fallback to message
  1540. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation")+"\r\n"+err.Error())
  1541. return
  1542. }
  1543. if len(traffics) == 0 {
  1544. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.askToAddUserId", "TgUserID=="+strconv.FormatInt(tgUserID, 10)))
  1545. return
  1546. }
  1547. var buttons []telego.InlineKeyboardButton
  1548. for _, tr := range traffics {
  1549. buttons = append(buttons, tu.InlineKeyboardButton(tr.Email).WithCallbackData(t.encodeQuery("client_sub_links "+tr.Email)))
  1550. }
  1551. cols := 1
  1552. if len(buttons) >= 6 {
  1553. cols = 2
  1554. }
  1555. keyboard := tu.InlineKeyboardGrid(tu.InlineKeyboardCols(cols, buttons...))
  1556. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.commands.pleaseChoose"), keyboard)
  1557. case "client_individual_links":
  1558. // show user's clients to choose for individual links
  1559. tgUserID := callbackQuery.From.ID
  1560. traffics, err := t.inboundService.GetClientTrafficTgBot(tgUserID)
  1561. if err != nil {
  1562. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation")+"\r\n"+err.Error())
  1563. return
  1564. }
  1565. if len(traffics) == 0 {
  1566. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.askToAddUserId", "TgUserID=="+strconv.FormatInt(tgUserID, 10)))
  1567. return
  1568. }
  1569. var buttons2 []telego.InlineKeyboardButton
  1570. for _, tr := range traffics {
  1571. buttons2 = append(buttons2, tu.InlineKeyboardButton(tr.Email).WithCallbackData(t.encodeQuery("client_individual_links "+tr.Email)))
  1572. }
  1573. cols2 := 1
  1574. if len(buttons2) >= 6 {
  1575. cols2 = 2
  1576. }
  1577. keyboard2 := tu.InlineKeyboardGrid(tu.InlineKeyboardCols(cols2, buttons2...))
  1578. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.commands.pleaseChoose"), keyboard2)
  1579. case "client_qr_links":
  1580. // show user's clients to choose for QR codes
  1581. tgUserID := callbackQuery.From.ID
  1582. traffics, err := t.inboundService.GetClientTrafficTgBot(tgUserID)
  1583. if err != nil {
  1584. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOccurred")+"\r\n"+err.Error())
  1585. return
  1586. }
  1587. if len(traffics) == 0 {
  1588. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.askToAddUserId", "TgUserID=="+strconv.FormatInt(tgUserID, 10)))
  1589. return
  1590. }
  1591. var buttons3 []telego.InlineKeyboardButton
  1592. for _, tr := range traffics {
  1593. buttons3 = append(buttons3, tu.InlineKeyboardButton(tr.Email).WithCallbackData(t.encodeQuery("client_qr_links "+tr.Email)))
  1594. }
  1595. cols3 := 1
  1596. if len(buttons3) >= 6 {
  1597. cols3 = 2
  1598. }
  1599. keyboard3 := tu.InlineKeyboardGrid(tu.InlineKeyboardCols(cols3, buttons3...))
  1600. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.commands.pleaseChoose"), keyboard3)
  1601. case "onlines":
  1602. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.onlines"))
  1603. t.onlineClients(chatId)
  1604. case "onlines_refresh":
  1605. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  1606. t.onlineClients(chatId, callbackQuery.Message.GetMessageID())
  1607. case "commands":
  1608. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.commands"))
  1609. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.commands.helpAdminCommands"))
  1610. case "add_client":
  1611. // assign default values to clients variables
  1612. client_Id = uuid.New().String()
  1613. client_Flow = ""
  1614. client_Email = t.randomLowerAndNum(8)
  1615. client_LimitIP = 0
  1616. client_TotalGB = 0
  1617. client_ExpiryTime = 0
  1618. client_Enable = true
  1619. client_TgID = ""
  1620. client_SubID = t.randomLowerAndNum(16)
  1621. client_Comment = ""
  1622. client_Reset = 0
  1623. client_Security = "auto"
  1624. client_ShPassword = t.randomShadowSocksPassword()
  1625. client_TrPassword = t.randomLowerAndNum(10)
  1626. client_Method = ""
  1627. inbounds, err := t.getInboundsAddClient()
  1628. if err != nil {
  1629. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1630. return
  1631. }
  1632. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.addClient"))
  1633. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.chooseInbound"), inbounds)
  1634. case "add_client_ch_default_email":
  1635. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1636. userStates[chatId] = "awaiting_email"
  1637. cancel_btn_markup := tu.InlineKeyboard(
  1638. tu.InlineKeyboardRow(
  1639. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.use_default")).WithCallbackData("add_client_default_info"),
  1640. ),
  1641. )
  1642. prompt_message := t.I18nBot("tgbot.messages.email_prompt", "ClientEmail=="+client_Email)
  1643. t.SendMsgToTgbot(chatId, prompt_message, cancel_btn_markup)
  1644. case "add_client_ch_default_id":
  1645. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1646. userStates[chatId] = "awaiting_id"
  1647. cancel_btn_markup := tu.InlineKeyboard(
  1648. tu.InlineKeyboardRow(
  1649. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.use_default")).WithCallbackData("add_client_default_info"),
  1650. ),
  1651. )
  1652. prompt_message := t.I18nBot("tgbot.messages.id_prompt", "ClientId=="+client_Id)
  1653. t.SendMsgToTgbot(chatId, prompt_message, cancel_btn_markup)
  1654. case "add_client_ch_default_pass_tr":
  1655. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1656. userStates[chatId] = "awaiting_password_tr"
  1657. cancel_btn_markup := tu.InlineKeyboard(
  1658. tu.InlineKeyboardRow(
  1659. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.use_default")).WithCallbackData("add_client_default_info"),
  1660. ),
  1661. )
  1662. prompt_message := t.I18nBot("tgbot.messages.pass_prompt", "ClientPassword=="+client_TrPassword)
  1663. t.SendMsgToTgbot(chatId, prompt_message, cancel_btn_markup)
  1664. case "add_client_ch_default_pass_sh":
  1665. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1666. userStates[chatId] = "awaiting_password_sh"
  1667. cancel_btn_markup := tu.InlineKeyboard(
  1668. tu.InlineKeyboardRow(
  1669. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.use_default")).WithCallbackData("add_client_default_info"),
  1670. ),
  1671. )
  1672. prompt_message := t.I18nBot("tgbot.messages.pass_prompt", "ClientPassword=="+client_ShPassword)
  1673. t.SendMsgToTgbot(chatId, prompt_message, cancel_btn_markup)
  1674. case "add_client_ch_default_comment":
  1675. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1676. userStates[chatId] = "awaiting_comment"
  1677. cancel_btn_markup := tu.InlineKeyboard(
  1678. tu.InlineKeyboardRow(
  1679. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.use_default")).WithCallbackData("add_client_default_info"),
  1680. ),
  1681. )
  1682. prompt_message := t.I18nBot("tgbot.messages.comment_prompt", "ClientComment=="+client_Comment)
  1683. t.SendMsgToTgbot(chatId, prompt_message, cancel_btn_markup)
  1684. case "add_client_ch_default_traffic":
  1685. inlineKeyboard := tu.InlineKeyboard(
  1686. tu.InlineKeyboardRow(
  1687. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("add_client_default_traffic_exp")),
  1688. ),
  1689. tu.InlineKeyboardRow(
  1690. tu.InlineKeyboardButton(t.I18nBot("tgbot.unlimited")).WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 0")),
  1691. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.custom")).WithCallbackData(t.encodeQuery("add_client_limit_traffic_in 0")),
  1692. ),
  1693. tu.InlineKeyboardRow(
  1694. tu.InlineKeyboardButton("1 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 1")),
  1695. tu.InlineKeyboardButton("5 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 5")),
  1696. tu.InlineKeyboardButton("10 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 10")),
  1697. ),
  1698. tu.InlineKeyboardRow(
  1699. tu.InlineKeyboardButton("20 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 20")),
  1700. tu.InlineKeyboardButton("30 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 30")),
  1701. tu.InlineKeyboardButton("40 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 40")),
  1702. ),
  1703. tu.InlineKeyboardRow(
  1704. tu.InlineKeyboardButton("50 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 50")),
  1705. tu.InlineKeyboardButton("60 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 60")),
  1706. tu.InlineKeyboardButton("80 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 80")),
  1707. ),
  1708. tu.InlineKeyboardRow(
  1709. tu.InlineKeyboardButton("100 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 100")),
  1710. tu.InlineKeyboardButton("150 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 150")),
  1711. tu.InlineKeyboardButton("200 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 200")),
  1712. ),
  1713. )
  1714. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  1715. case "add_client_ch_default_exp":
  1716. inlineKeyboard := tu.InlineKeyboard(
  1717. tu.InlineKeyboardRow(
  1718. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("add_client_default_traffic_exp")),
  1719. ),
  1720. tu.InlineKeyboardRow(
  1721. tu.InlineKeyboardButton(t.I18nBot("tgbot.unlimited")).WithCallbackData(t.encodeQuery("add_client_reset_exp_c 0")),
  1722. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.custom")).WithCallbackData(t.encodeQuery("add_client_reset_exp_in 0")),
  1723. ),
  1724. tu.InlineKeyboardRow(
  1725. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 7 "+t.I18nBot("tgbot.days")).WithCallbackData(t.encodeQuery("add_client_reset_exp_c 7")),
  1726. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 10 "+t.I18nBot("tgbot.days")).WithCallbackData(t.encodeQuery("add_client_reset_exp_c 10")),
  1727. ),
  1728. tu.InlineKeyboardRow(
  1729. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 14 "+t.I18nBot("tgbot.days")).WithCallbackData(t.encodeQuery("add_client_reset_exp_c 14")),
  1730. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 20 "+t.I18nBot("tgbot.days")).WithCallbackData(t.encodeQuery("add_client_reset_exp_c 20")),
  1731. ),
  1732. tu.InlineKeyboardRow(
  1733. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 1 "+t.I18nBot("tgbot.month")).WithCallbackData(t.encodeQuery("add_client_reset_exp_c 30")),
  1734. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 3 "+t.I18nBot("tgbot.months")).WithCallbackData(t.encodeQuery("add_client_reset_exp_c 90")),
  1735. ),
  1736. tu.InlineKeyboardRow(
  1737. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 6 "+t.I18nBot("tgbot.months")).WithCallbackData(t.encodeQuery("add_client_reset_exp_c 180")),
  1738. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 12 "+t.I18nBot("tgbot.months")).WithCallbackData(t.encodeQuery("add_client_reset_exp_c 365")),
  1739. ),
  1740. )
  1741. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  1742. case "add_client_ch_default_ip_limit":
  1743. inlineKeyboard := tu.InlineKeyboard(
  1744. tu.InlineKeyboardRow(
  1745. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("add_client_default_ip_limit")),
  1746. ),
  1747. tu.InlineKeyboardRow(
  1748. tu.InlineKeyboardButton(t.I18nBot("tgbot.unlimited")).WithCallbackData(t.encodeQuery("add_client_ip_limit_c 0")),
  1749. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.custom")).WithCallbackData(t.encodeQuery("add_client_ip_limit_in 0")),
  1750. ),
  1751. tu.InlineKeyboardRow(
  1752. tu.InlineKeyboardButton("1").WithCallbackData(t.encodeQuery("add_client_ip_limit_c 1")),
  1753. tu.InlineKeyboardButton("2").WithCallbackData(t.encodeQuery("add_client_ip_limit_c 2")),
  1754. ),
  1755. tu.InlineKeyboardRow(
  1756. tu.InlineKeyboardButton("3").WithCallbackData(t.encodeQuery("add_client_ip_limit_c 3")),
  1757. tu.InlineKeyboardButton("4").WithCallbackData(t.encodeQuery("add_client_ip_limit_c 4")),
  1758. ),
  1759. tu.InlineKeyboardRow(
  1760. tu.InlineKeyboardButton("5").WithCallbackData(t.encodeQuery("add_client_ip_limit_c 5")),
  1761. tu.InlineKeyboardButton("6").WithCallbackData(t.encodeQuery("add_client_ip_limit_c 6")),
  1762. tu.InlineKeyboardButton("7").WithCallbackData(t.encodeQuery("add_client_ip_limit_c 7")),
  1763. ),
  1764. tu.InlineKeyboardRow(
  1765. tu.InlineKeyboardButton("8").WithCallbackData(t.encodeQuery("add_client_ip_limit_c 8")),
  1766. tu.InlineKeyboardButton("9").WithCallbackData(t.encodeQuery("add_client_ip_limit_c 9")),
  1767. tu.InlineKeyboardButton("10").WithCallbackData(t.encodeQuery("add_client_ip_limit_c 10")),
  1768. ),
  1769. )
  1770. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  1771. case "add_client_default_info":
  1772. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1773. t.SendMsgToTgbotDeleteAfter(chatId, t.I18nBot("tgbot.messages.using_default_value"), 3, tu.ReplyKeyboardRemove())
  1774. delete(userStates, chatId)
  1775. inbound, _ := t.inboundService.GetInbound(receiver_inbound_ID)
  1776. message_text, _ := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  1777. t.addClient(chatId, message_text)
  1778. case "add_client_cancel":
  1779. delete(userStates, chatId)
  1780. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1781. t.SendMsgToTgbotDeleteAfter(chatId, t.I18nBot("tgbot.messages.cancel"), 3, tu.ReplyKeyboardRemove())
  1782. case "add_client_default_traffic_exp":
  1783. messageId := callbackQuery.Message.GetMessageID()
  1784. inbound, err := t.inboundService.GetInbound(receiver_inbound_ID)
  1785. if err != nil {
  1786. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1787. return
  1788. }
  1789. message_text, err := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  1790. if err != nil {
  1791. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1792. return
  1793. }
  1794. t.addClient(chatId, message_text, messageId)
  1795. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.canceled", "Email=="+client_Email))
  1796. case "add_client_default_ip_limit":
  1797. messageId := callbackQuery.Message.GetMessageID()
  1798. inbound, err := t.inboundService.GetInbound(receiver_inbound_ID)
  1799. if err != nil {
  1800. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1801. return
  1802. }
  1803. message_text, err := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  1804. if err != nil {
  1805. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1806. return
  1807. }
  1808. t.addClient(chatId, message_text, messageId)
  1809. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.canceled", "Email=="+client_Email))
  1810. case "add_client_submit_disable":
  1811. client_Enable = false
  1812. _, err := t.SubmitAddClient()
  1813. if err != nil {
  1814. errorMessage := fmt.Sprintf("%v", err)
  1815. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.messages.error_add_client", "error=="+errorMessage), tu.ReplyKeyboardRemove())
  1816. } else {
  1817. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1818. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.successfulOperation"), tu.ReplyKeyboardRemove())
  1819. }
  1820. case "add_client_submit_enable":
  1821. client_Enable = true
  1822. _, err := t.SubmitAddClient()
  1823. if err != nil {
  1824. errorMessage := fmt.Sprintf("%v", err)
  1825. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.messages.error_add_client", "error=="+errorMessage), tu.ReplyKeyboardRemove())
  1826. } else {
  1827. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1828. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.successfulOperation"), tu.ReplyKeyboardRemove())
  1829. }
  1830. case "reset_all_traffics_cancel":
  1831. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1832. t.SendMsgToTgbotDeleteAfter(chatId, t.I18nBot("tgbot.messages.cancel"), 1, tu.ReplyKeyboardRemove())
  1833. case "reset_all_traffics":
  1834. inlineKeyboard := tu.InlineKeyboard(
  1835. tu.InlineKeyboardRow(
  1836. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancelReset")).WithCallbackData(t.encodeQuery("reset_all_traffics_cancel")),
  1837. ),
  1838. tu.InlineKeyboardRow(
  1839. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmResetTraffic")).WithCallbackData(t.encodeQuery("reset_all_traffics_c")),
  1840. ),
  1841. )
  1842. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.messages.AreYouSure"), inlineKeyboard)
  1843. case "reset_all_traffics_c":
  1844. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1845. emails, err := t.inboundService.getAllEmails()
  1846. if err != nil {
  1847. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation"), tu.ReplyKeyboardRemove())
  1848. return
  1849. }
  1850. for _, email := range emails {
  1851. err := t.inboundService.ResetClientTrafficByEmail(email)
  1852. if err == nil {
  1853. msg := t.I18nBot("tgbot.messages.SuccessResetTraffic", "ClientEmail=="+email)
  1854. t.SendMsgToTgbot(chatId, msg, tu.ReplyKeyboardRemove())
  1855. } else {
  1856. msg := t.I18nBot("tgbot.messages.FailedResetTraffic", "ClientEmail=="+email, "ErrorMessage=="+err.Error())
  1857. t.SendMsgToTgbot(chatId, msg, tu.ReplyKeyboardRemove())
  1858. }
  1859. }
  1860. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.messages.FinishProcess"), tu.ReplyKeyboardRemove())
  1861. case "get_sorted_traffic_usage_report":
  1862. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1863. emails, err := t.inboundService.getAllEmails()
  1864. if err != nil {
  1865. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation"), tu.ReplyKeyboardRemove())
  1866. return
  1867. }
  1868. valid_emails, extra_emails, err := t.inboundService.FilterAndSortClientEmails(emails)
  1869. if err != nil {
  1870. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation"), tu.ReplyKeyboardRemove())
  1871. return
  1872. }
  1873. for _, valid_emails := range valid_emails {
  1874. traffic, err := t.inboundService.GetClientTrafficByEmail(valid_emails)
  1875. if err != nil {
  1876. logger.Warning(err)
  1877. msg := t.I18nBot("tgbot.wentWrong")
  1878. t.SendMsgToTgbot(chatId, msg)
  1879. continue
  1880. }
  1881. if traffic == nil {
  1882. msg := t.I18nBot("tgbot.noResult")
  1883. t.SendMsgToTgbot(chatId, msg)
  1884. continue
  1885. }
  1886. output := t.clientInfoMsg(traffic, false, false, false, false, true, false)
  1887. t.SendMsgToTgbot(chatId, output, tu.ReplyKeyboardRemove())
  1888. }
  1889. for _, extra_emails := range extra_emails {
  1890. msg := fmt.Sprintf("📧 %s\n%s", extra_emails, t.I18nBot("tgbot.noResult"))
  1891. t.SendMsgToTgbot(chatId, msg, tu.ReplyKeyboardRemove())
  1892. }
  1893. default:
  1894. if after, ok := strings.CutPrefix(callbackQuery.Data, "client_sub_links "); ok {
  1895. email := after
  1896. t.sendClientSubLinks(chatId, email)
  1897. return
  1898. }
  1899. if after, ok := strings.CutPrefix(callbackQuery.Data, "client_individual_links "); ok {
  1900. email := after
  1901. t.sendClientIndividualLinks(chatId, email)
  1902. return
  1903. }
  1904. if after, ok := strings.CutPrefix(callbackQuery.Data, "client_qr_links "); ok {
  1905. email := after
  1906. t.sendClientQRLinks(chatId, email)
  1907. return
  1908. }
  1909. }
  1910. }
  1911. // BuildInboundClientDataMessage builds a message with client data for the given inbound and protocol.
  1912. func (t *Tgbot) BuildInboundClientDataMessage(inbound_remark string, protocol model.Protocol) (string, error) {
  1913. var message string
  1914. currentTime := time.Now()
  1915. timestampMillis := currentTime.UnixNano() / int64(time.Millisecond)
  1916. expiryTime := ""
  1917. diff := client_ExpiryTime/1000 - timestampMillis
  1918. if client_ExpiryTime == 0 {
  1919. expiryTime = t.I18nBot("tgbot.unlimited")
  1920. } else if diff > 172800 {
  1921. expiryTime = time.Unix((client_ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  1922. } else if client_ExpiryTime < 0 {
  1923. expiryTime = fmt.Sprintf("%d %s", client_ExpiryTime/-86400000, t.I18nBot("tgbot.days"))
  1924. } else {
  1925. expiryTime = fmt.Sprintf("%d %s", diff/3600, t.I18nBot("tgbot.hours"))
  1926. }
  1927. traffic_value := ""
  1928. if client_TotalGB == 0 {
  1929. traffic_value = "♾️ Unlimited(Reset)"
  1930. } else {
  1931. traffic_value = common.FormatTraffic(client_TotalGB)
  1932. }
  1933. ip_limit := ""
  1934. if client_LimitIP == 0 {
  1935. ip_limit = "♾️ Unlimited(Reset)"
  1936. } else {
  1937. ip_limit = fmt.Sprint(client_LimitIP)
  1938. }
  1939. switch protocol {
  1940. case model.VMESS, model.VLESS:
  1941. message = t.I18nBot("tgbot.messages.inbound_client_data_id", "InboundRemark=="+inbound_remark, "ClientId=="+client_Id, "ClientEmail=="+client_Email, "ClientTraffic=="+traffic_value, "ClientExp=="+expiryTime, "IpLimit=="+ip_limit, "ClientComment=="+client_Comment)
  1942. case model.Trojan:
  1943. message = t.I18nBot("tgbot.messages.inbound_client_data_pass", "InboundRemark=="+inbound_remark, "ClientPass=="+client_TrPassword, "ClientEmail=="+client_Email, "ClientTraffic=="+traffic_value, "ClientExp=="+expiryTime, "IpLimit=="+ip_limit, "ClientComment=="+client_Comment)
  1944. case model.Shadowsocks:
  1945. message = t.I18nBot("tgbot.messages.inbound_client_data_pass", "InboundRemark=="+inbound_remark, "ClientPass=="+client_ShPassword, "ClientEmail=="+client_Email, "ClientTraffic=="+traffic_value, "ClientExp=="+expiryTime, "IpLimit=="+ip_limit, "ClientComment=="+client_Comment)
  1946. default:
  1947. return "", errors.New("unknown protocol")
  1948. }
  1949. return message, nil
  1950. }
  1951. // BuildJSONForProtocol builds a JSON string for the given protocol with client data.
  1952. func (t *Tgbot) BuildJSONForProtocol(protocol model.Protocol) (string, error) {
  1953. var jsonString string
  1954. switch protocol {
  1955. case model.VMESS:
  1956. jsonString = fmt.Sprintf(`{
  1957. "clients": [{
  1958. "id": "%s",
  1959. "security": "%s",
  1960. "email": "%s",
  1961. "limitIp": %d,
  1962. "totalGB": %d,
  1963. "expiryTime": %d,
  1964. "enable": %t,
  1965. "tgId": "%s",
  1966. "subId": "%s",
  1967. "comment": "%s",
  1968. "reset": %d
  1969. }]
  1970. }`, client_Id, client_Security, client_Email, client_LimitIP, client_TotalGB, client_ExpiryTime, client_Enable, client_TgID, client_SubID, client_Comment, client_Reset)
  1971. case model.VLESS:
  1972. jsonString = fmt.Sprintf(`{
  1973. "clients": [{
  1974. "id": "%s",
  1975. "flow": "%s",
  1976. "email": "%s",
  1977. "limitIp": %d,
  1978. "totalGB": %d,
  1979. "expiryTime": %d,
  1980. "enable": %t,
  1981. "tgId": "%s",
  1982. "subId": "%s",
  1983. "comment": "%s",
  1984. "reset": %d
  1985. }]
  1986. }`, client_Id, client_Flow, client_Email, client_LimitIP, client_TotalGB, client_ExpiryTime, client_Enable, client_TgID, client_SubID, client_Comment, client_Reset)
  1987. case model.Trojan:
  1988. jsonString = fmt.Sprintf(`{
  1989. "clients": [{
  1990. "password": "%s",
  1991. "email": "%s",
  1992. "limitIp": %d,
  1993. "totalGB": %d,
  1994. "expiryTime": %d,
  1995. "enable": %t,
  1996. "tgId": "%s",
  1997. "subId": "%s",
  1998. "comment": "%s",
  1999. "reset": %d
  2000. }]
  2001. }`, client_TrPassword, client_Email, client_LimitIP, client_TotalGB, client_ExpiryTime, client_Enable, client_TgID, client_SubID, client_Comment, client_Reset)
  2002. case model.Shadowsocks:
  2003. jsonString = fmt.Sprintf(`{
  2004. "clients": [{
  2005. "method": "%s",
  2006. "password": "%s",
  2007. "email": "%s",
  2008. "limitIp": %d,
  2009. "totalGB": %d,
  2010. "expiryTime": %d,
  2011. "enable": %t,
  2012. "tgId": "%s",
  2013. "subId": "%s",
  2014. "comment": "%s",
  2015. "reset": %d
  2016. }]
  2017. }`, client_Method, client_ShPassword, client_Email, client_LimitIP, client_TotalGB, client_ExpiryTime, client_Enable, client_TgID, client_SubID, client_Comment, client_Reset)
  2018. default:
  2019. return "", errors.New("unknown protocol")
  2020. }
  2021. return jsonString, nil
  2022. }
  2023. // SubmitAddClient submits the client addition request to the inbound service.
  2024. func (t *Tgbot) SubmitAddClient() (bool, error) {
  2025. inbound, err := t.inboundService.GetInbound(receiver_inbound_ID)
  2026. if err != nil {
  2027. logger.Warning("getIboundClients run failed:", err)
  2028. return false, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  2029. }
  2030. jsonString, err := t.BuildJSONForProtocol(inbound.Protocol)
  2031. if err != nil {
  2032. logger.Warning("BuildJSONForProtocol run failed:", err)
  2033. return false, errors.New("failed to build JSON for protocol")
  2034. }
  2035. newInbound := &model.Inbound{
  2036. Id: receiver_inbound_ID,
  2037. Settings: jsonString,
  2038. }
  2039. return t.inboundService.AddInboundClient(newInbound)
  2040. }
  2041. // checkAdmin checks if the given Telegram ID is an admin.
  2042. func checkAdmin(tgId int64) bool {
  2043. for _, adminId := range adminIds {
  2044. if adminId == tgId {
  2045. return true
  2046. }
  2047. }
  2048. return false
  2049. }
  2050. // SendAnswer sends a response message with an inline keyboard to the specified chat.
  2051. func (t *Tgbot) SendAnswer(chatId int64, msg string, isAdmin bool) {
  2052. numericKeyboard := tu.InlineKeyboard(
  2053. tu.InlineKeyboardRow(
  2054. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.SortedTrafficUsageReport")).WithCallbackData(t.encodeQuery("get_sorted_traffic_usage_report")),
  2055. ),
  2056. tu.InlineKeyboardRow(
  2057. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.serverUsage")).WithCallbackData(t.encodeQuery("get_usage")),
  2058. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.ResetAllTraffics")).WithCallbackData(t.encodeQuery("reset_all_traffics")),
  2059. ),
  2060. tu.InlineKeyboardRow(
  2061. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.dbBackup")).WithCallbackData(t.encodeQuery("get_backup")),
  2062. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.getBanLogs")).WithCallbackData(t.encodeQuery("get_banlogs")),
  2063. ),
  2064. tu.InlineKeyboardRow(
  2065. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.getInbounds")).WithCallbackData(t.encodeQuery("inbounds")),
  2066. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.depleteSoon")).WithCallbackData(t.encodeQuery("deplete_soon")),
  2067. ),
  2068. tu.InlineKeyboardRow(
  2069. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.commands")).WithCallbackData(t.encodeQuery("commands")),
  2070. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.onlines")).WithCallbackData(t.encodeQuery("onlines")),
  2071. ),
  2072. tu.InlineKeyboardRow(
  2073. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.allClients")).WithCallbackData(t.encodeQuery("get_inbounds")),
  2074. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.addClient")).WithCallbackData(t.encodeQuery("add_client")),
  2075. ),
  2076. tu.InlineKeyboardRow(
  2077. tu.InlineKeyboardButton(t.I18nBot("pages.settings.subSettings")).WithCallbackData(t.encodeQuery("admin_client_sub_links")),
  2078. tu.InlineKeyboardButton(t.I18nBot("subscription.individualLinks")).WithCallbackData(t.encodeQuery("admin_client_individual_links")),
  2079. tu.InlineKeyboardButton(t.I18nBot("qrCode")).WithCallbackData(t.encodeQuery("admin_client_qr_links")),
  2080. ),
  2081. // TODOOOOOOOOOOOOOO: Add restart button here.
  2082. )
  2083. numericKeyboardClient := tu.InlineKeyboard(
  2084. tu.InlineKeyboardRow(
  2085. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.clientUsage")).WithCallbackData(t.encodeQuery("client_traffic")),
  2086. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.commands")).WithCallbackData(t.encodeQuery("client_commands")),
  2087. ),
  2088. tu.InlineKeyboardRow(
  2089. tu.InlineKeyboardButton(t.I18nBot("pages.settings.subSettings")).WithCallbackData(t.encodeQuery("client_sub_links")),
  2090. tu.InlineKeyboardButton(t.I18nBot("subscription.individualLinks")).WithCallbackData(t.encodeQuery("client_individual_links")),
  2091. ),
  2092. tu.InlineKeyboardRow(
  2093. tu.InlineKeyboardButton(t.I18nBot("qrCode")).WithCallbackData(t.encodeQuery("client_qr_links")),
  2094. ),
  2095. )
  2096. var ReplyMarkup telego.ReplyMarkup
  2097. if isAdmin {
  2098. ReplyMarkup = numericKeyboard
  2099. } else {
  2100. ReplyMarkup = numericKeyboardClient
  2101. }
  2102. t.SendMsgToTgbot(chatId, msg, ReplyMarkup)
  2103. }
  2104. // SendMsgToTgbot sends a message to the Telegram bot with optional reply markup.
  2105. func (t *Tgbot) SendMsgToTgbot(chatId int64, msg string, replyMarkup ...telego.ReplyMarkup) {
  2106. if !isRunning {
  2107. return
  2108. }
  2109. if msg == "" {
  2110. logger.Info("[tgbot] message is empty!")
  2111. return
  2112. }
  2113. var allMessages []string
  2114. limit := 2000
  2115. // paging message if it is big
  2116. if len(msg) > limit {
  2117. messages := strings.Split(msg, "\r\n\r\n")
  2118. lastIndex := -1
  2119. for _, message := range messages {
  2120. if (len(allMessages) == 0) || (len(allMessages[lastIndex])+len(message) > limit) {
  2121. allMessages = append(allMessages, message)
  2122. lastIndex++
  2123. } else {
  2124. allMessages[lastIndex] += "\r\n\r\n" + message
  2125. }
  2126. }
  2127. if strings.TrimSpace(allMessages[len(allMessages)-1]) == "" {
  2128. allMessages = allMessages[:len(allMessages)-1]
  2129. }
  2130. } else {
  2131. allMessages = append(allMessages, msg)
  2132. }
  2133. for n, message := range allMessages {
  2134. params := telego.SendMessageParams{
  2135. ChatID: tu.ID(chatId),
  2136. Text: message,
  2137. ParseMode: "HTML",
  2138. }
  2139. // only add replyMarkup to last message
  2140. if len(replyMarkup) > 0 && n == (len(allMessages)-1) {
  2141. params.ReplyMarkup = replyMarkup[0]
  2142. }
  2143. // Retry logic with exponential backoff for connection errors
  2144. maxRetries := 3
  2145. for attempt := range maxRetries {
  2146. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  2147. _, err := bot.SendMessage(ctx, &params)
  2148. cancel()
  2149. if err == nil {
  2150. break // Success
  2151. }
  2152. // Check if error is a connection error
  2153. errStr := err.Error()
  2154. isConnectionError := strings.Contains(errStr, "connection") ||
  2155. strings.Contains(errStr, "timeout") ||
  2156. strings.Contains(errStr, "closed")
  2157. if isConnectionError && attempt < maxRetries-1 {
  2158. // Exponential backoff: 1s, 2s, 4s
  2159. backoff := time.Duration(1<<uint(attempt)) * time.Second
  2160. logger.Warningf("Connection error sending telegram message (attempt %d/%d), retrying in %v: %v",
  2161. attempt+1, maxRetries, backoff, err)
  2162. time.Sleep(backoff)
  2163. } else {
  2164. logger.Warning("Error sending telegram message:", err)
  2165. break
  2166. }
  2167. }
  2168. // Reduced delay to improve performance (only needed for rate limiting)
  2169. if n < len(allMessages)-1 { // Only delay between messages, not after the last one
  2170. time.Sleep(100 * time.Millisecond)
  2171. }
  2172. }
  2173. }
  2174. // buildSubscriptionURLs builds the HTML sub page URL and JSON subscription URL for a client email
  2175. func (t *Tgbot) buildSubscriptionURLs(email string) (string, string, error) {
  2176. // Resolve subId from client email
  2177. traffic, client, err := t.inboundService.GetClientByEmail(email)
  2178. _ = traffic
  2179. if err != nil || client == nil {
  2180. return "", "", errors.New("client not found")
  2181. }
  2182. // Gather settings to construct absolute URLs
  2183. subURI, _ := t.settingService.GetSubURI()
  2184. subJsonURI, _ := t.settingService.GetSubJsonURI()
  2185. subDomain, _ := t.settingService.GetSubDomain()
  2186. subPort, _ := t.settingService.GetSubPort()
  2187. subPath, _ := t.settingService.GetSubPath()
  2188. subJsonPath, _ := t.settingService.GetSubJsonPath()
  2189. subJsonEnable, _ := t.settingService.GetSubJsonEnable()
  2190. subKeyFile, _ := t.settingService.GetSubKeyFile()
  2191. subCertFile, _ := t.settingService.GetSubCertFile()
  2192. tls := (subKeyFile != "" && subCertFile != "")
  2193. scheme := "http"
  2194. if tls {
  2195. scheme = "https"
  2196. }
  2197. // Fallbacks
  2198. if subDomain == "" {
  2199. // try panel domain, otherwise OS hostname
  2200. if d, err := t.settingService.GetWebDomain(); err == nil && d != "" {
  2201. subDomain = d
  2202. } else if hostname != "" {
  2203. subDomain = hostname
  2204. } else {
  2205. subDomain = "localhost"
  2206. }
  2207. }
  2208. host := subDomain
  2209. if (subPort == 443 && tls) || (subPort == 80 && !tls) {
  2210. // standard ports: no port in host
  2211. } else {
  2212. host = fmt.Sprintf("%s:%d", subDomain, subPort)
  2213. }
  2214. // Ensure paths
  2215. if !strings.HasPrefix(subPath, "/") {
  2216. subPath = "/" + subPath
  2217. }
  2218. if !strings.HasSuffix(subPath, "/") {
  2219. subPath = subPath + "/"
  2220. }
  2221. if !strings.HasPrefix(subJsonPath, "/") {
  2222. subJsonPath = "/" + subJsonPath
  2223. }
  2224. if !strings.HasSuffix(subJsonPath, "/") {
  2225. subJsonPath = subJsonPath + "/"
  2226. }
  2227. var subURL string
  2228. var subJsonURL string
  2229. // If pre-configured URIs are available, use them directly
  2230. if subURI != "" {
  2231. if !strings.HasSuffix(subURI, "/") {
  2232. subURI = subURI + "/"
  2233. }
  2234. subURL = fmt.Sprintf("%s%s", subURI, client.SubID)
  2235. } else {
  2236. subURL = fmt.Sprintf("%s://%s%s%s", scheme, host, subPath, client.SubID)
  2237. }
  2238. if subJsonURI != "" {
  2239. if !strings.HasSuffix(subJsonURI, "/") {
  2240. subJsonURI = subJsonURI + "/"
  2241. }
  2242. subJsonURL = fmt.Sprintf("%s%s", subJsonURI, client.SubID)
  2243. } else {
  2244. subJsonURL = fmt.Sprintf("%s://%s%s%s", scheme, host, subJsonPath, client.SubID)
  2245. }
  2246. if !subJsonEnable {
  2247. subJsonURL = ""
  2248. }
  2249. return subURL, subJsonURL, nil
  2250. }
  2251. // sendClientSubLinks sends the subscription links for the client to the chat.
  2252. func (t *Tgbot) sendClientSubLinks(chatId int64, email string) {
  2253. subURL, subJsonURL, err := t.buildSubscriptionURLs(email)
  2254. if err != nil {
  2255. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation")+"\r\n"+err.Error())
  2256. return
  2257. }
  2258. msg := "Subscription URL:\r\n<code>" + subURL + "</code>"
  2259. if subJsonURL != "" {
  2260. msg += "\r\n\r\nJSON URL:\r\n<code>" + subJsonURL + "</code>"
  2261. }
  2262. inlineKeyboard := tu.InlineKeyboard(
  2263. tu.InlineKeyboardRow(
  2264. tu.InlineKeyboardButton(t.I18nBot("subscription.individualLinks")).WithCallbackData(t.encodeQuery("client_individual_links "+email)),
  2265. ),
  2266. tu.InlineKeyboardRow(
  2267. tu.InlineKeyboardButton(t.I18nBot("qrCode")).WithCallbackData(t.encodeQuery("client_qr_links "+email)),
  2268. ),
  2269. )
  2270. t.SendMsgToTgbot(chatId, msg, inlineKeyboard)
  2271. }
  2272. // sendClientIndividualLinks fetches the subscription content (individual links) and sends it to the user
  2273. func (t *Tgbot) sendClientIndividualLinks(chatId int64, email string) {
  2274. // Build the HTML sub page URL; we'll call it with header Accept to get raw content
  2275. subURL, _, err := t.buildSubscriptionURLs(email)
  2276. if err != nil {
  2277. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation")+"\r\n"+err.Error())
  2278. return
  2279. }
  2280. // Try to fetch raw subscription links. Prefer plain text response.
  2281. req, err := http.NewRequest("GET", subURL, nil)
  2282. if err != nil {
  2283. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation")+"\r\n"+err.Error())
  2284. return
  2285. }
  2286. // Force plain text to avoid HTML page; controller respects Accept header
  2287. req.Header.Set("Accept", "text/plain, */*;q=0.1")
  2288. // Use optimized client with connection pooling
  2289. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  2290. defer cancel()
  2291. req = req.WithContext(ctx)
  2292. resp, err := optimizedHTTPClient.Do(req)
  2293. if err != nil {
  2294. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation")+"\r\n"+err.Error())
  2295. return
  2296. }
  2297. defer resp.Body.Close()
  2298. bodyBytes, err := io.ReadAll(resp.Body)
  2299. if err != nil {
  2300. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation")+"\r\n"+err.Error())
  2301. return
  2302. }
  2303. // If service is configured to encode (Base64), decode it
  2304. encoded, _ := t.settingService.GetSubEncrypt()
  2305. var content string
  2306. if encoded {
  2307. decoded, err := base64.StdEncoding.DecodeString(string(bodyBytes))
  2308. if err != nil {
  2309. // fallback to raw text
  2310. content = string(bodyBytes)
  2311. } else {
  2312. content = string(decoded)
  2313. }
  2314. } else {
  2315. content = string(bodyBytes)
  2316. }
  2317. // Normalize line endings and trim
  2318. lines := strings.Split(strings.ReplaceAll(content, "\r\n", "\n"), "\n")
  2319. var cleaned []string
  2320. for _, l := range lines {
  2321. l = strings.TrimSpace(l)
  2322. if l != "" {
  2323. cleaned = append(cleaned, l)
  2324. }
  2325. }
  2326. if len(cleaned) == 0 {
  2327. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.noResult"))
  2328. return
  2329. }
  2330. // Send in chunks to respect message length; use monospace formatting
  2331. const maxPerMessage = 50
  2332. for i := 0; i < len(cleaned); i += maxPerMessage {
  2333. j := i + maxPerMessage
  2334. if j > len(cleaned) {
  2335. j = len(cleaned)
  2336. }
  2337. chunk := cleaned[i:j]
  2338. msg := t.I18nBot("subscription.individualLinks") + ":\r\n"
  2339. for _, link := range chunk {
  2340. // wrap each link in <code>
  2341. msg += "<code>" + link + "</code>\r\n"
  2342. }
  2343. t.SendMsgToTgbot(chatId, msg)
  2344. }
  2345. }
  2346. // sendClientQRLinks generates QR images for subscription URL, JSON URL, and a few individual links, then sends them
  2347. func (t *Tgbot) sendClientQRLinks(chatId int64, email string) {
  2348. subURL, subJsonURL, err := t.buildSubscriptionURLs(email)
  2349. if err != nil {
  2350. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation")+"\r\n"+err.Error())
  2351. return
  2352. }
  2353. // Helper to create QR PNG bytes from content
  2354. createQR := func(content string, size int) ([]byte, error) {
  2355. if size <= 0 {
  2356. size = 256
  2357. }
  2358. return qrcode.Encode(content, qrcode.Medium, size)
  2359. }
  2360. // Inform user
  2361. t.SendMsgToTgbot(chatId, "QRCode"+":")
  2362. // Send sub URL QR (filename: sub.png)
  2363. if png, err := createQR(subURL, 320); err == nil {
  2364. document := tu.Document(
  2365. tu.ID(chatId),
  2366. tu.FileFromBytes(png, "sub.png"),
  2367. )
  2368. _, _ = bot.SendDocument(context.Background(), document)
  2369. } else {
  2370. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation")+"\r\n"+err.Error())
  2371. }
  2372. // Send JSON URL QR (filename: subjson.png) when available
  2373. if subJsonURL != "" {
  2374. if png, err := createQR(subJsonURL, 320); err == nil {
  2375. document := tu.Document(
  2376. tu.ID(chatId),
  2377. tu.FileFromBytes(png, "subjson.png"),
  2378. )
  2379. _, _ = bot.SendDocument(context.Background(), document)
  2380. } else {
  2381. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation")+"\r\n"+err.Error())
  2382. }
  2383. }
  2384. // Also generate a few individual links' QRs (first up to 5)
  2385. subPageURL := subURL
  2386. req, err := http.NewRequest("GET", subPageURL, nil)
  2387. if err == nil {
  2388. req.Header.Set("Accept", "text/plain, */*;q=0.1")
  2389. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  2390. defer cancel()
  2391. req = req.WithContext(ctx)
  2392. if resp, err := optimizedHTTPClient.Do(req); err == nil {
  2393. body, _ := io.ReadAll(resp.Body)
  2394. _ = resp.Body.Close()
  2395. encoded, _ := t.settingService.GetSubEncrypt()
  2396. var content string
  2397. if encoded {
  2398. if dec, err := base64.StdEncoding.DecodeString(string(body)); err == nil {
  2399. content = string(dec)
  2400. } else {
  2401. content = string(body)
  2402. }
  2403. } else {
  2404. content = string(body)
  2405. }
  2406. lines := strings.Split(strings.ReplaceAll(content, "\r\n", "\n"), "\n")
  2407. var cleaned []string
  2408. for _, l := range lines {
  2409. l = strings.TrimSpace(l)
  2410. if l != "" {
  2411. cleaned = append(cleaned, l)
  2412. }
  2413. }
  2414. if len(cleaned) > 0 {
  2415. max := min(len(cleaned), 5)
  2416. for i := range max {
  2417. if png, err := createQR(cleaned[i], 320); err == nil {
  2418. // Use the email as filename for individual link QR
  2419. filename := email + ".png"
  2420. document := tu.Document(
  2421. tu.ID(chatId),
  2422. tu.FileFromBytes(png, filename),
  2423. )
  2424. _, _ = bot.SendDocument(context.Background(), document)
  2425. // Reduced delay for better performance
  2426. if i < max-1 { // Only delay between documents, not after the last one
  2427. time.Sleep(50 * time.Millisecond)
  2428. }
  2429. }
  2430. }
  2431. }
  2432. }
  2433. }
  2434. }
  2435. // SendMsgToTgbotAdmins sends a message to all admin Telegram chats.
  2436. func (t *Tgbot) SendMsgToTgbotAdmins(msg string, replyMarkup ...telego.ReplyMarkup) {
  2437. if len(replyMarkup) > 0 {
  2438. for _, adminId := range adminIds {
  2439. t.SendMsgToTgbot(adminId, msg, replyMarkup[0])
  2440. }
  2441. } else {
  2442. for _, adminId := range adminIds {
  2443. t.SendMsgToTgbot(adminId, msg)
  2444. }
  2445. }
  2446. }
  2447. // SendReport sends a periodic report to admin chats.
  2448. func (t *Tgbot) SendReport() {
  2449. runTime, err := t.settingService.GetTgbotRuntime()
  2450. if err == nil && len(runTime) > 0 {
  2451. msg := ""
  2452. msg += t.I18nBot("tgbot.messages.report", "RunTime=="+runTime)
  2453. msg += t.I18nBot("tgbot.messages.datetime", "DateTime=="+time.Now().Format("2006-01-02 15:04:05"))
  2454. t.SendMsgToTgbotAdmins(msg)
  2455. }
  2456. info := t.sendServerUsage()
  2457. t.SendMsgToTgbotAdmins(info)
  2458. t.sendExhaustedToAdmins()
  2459. t.notifyExhausted()
  2460. backupEnable, err := t.settingService.GetTgBotBackup()
  2461. if err == nil && backupEnable {
  2462. t.SendBackupToAdmins()
  2463. }
  2464. }
  2465. // SendBackupToAdmins sends a database backup to admin chats.
  2466. func (t *Tgbot) SendBackupToAdmins() {
  2467. if !t.IsRunning() {
  2468. return
  2469. }
  2470. for i, adminId := range adminIds {
  2471. t.sendBackup(int64(adminId))
  2472. // Add delay between sends to avoid Telegram rate limits
  2473. if i < len(adminIds)-1 {
  2474. time.Sleep(1 * time.Second)
  2475. }
  2476. }
  2477. }
  2478. // sendExhaustedToAdmins sends notifications about exhausted clients to admins.
  2479. func (t *Tgbot) sendExhaustedToAdmins() {
  2480. if !t.IsRunning() {
  2481. return
  2482. }
  2483. for _, adminId := range adminIds {
  2484. t.getExhausted(int64(adminId))
  2485. }
  2486. }
  2487. // getServerUsage retrieves and formats server usage information.
  2488. func (t *Tgbot) getServerUsage(chatId int64, messageID ...int) string {
  2489. info := t.prepareServerUsageInfo()
  2490. keyboard := tu.InlineKeyboard(tu.InlineKeyboardRow(
  2491. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(t.encodeQuery("usage_refresh"))))
  2492. if len(messageID) > 0 {
  2493. t.editMessageTgBot(chatId, messageID[0], info, keyboard)
  2494. } else {
  2495. t.SendMsgToTgbot(chatId, info, keyboard)
  2496. }
  2497. return info
  2498. }
  2499. // Send server usage without an inline keyboard
  2500. func (t *Tgbot) sendServerUsage() string {
  2501. info := t.prepareServerUsageInfo()
  2502. return info
  2503. }
  2504. // prepareServerUsageInfo prepares the server usage information string.
  2505. func (t *Tgbot) prepareServerUsageInfo() string {
  2506. // Check if we have cached data first
  2507. if cachedStats, found := t.getCachedServerStats(); found {
  2508. return cachedStats
  2509. }
  2510. info, ipv4, ipv6 := "", "", ""
  2511. // get latest status of server with caching
  2512. if cachedStatus, found := t.getCachedStatus(); found {
  2513. t.lastStatus = cachedStatus
  2514. } else {
  2515. t.lastStatus = t.serverService.GetStatus(t.lastStatus)
  2516. t.setCachedStatus(t.lastStatus)
  2517. }
  2518. onlines := p.GetOnlineClients()
  2519. info += t.I18nBot("tgbot.messages.hostname", "Hostname=="+hostname)
  2520. info += t.I18nBot("tgbot.messages.version", "Version=="+config.GetVersion())
  2521. info += t.I18nBot("tgbot.messages.xrayVersion", "XrayVersion=="+fmt.Sprint(t.lastStatus.Xray.Version))
  2522. // get ip address
  2523. netInterfaces, err := net.Interfaces()
  2524. if err != nil {
  2525. logger.Error("net.Interfaces failed, err: ", err.Error())
  2526. info += t.I18nBot("tgbot.messages.ip", "IP=="+t.I18nBot("tgbot.unknown"))
  2527. info += "\r\n"
  2528. } else {
  2529. for i := 0; i < len(netInterfaces); i++ {
  2530. if (netInterfaces[i].Flags & net.FlagUp) != 0 {
  2531. addrs, _ := netInterfaces[i].Addrs()
  2532. for _, address := range addrs {
  2533. if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
  2534. if ipnet.IP.To4() != nil {
  2535. ipv4 += ipnet.IP.String() + " "
  2536. } else if ipnet.IP.To16() != nil && !ipnet.IP.IsLinkLocalUnicast() {
  2537. ipv6 += ipnet.IP.String() + " "
  2538. }
  2539. }
  2540. }
  2541. }
  2542. }
  2543. info += t.I18nBot("tgbot.messages.ipv4", "IPv4=="+ipv4)
  2544. info += t.I18nBot("tgbot.messages.ipv6", "IPv6=="+ipv6)
  2545. }
  2546. info += t.I18nBot("tgbot.messages.serverUpTime", "UpTime=="+strconv.FormatUint(t.lastStatus.Uptime/86400, 10), "Unit=="+t.I18nBot("tgbot.days"))
  2547. 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))
  2548. info += t.I18nBot("tgbot.messages.serverMemory", "Current=="+common.FormatTraffic(int64(t.lastStatus.Mem.Current)), "Total=="+common.FormatTraffic(int64(t.lastStatus.Mem.Total)))
  2549. info += t.I18nBot("tgbot.messages.onlinesCount", "Count=="+fmt.Sprint(len(onlines)))
  2550. info += t.I18nBot("tgbot.messages.tcpCount", "Count=="+strconv.Itoa(t.lastStatus.TcpCount))
  2551. info += t.I18nBot("tgbot.messages.udpCount", "Count=="+strconv.Itoa(t.lastStatus.UdpCount))
  2552. 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)))
  2553. info += t.I18nBot("tgbot.messages.xrayStatus", "State=="+fmt.Sprint(t.lastStatus.Xray.State))
  2554. // Cache the complete server stats
  2555. t.setCachedServerStats(info)
  2556. return info
  2557. }
  2558. // UserLoginNotify sends a notification about user login attempts to admins.
  2559. func (t *Tgbot) UserLoginNotify(username string, password string, ip string, time string, status LoginStatus) {
  2560. if !t.IsRunning() {
  2561. return
  2562. }
  2563. if username == "" || ip == "" || time == "" {
  2564. logger.Warning("UserLoginNotify failed, invalid info!")
  2565. return
  2566. }
  2567. loginNotifyEnabled, err := t.settingService.GetTgBotLoginNotify()
  2568. if err != nil || !loginNotifyEnabled {
  2569. return
  2570. }
  2571. msg := ""
  2572. switch status {
  2573. case LoginSuccess:
  2574. msg += t.I18nBot("tgbot.messages.loginSuccess")
  2575. msg += t.I18nBot("tgbot.messages.hostname", "Hostname=="+hostname)
  2576. case LoginFail:
  2577. msg += t.I18nBot("tgbot.messages.loginFailed")
  2578. msg += t.I18nBot("tgbot.messages.hostname", "Hostname=="+hostname)
  2579. msg += t.I18nBot("tgbot.messages.password", "Password=="+password)
  2580. }
  2581. msg += t.I18nBot("tgbot.messages.username", "Username=="+username)
  2582. msg += t.I18nBot("tgbot.messages.ip", "IP=="+ip)
  2583. msg += t.I18nBot("tgbot.messages.time", "Time=="+time)
  2584. t.SendMsgToTgbotAdmins(msg)
  2585. }
  2586. // getInboundUsages retrieves and formats inbound usage information.
  2587. func (t *Tgbot) getInboundUsages() string {
  2588. info := ""
  2589. // get traffic
  2590. inbounds, err := t.inboundService.GetAllInbounds()
  2591. if err != nil {
  2592. logger.Warning("GetAllInbounds run failed:", err)
  2593. info += t.I18nBot("tgbot.answers.getInboundsFailed")
  2594. } else {
  2595. // NOTE:If there no any sessions here,need to notify here
  2596. // TODO:Sub-node push, automatic conversion format
  2597. for _, inbound := range inbounds {
  2598. info += t.I18nBot("tgbot.messages.inbound", "Remark=="+inbound.Remark)
  2599. info += t.I18nBot("tgbot.messages.port", "Port=="+strconv.Itoa(inbound.Port))
  2600. info += t.I18nBot("tgbot.messages.traffic", "Total=="+common.FormatTraffic((inbound.Up+inbound.Down)), "Upload=="+common.FormatTraffic(inbound.Up), "Download=="+common.FormatTraffic(inbound.Down))
  2601. if inbound.ExpiryTime == 0 {
  2602. info += t.I18nBot("tgbot.messages.expire", "Time=="+t.I18nBot("tgbot.unlimited"))
  2603. } else {
  2604. info += t.I18nBot("tgbot.messages.expire", "Time=="+time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  2605. }
  2606. info += "\r\n"
  2607. }
  2608. }
  2609. return info
  2610. }
  2611. // getInbounds creates an inline keyboard with all inbounds.
  2612. func (t *Tgbot) getInbounds() (*telego.InlineKeyboardMarkup, error) {
  2613. inbounds, err := t.inboundService.GetAllInbounds()
  2614. if err != nil {
  2615. logger.Warning("GetAllInbounds run failed:", err)
  2616. return nil, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  2617. }
  2618. if len(inbounds) == 0 {
  2619. logger.Warning("No inbounds found")
  2620. return nil, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  2621. }
  2622. var buttons []telego.InlineKeyboardButton
  2623. for _, inbound := range inbounds {
  2624. status := "❌"
  2625. if inbound.Enable {
  2626. status = "✅"
  2627. }
  2628. callbackData := t.encodeQuery(fmt.Sprintf("%s %d", "get_clients", inbound.Id))
  2629. buttons = append(buttons, tu.InlineKeyboardButton(fmt.Sprintf("%v - %v", inbound.Remark, status)).WithCallbackData(callbackData))
  2630. }
  2631. cols := 1
  2632. if len(buttons) >= 6 {
  2633. cols = 2
  2634. }
  2635. keyboard := tu.InlineKeyboardGrid(tu.InlineKeyboardCols(cols, buttons...))
  2636. return keyboard, nil
  2637. }
  2638. // getInboundsFor builds an inline keyboard of inbounds for a custom next action.
  2639. func (t *Tgbot) getInboundsFor(nextAction string) (*telego.InlineKeyboardMarkup, error) {
  2640. inbounds, err := t.inboundService.GetAllInbounds()
  2641. if err != nil {
  2642. logger.Warning("GetAllInbounds run failed:", err)
  2643. return nil, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  2644. }
  2645. if len(inbounds) == 0 {
  2646. logger.Warning("No inbounds found")
  2647. return nil, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  2648. }
  2649. var buttons []telego.InlineKeyboardButton
  2650. for _, inbound := range inbounds {
  2651. status := "❌"
  2652. if inbound.Enable {
  2653. status = "✅"
  2654. }
  2655. callbackData := t.encodeQuery(fmt.Sprintf("%s %d", nextAction, inbound.Id))
  2656. buttons = append(buttons, tu.InlineKeyboardButton(fmt.Sprintf("%v - %v", inbound.Remark, status)).WithCallbackData(callbackData))
  2657. }
  2658. cols := 1
  2659. if len(buttons) >= 6 {
  2660. cols = 2
  2661. }
  2662. keyboard := tu.InlineKeyboardGrid(tu.InlineKeyboardCols(cols, buttons...))
  2663. return keyboard, nil
  2664. }
  2665. // getInboundClientsFor lists clients of an inbound with a specific action prefix to be appended with email
  2666. func (t *Tgbot) getInboundClientsFor(inboundID int, action string) (*telego.InlineKeyboardMarkup, error) {
  2667. inbound, err := t.inboundService.GetInbound(inboundID)
  2668. if err != nil {
  2669. logger.Warning("getInboundClientsFor run failed:", err)
  2670. return nil, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  2671. }
  2672. clients, err := t.inboundService.GetClients(inbound)
  2673. var buttons []telego.InlineKeyboardButton
  2674. if err != nil {
  2675. logger.Warning("GetInboundClients run failed:", err)
  2676. return nil, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  2677. } else {
  2678. if len(clients) > 0 {
  2679. for _, client := range clients {
  2680. buttons = append(buttons, tu.InlineKeyboardButton(client.Email).WithCallbackData(t.encodeQuery(action+" "+client.Email)))
  2681. }
  2682. } else {
  2683. return nil, errors.New(t.I18nBot("tgbot.answers.getClientsFailed"))
  2684. }
  2685. }
  2686. cols := 0
  2687. if len(buttons) < 6 {
  2688. cols = 3
  2689. } else {
  2690. cols = 2
  2691. }
  2692. keyboard := tu.InlineKeyboardGrid(tu.InlineKeyboardCols(cols, buttons...))
  2693. return keyboard, nil
  2694. }
  2695. // getInboundsAddClient creates an inline keyboard for adding clients to inbounds.
  2696. func (t *Tgbot) getInboundsAddClient() (*telego.InlineKeyboardMarkup, error) {
  2697. inbounds, err := t.inboundService.GetAllInbounds()
  2698. if err != nil {
  2699. logger.Warning("GetAllInbounds run failed:", err)
  2700. return nil, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  2701. }
  2702. if len(inbounds) == 0 {
  2703. logger.Warning("No inbounds found")
  2704. return nil, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  2705. }
  2706. excludedProtocols := map[model.Protocol]bool{
  2707. model.Tunnel: true,
  2708. model.Mixed: true,
  2709. model.WireGuard: true,
  2710. model.HTTP: true,
  2711. }
  2712. var buttons []telego.InlineKeyboardButton
  2713. for _, inbound := range inbounds {
  2714. if excludedProtocols[inbound.Protocol] {
  2715. continue
  2716. }
  2717. status := "❌"
  2718. if inbound.Enable {
  2719. status = "✅"
  2720. }
  2721. callbackData := t.encodeQuery(fmt.Sprintf("%s %d", "add_client_to", inbound.Id))
  2722. buttons = append(buttons, tu.InlineKeyboardButton(fmt.Sprintf("%v - %v", inbound.Remark, status)).WithCallbackData(callbackData))
  2723. }
  2724. cols := 1
  2725. if len(buttons) >= 6 {
  2726. cols = 2
  2727. }
  2728. keyboard := tu.InlineKeyboardGrid(tu.InlineKeyboardCols(cols, buttons...))
  2729. return keyboard, nil
  2730. }
  2731. // getInboundClients creates an inline keyboard with clients of a specific inbound.
  2732. func (t *Tgbot) getInboundClients(id int) (*telego.InlineKeyboardMarkup, error) {
  2733. inbound, err := t.inboundService.GetInbound(id)
  2734. if err != nil {
  2735. logger.Warning("getIboundClients run failed:", err)
  2736. return nil, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  2737. }
  2738. clients, err := t.inboundService.GetClients(inbound)
  2739. var buttons []telego.InlineKeyboardButton
  2740. if err != nil {
  2741. logger.Warning("GetInboundClients run failed:", err)
  2742. return nil, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  2743. } else {
  2744. if len(clients) > 0 {
  2745. for _, client := range clients {
  2746. buttons = append(buttons, tu.InlineKeyboardButton(client.Email).WithCallbackData(t.encodeQuery("client_get_usage "+client.Email)))
  2747. }
  2748. } else {
  2749. return nil, errors.New(t.I18nBot("tgbot.answers.getClientsFailed"))
  2750. }
  2751. }
  2752. cols := 0
  2753. if len(buttons) < 6 {
  2754. cols = 3
  2755. } else {
  2756. cols = 2
  2757. }
  2758. keyboard := tu.InlineKeyboardGrid(tu.InlineKeyboardCols(cols, buttons...))
  2759. return keyboard, nil
  2760. }
  2761. // clientInfoMsg formats client information message based on traffic and flags.
  2762. func (t *Tgbot) clientInfoMsg(
  2763. traffic *xray.ClientTraffic,
  2764. printEnabled bool,
  2765. printOnline bool,
  2766. printActive bool,
  2767. printDate bool,
  2768. printTraffic bool,
  2769. printRefreshed bool,
  2770. ) string {
  2771. now := time.Now().Unix()
  2772. expiryTime := ""
  2773. flag := false
  2774. diff := traffic.ExpiryTime/1000 - now
  2775. if traffic.ExpiryTime == 0 {
  2776. expiryTime = t.I18nBot("tgbot.unlimited")
  2777. } else if diff > 172800 || !traffic.Enable {
  2778. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  2779. if diff > 0 {
  2780. days := diff / 86400
  2781. hours := (diff % 86400) / 3600
  2782. minutes := (diff % 3600) / 60
  2783. remainingTime := ""
  2784. if days > 0 {
  2785. remainingTime += fmt.Sprintf("%d %s ", days, t.I18nBot("tgbot.days"))
  2786. }
  2787. if hours > 0 {
  2788. remainingTime += fmt.Sprintf("%d %s ", hours, t.I18nBot("tgbot.hours"))
  2789. }
  2790. if minutes > 0 {
  2791. remainingTime += fmt.Sprintf("%d %s", minutes, t.I18nBot("tgbot.minutes"))
  2792. }
  2793. expiryTime += fmt.Sprintf(" (%s)", remainingTime)
  2794. }
  2795. } else if traffic.ExpiryTime < 0 {
  2796. expiryTime = fmt.Sprintf("%d %s", traffic.ExpiryTime/-86400000, t.I18nBot("tgbot.days"))
  2797. flag = true
  2798. } else {
  2799. expiryTime = fmt.Sprintf("%d %s", diff/3600, t.I18nBot("tgbot.hours"))
  2800. flag = true
  2801. }
  2802. total := ""
  2803. if traffic.Total == 0 {
  2804. total = t.I18nBot("tgbot.unlimited")
  2805. } else {
  2806. total = common.FormatTraffic((traffic.Total))
  2807. }
  2808. enabled := ""
  2809. isEnabled, err := t.inboundService.checkIsEnabledByEmail(traffic.Email)
  2810. if err != nil {
  2811. logger.Warning(err)
  2812. enabled = t.I18nBot("tgbot.wentWrong")
  2813. } else if isEnabled {
  2814. enabled = t.I18nBot("tgbot.messages.yes")
  2815. } else {
  2816. enabled = t.I18nBot("tgbot.messages.no")
  2817. }
  2818. active := ""
  2819. if traffic.Enable {
  2820. active = t.I18nBot("tgbot.messages.yes")
  2821. } else {
  2822. active = t.I18nBot("tgbot.messages.no")
  2823. }
  2824. status := t.I18nBot("tgbot.offline")
  2825. isOnline := false
  2826. if p.IsRunning() {
  2827. for _, online := range p.GetOnlineClients() {
  2828. if online == traffic.Email {
  2829. status = t.I18nBot("tgbot.online")
  2830. isOnline = true
  2831. break
  2832. }
  2833. }
  2834. }
  2835. output := ""
  2836. output += t.I18nBot("tgbot.messages.email", "Email=="+traffic.Email)
  2837. if printEnabled {
  2838. output += t.I18nBot("tgbot.messages.enabled", "Enable=="+enabled)
  2839. }
  2840. if printOnline {
  2841. output += t.I18nBot("tgbot.messages.online", "Status=="+status)
  2842. if !isOnline && traffic.LastOnline > 0 {
  2843. output += t.I18nBot("tgbot.messages.lastOnline", "Time=="+time.UnixMilli(traffic.LastOnline).Format("2006-01-02 15:04:05"))
  2844. }
  2845. }
  2846. if printActive {
  2847. output += t.I18nBot("tgbot.messages.active", "Enable=="+active)
  2848. }
  2849. if printDate {
  2850. if flag {
  2851. output += t.I18nBot("tgbot.messages.expireIn", "Time=="+expiryTime)
  2852. } else {
  2853. output += t.I18nBot("tgbot.messages.expire", "Time=="+expiryTime)
  2854. }
  2855. }
  2856. if printTraffic {
  2857. output += t.I18nBot("tgbot.messages.upload", "Upload=="+common.FormatTraffic(traffic.Up))
  2858. output += t.I18nBot("tgbot.messages.download", "Download=="+common.FormatTraffic(traffic.Down))
  2859. output += t.I18nBot("tgbot.messages.total", "UpDown=="+common.FormatTraffic((traffic.Up+traffic.Down)), "Total=="+total)
  2860. }
  2861. if printRefreshed {
  2862. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  2863. }
  2864. return output
  2865. }
  2866. // getClientUsage retrieves and sends client usage information to the chat.
  2867. func (t *Tgbot) getClientUsage(chatId int64, tgUserID int64, email ...string) {
  2868. traffics, err := t.inboundService.GetClientTrafficTgBot(tgUserID)
  2869. if err != nil {
  2870. logger.Warning(err)
  2871. msg := t.I18nBot("tgbot.wentWrong")
  2872. t.SendMsgToTgbot(chatId, msg)
  2873. return
  2874. }
  2875. if len(traffics) == 0 {
  2876. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.askToAddUserId", "TgUserID=="+strconv.FormatInt(tgUserID, 10)))
  2877. return
  2878. }
  2879. output := ""
  2880. if len(traffics) > 0 {
  2881. if len(email) > 0 {
  2882. for _, traffic := range traffics {
  2883. if traffic.Email == email[0] {
  2884. output := t.clientInfoMsg(traffic, true, true, true, true, true, true)
  2885. t.SendMsgToTgbot(chatId, output)
  2886. return
  2887. }
  2888. }
  2889. msg := t.I18nBot("tgbot.noResult")
  2890. t.SendMsgToTgbot(chatId, msg)
  2891. return
  2892. } else {
  2893. for _, traffic := range traffics {
  2894. output += t.clientInfoMsg(traffic, true, true, true, true, true, false)
  2895. output += "\r\n"
  2896. }
  2897. }
  2898. }
  2899. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  2900. t.SendMsgToTgbot(chatId, output)
  2901. output = t.I18nBot("tgbot.commands.pleaseChoose")
  2902. t.SendAnswer(chatId, output, false)
  2903. }
  2904. // searchClientIps searches and sends client IP addresses for the given email.
  2905. func (t *Tgbot) searchClientIps(chatId int64, email string, messageID ...int) {
  2906. ips, err := t.inboundService.GetInboundClientIps(email)
  2907. if err != nil || len(ips) == 0 {
  2908. ips = t.I18nBot("tgbot.noIpRecord")
  2909. }
  2910. formattedIps := ips
  2911. if err == nil && len(ips) > 0 {
  2912. type ipWithTimestamp struct {
  2913. IP string `json:"ip"`
  2914. Timestamp int64 `json:"timestamp"`
  2915. }
  2916. var ipsWithTime []ipWithTimestamp
  2917. if json.Unmarshal([]byte(ips), &ipsWithTime) == nil && len(ipsWithTime) > 0 {
  2918. lines := make([]string, 0, len(ipsWithTime))
  2919. for _, item := range ipsWithTime {
  2920. if item.IP == "" {
  2921. continue
  2922. }
  2923. if item.Timestamp > 0 {
  2924. ts := time.Unix(item.Timestamp, 0).Format("2006-01-02 15:04:05")
  2925. lines = append(lines, fmt.Sprintf("%s (%s)", item.IP, ts))
  2926. continue
  2927. }
  2928. lines = append(lines, item.IP)
  2929. }
  2930. if len(lines) > 0 {
  2931. formattedIps = strings.Join(lines, "\n")
  2932. }
  2933. } else {
  2934. var oldIps []string
  2935. if json.Unmarshal([]byte(ips), &oldIps) == nil && len(oldIps) > 0 {
  2936. formattedIps = strings.Join(oldIps, "\n")
  2937. }
  2938. }
  2939. }
  2940. output := ""
  2941. output += t.I18nBot("tgbot.messages.email", "Email=="+email)
  2942. output += t.I18nBot("tgbot.messages.ips", "IPs=="+formattedIps)
  2943. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  2944. inlineKeyboard := tu.InlineKeyboard(
  2945. tu.InlineKeyboardRow(
  2946. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(t.encodeQuery("ips_refresh "+email)),
  2947. ),
  2948. tu.InlineKeyboardRow(
  2949. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.clearIPs")).WithCallbackData(t.encodeQuery("clear_ips "+email)),
  2950. ),
  2951. )
  2952. if len(messageID) > 0 {
  2953. t.editMessageTgBot(chatId, messageID[0], output, inlineKeyboard)
  2954. } else {
  2955. t.SendMsgToTgbot(chatId, output, inlineKeyboard)
  2956. }
  2957. }
  2958. // clientTelegramUserInfo retrieves and sends Telegram user info for the client.
  2959. func (t *Tgbot) clientTelegramUserInfo(chatId int64, email string, messageID ...int) {
  2960. traffic, client, err := t.inboundService.GetClientByEmail(email)
  2961. if err != nil {
  2962. logger.Warning(err)
  2963. msg := t.I18nBot("tgbot.wentWrong")
  2964. t.SendMsgToTgbot(chatId, msg)
  2965. return
  2966. }
  2967. if client == nil {
  2968. msg := t.I18nBot("tgbot.noResult")
  2969. t.SendMsgToTgbot(chatId, msg)
  2970. return
  2971. }
  2972. tgId := "None"
  2973. if client.TgID != 0 {
  2974. tgId = strconv.FormatInt(client.TgID, 10)
  2975. }
  2976. output := ""
  2977. output += t.I18nBot("tgbot.messages.email", "Email=="+email)
  2978. output += t.I18nBot("tgbot.messages.TGUser", "TelegramID=="+tgId)
  2979. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  2980. inlineKeyboard := tu.InlineKeyboard(
  2981. tu.InlineKeyboardRow(
  2982. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(t.encodeQuery("tgid_refresh "+email)),
  2983. ),
  2984. tu.InlineKeyboardRow(
  2985. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.removeTGUser")).WithCallbackData(t.encodeQuery("tgid_remove "+email)),
  2986. ),
  2987. )
  2988. if len(messageID) > 0 {
  2989. t.editMessageTgBot(chatId, messageID[0], output, inlineKeyboard)
  2990. } else {
  2991. t.SendMsgToTgbot(chatId, output, inlineKeyboard)
  2992. requestUser := telego.KeyboardButtonRequestUsers{
  2993. RequestID: int32(traffic.Id),
  2994. UserIsBot: new(bool),
  2995. }
  2996. keyboard := tu.Keyboard(
  2997. tu.KeyboardRow(
  2998. tu.KeyboardButton(t.I18nBot("tgbot.buttons.selectTGUser")).WithRequestUsers(&requestUser),
  2999. ),
  3000. tu.KeyboardRow(
  3001. tu.KeyboardButton(t.I18nBot("tgbot.buttons.closeKeyboard")),
  3002. ),
  3003. ).WithIsPersistent().WithResizeKeyboard()
  3004. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.buttons.selectOneTGUser"), keyboard)
  3005. }
  3006. }
  3007. // searchClient searches for a client by email and sends the information.
  3008. func (t *Tgbot) searchClient(chatId int64, email string, messageID ...int) {
  3009. traffic, err := t.inboundService.GetClientTrafficByEmail(email)
  3010. if err != nil {
  3011. logger.Warning(err)
  3012. msg := t.I18nBot("tgbot.wentWrong")
  3013. t.SendMsgToTgbot(chatId, msg)
  3014. return
  3015. }
  3016. if traffic == nil {
  3017. msg := t.I18nBot("tgbot.noResult")
  3018. t.SendMsgToTgbot(chatId, msg)
  3019. return
  3020. }
  3021. output := t.clientInfoMsg(traffic, true, true, true, true, true, true)
  3022. inlineKeyboard := tu.InlineKeyboard(
  3023. tu.InlineKeyboardRow(
  3024. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(t.encodeQuery("client_refresh "+email)),
  3025. ),
  3026. tu.InlineKeyboardRow(
  3027. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.resetTraffic")).WithCallbackData(t.encodeQuery("reset_traffic "+email)),
  3028. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.limitTraffic")).WithCallbackData(t.encodeQuery("limit_traffic "+email)),
  3029. ),
  3030. tu.InlineKeyboardRow(
  3031. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.resetExpire")).WithCallbackData(t.encodeQuery("reset_exp "+email)),
  3032. ),
  3033. tu.InlineKeyboardRow(
  3034. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.ipLog")).WithCallbackData(t.encodeQuery("ip_log "+email)),
  3035. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.ipLimit")).WithCallbackData(t.encodeQuery("ip_limit "+email)),
  3036. ),
  3037. tu.InlineKeyboardRow(
  3038. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.setTGUser")).WithCallbackData(t.encodeQuery("tg_user "+email)),
  3039. ),
  3040. tu.InlineKeyboardRow(
  3041. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.toggle")).WithCallbackData(t.encodeQuery("toggle_enable "+email)),
  3042. ),
  3043. )
  3044. if len(messageID) > 0 {
  3045. t.editMessageTgBot(chatId, messageID[0], output, inlineKeyboard)
  3046. } else {
  3047. t.SendMsgToTgbot(chatId, output, inlineKeyboard)
  3048. }
  3049. }
  3050. // addClient handles the process of adding a new client to an inbound.
  3051. func (t *Tgbot) addClient(chatId int64, msg string, messageID ...int) {
  3052. inbound, err := t.inboundService.GetInbound(receiver_inbound_ID)
  3053. if err != nil {
  3054. t.SendMsgToTgbot(chatId, err.Error())
  3055. return
  3056. }
  3057. protocol := inbound.Protocol
  3058. switch protocol {
  3059. case model.VMESS, model.VLESS:
  3060. inlineKeyboard := tu.InlineKeyboard(
  3061. tu.InlineKeyboardRow(
  3062. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.change_email")).WithCallbackData("add_client_ch_default_email"),
  3063. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.change_id")).WithCallbackData("add_client_ch_default_id"),
  3064. ),
  3065. tu.InlineKeyboardRow(
  3066. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.limitTraffic")).WithCallbackData("add_client_ch_default_traffic"),
  3067. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.resetExpire")).WithCallbackData("add_client_ch_default_exp"),
  3068. ),
  3069. tu.InlineKeyboardRow(
  3070. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.change_comment")).WithCallbackData("add_client_ch_default_comment"),
  3071. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.ipLimit")).WithCallbackData("add_client_ch_default_ip_limit"),
  3072. ),
  3073. tu.InlineKeyboardRow(
  3074. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.submitDisable")).WithCallbackData("add_client_submit_disable"),
  3075. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.submitEnable")).WithCallbackData("add_client_submit_enable"),
  3076. ),
  3077. tu.InlineKeyboardRow(
  3078. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData("add_client_cancel"),
  3079. ),
  3080. )
  3081. if len(messageID) > 0 {
  3082. t.editMessageTgBot(chatId, messageID[0], msg, inlineKeyboard)
  3083. } else {
  3084. t.SendMsgToTgbot(chatId, msg, inlineKeyboard)
  3085. }
  3086. case model.Trojan:
  3087. inlineKeyboard := tu.InlineKeyboard(
  3088. tu.InlineKeyboardRow(
  3089. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.change_email")).WithCallbackData("add_client_ch_default_email"),
  3090. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.change_password")).WithCallbackData("add_client_ch_default_pass_tr"),
  3091. ),
  3092. tu.InlineKeyboardRow(
  3093. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.limitTraffic")).WithCallbackData("add_client_ch_default_traffic"),
  3094. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.resetExpire")).WithCallbackData("add_client_ch_default_exp"),
  3095. ),
  3096. tu.InlineKeyboardRow(
  3097. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.change_comment")).WithCallbackData("add_client_ch_default_comment"),
  3098. tu.InlineKeyboardButton("ip limit").WithCallbackData("add_client_ch_default_ip_limit"),
  3099. ),
  3100. tu.InlineKeyboardRow(
  3101. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.submitDisable")).WithCallbackData("add_client_submit_disable"),
  3102. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.submitEnable")).WithCallbackData("add_client_submit_enable"),
  3103. ),
  3104. tu.InlineKeyboardRow(
  3105. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData("add_client_cancel"),
  3106. ),
  3107. )
  3108. if len(messageID) > 0 {
  3109. t.editMessageTgBot(chatId, messageID[0], msg, inlineKeyboard)
  3110. } else {
  3111. t.SendMsgToTgbot(chatId, msg, inlineKeyboard)
  3112. }
  3113. case model.Shadowsocks:
  3114. inlineKeyboard := tu.InlineKeyboard(
  3115. tu.InlineKeyboardRow(
  3116. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.change_email")).WithCallbackData("add_client_ch_default_email"),
  3117. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.change_password")).WithCallbackData("add_client_ch_default_pass_sh"),
  3118. ),
  3119. tu.InlineKeyboardRow(
  3120. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.limitTraffic")).WithCallbackData("add_client_ch_default_traffic"),
  3121. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.resetExpire")).WithCallbackData("add_client_ch_default_exp"),
  3122. ),
  3123. tu.InlineKeyboardRow(
  3124. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.change_comment")).WithCallbackData("add_client_ch_default_comment"),
  3125. tu.InlineKeyboardButton("ip limit").WithCallbackData("add_client_ch_default_ip_limit"),
  3126. ),
  3127. tu.InlineKeyboardRow(
  3128. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.submitDisable")).WithCallbackData("add_client_submit_disable"),
  3129. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.submitEnable")).WithCallbackData("add_client_submit_enable"),
  3130. ),
  3131. tu.InlineKeyboardRow(
  3132. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData("add_client_cancel"),
  3133. ),
  3134. )
  3135. if len(messageID) > 0 {
  3136. t.editMessageTgBot(chatId, messageID[0], msg, inlineKeyboard)
  3137. } else {
  3138. t.SendMsgToTgbot(chatId, msg, inlineKeyboard)
  3139. }
  3140. }
  3141. }
  3142. // searchInbound searches for inbounds by remark and sends the results.
  3143. func (t *Tgbot) searchInbound(chatId int64, remark string) {
  3144. inbounds, err := t.inboundService.SearchInbounds(remark)
  3145. if err != nil {
  3146. logger.Warning(err)
  3147. msg := t.I18nBot("tgbot.wentWrong")
  3148. t.SendMsgToTgbot(chatId, msg)
  3149. return
  3150. }
  3151. if len(inbounds) == 0 {
  3152. msg := t.I18nBot("tgbot.noInbounds")
  3153. t.SendMsgToTgbot(chatId, msg)
  3154. return
  3155. }
  3156. for _, inbound := range inbounds {
  3157. info := ""
  3158. info += t.I18nBot("tgbot.messages.inbound", "Remark=="+inbound.Remark)
  3159. info += t.I18nBot("tgbot.messages.port", "Port=="+strconv.Itoa(inbound.Port))
  3160. info += t.I18nBot("tgbot.messages.traffic", "Total=="+common.FormatTraffic((inbound.Up+inbound.Down)), "Upload=="+common.FormatTraffic(inbound.Up), "Download=="+common.FormatTraffic(inbound.Down))
  3161. if inbound.ExpiryTime == 0 {
  3162. info += t.I18nBot("tgbot.messages.expire", "Time=="+t.I18nBot("tgbot.unlimited"))
  3163. } else {
  3164. info += t.I18nBot("tgbot.messages.expire", "Time=="+time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  3165. }
  3166. t.SendMsgToTgbot(chatId, info)
  3167. if len(inbound.ClientStats) > 0 {
  3168. output := ""
  3169. for _, traffic := range inbound.ClientStats {
  3170. output += t.clientInfoMsg(&traffic, true, true, true, true, true, true)
  3171. }
  3172. t.SendMsgToTgbot(chatId, output)
  3173. }
  3174. }
  3175. }
  3176. // getExhausted retrieves and sends information about exhausted clients.
  3177. func (t *Tgbot) getExhausted(chatId int64) {
  3178. trDiff := int64(0)
  3179. exDiff := int64(0)
  3180. now := time.Now().Unix() * 1000
  3181. var exhaustedInbounds []model.Inbound
  3182. var exhaustedClients []xray.ClientTraffic
  3183. var disabledInbounds []model.Inbound
  3184. var disabledClients []xray.ClientTraffic
  3185. TrafficThreshold, err := t.settingService.GetTrafficDiff()
  3186. if err == nil && TrafficThreshold > 0 {
  3187. trDiff = int64(TrafficThreshold) * 1073741824
  3188. }
  3189. ExpireThreshold, err := t.settingService.GetExpireDiff()
  3190. if err == nil && ExpireThreshold > 0 {
  3191. exDiff = int64(ExpireThreshold) * 86400000
  3192. }
  3193. inbounds, err := t.inboundService.GetAllInbounds()
  3194. if err != nil {
  3195. logger.Warning("Unable to load Inbounds", err)
  3196. }
  3197. for _, inbound := range inbounds {
  3198. if inbound.Enable {
  3199. if (inbound.ExpiryTime > 0 && (inbound.ExpiryTime-now < exDiff)) ||
  3200. (inbound.Total > 0 && (inbound.Total-(inbound.Up+inbound.Down) < trDiff)) {
  3201. exhaustedInbounds = append(exhaustedInbounds, *inbound)
  3202. }
  3203. if len(inbound.ClientStats) > 0 {
  3204. for _, client := range inbound.ClientStats {
  3205. if client.Enable {
  3206. if (client.ExpiryTime > 0 && (client.ExpiryTime-now < exDiff)) ||
  3207. (client.Total > 0 && (client.Total-(client.Up+client.Down) < trDiff)) {
  3208. exhaustedClients = append(exhaustedClients, client)
  3209. }
  3210. } else {
  3211. disabledClients = append(disabledClients, client)
  3212. }
  3213. }
  3214. }
  3215. } else {
  3216. disabledInbounds = append(disabledInbounds, *inbound)
  3217. }
  3218. }
  3219. // Inbounds
  3220. output := ""
  3221. output += t.I18nBot("tgbot.messages.exhaustedCount", "Type=="+t.I18nBot("tgbot.inbounds"))
  3222. output += t.I18nBot("tgbot.messages.disabled", "Disabled=="+strconv.Itoa(len(disabledInbounds)))
  3223. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+strconv.Itoa(len(exhaustedInbounds)))
  3224. if len(exhaustedInbounds) > 0 {
  3225. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+t.I18nBot("tgbot.inbounds"))
  3226. for _, inbound := range exhaustedInbounds {
  3227. output += t.I18nBot("tgbot.messages.inbound", "Remark=="+inbound.Remark)
  3228. output += t.I18nBot("tgbot.messages.port", "Port=="+strconv.Itoa(inbound.Port))
  3229. output += t.I18nBot("tgbot.messages.traffic", "Total=="+common.FormatTraffic((inbound.Up+inbound.Down)), "Upload=="+common.FormatTraffic(inbound.Up), "Download=="+common.FormatTraffic(inbound.Down))
  3230. if inbound.ExpiryTime == 0 {
  3231. output += t.I18nBot("tgbot.messages.expire", "Time=="+t.I18nBot("tgbot.unlimited"))
  3232. } else {
  3233. output += t.I18nBot("tgbot.messages.expire", "Time=="+time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  3234. }
  3235. output += "\r\n"
  3236. }
  3237. }
  3238. // Clients
  3239. exhaustedCC := len(exhaustedClients)
  3240. output += t.I18nBot("tgbot.messages.exhaustedCount", "Type=="+t.I18nBot("tgbot.clients"))
  3241. output += t.I18nBot("tgbot.messages.disabled", "Disabled=="+strconv.Itoa(len(disabledClients)))
  3242. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+strconv.Itoa(exhaustedCC))
  3243. if exhaustedCC > 0 {
  3244. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+t.I18nBot("tgbot.clients"))
  3245. var buttons []telego.InlineKeyboardButton
  3246. for _, traffic := range exhaustedClients {
  3247. output += t.clientInfoMsg(&traffic, true, false, false, true, true, false)
  3248. output += "\r\n"
  3249. buttons = append(buttons, tu.InlineKeyboardButton(traffic.Email).WithCallbackData(t.encodeQuery("client_get_usage "+traffic.Email)))
  3250. }
  3251. cols := 0
  3252. if exhaustedCC < 11 {
  3253. cols = 1
  3254. } else {
  3255. cols = 2
  3256. }
  3257. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  3258. keyboard := tu.InlineKeyboardGrid(tu.InlineKeyboardCols(cols, buttons...))
  3259. t.SendMsgToTgbot(chatId, output, keyboard)
  3260. } else {
  3261. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  3262. t.SendMsgToTgbot(chatId, output)
  3263. }
  3264. }
  3265. // notifyExhausted sends notifications for exhausted clients.
  3266. func (t *Tgbot) notifyExhausted() {
  3267. trDiff := int64(0)
  3268. exDiff := int64(0)
  3269. now := time.Now().Unix() * 1000
  3270. TrafficThreshold, err := t.settingService.GetTrafficDiff()
  3271. if err == nil && TrafficThreshold > 0 {
  3272. trDiff = int64(TrafficThreshold) * 1073741824
  3273. }
  3274. ExpireThreshold, err := t.settingService.GetExpireDiff()
  3275. if err == nil && ExpireThreshold > 0 {
  3276. exDiff = int64(ExpireThreshold) * 86400000
  3277. }
  3278. inbounds, err := t.inboundService.GetAllInbounds()
  3279. if err != nil {
  3280. logger.Warning("Unable to load Inbounds", err)
  3281. }
  3282. var chatIDsDone []int64
  3283. for _, inbound := range inbounds {
  3284. if inbound.Enable {
  3285. if len(inbound.ClientStats) > 0 {
  3286. clients, err := t.inboundService.GetClients(inbound)
  3287. if err == nil {
  3288. for _, client := range clients {
  3289. if client.TgID != 0 {
  3290. chatID := client.TgID
  3291. if !int64Contains(chatIDsDone, chatID) && !checkAdmin(chatID) {
  3292. var disabledClients []xray.ClientTraffic
  3293. var exhaustedClients []xray.ClientTraffic
  3294. traffics, err := t.inboundService.GetClientTrafficTgBot(client.TgID)
  3295. if err == nil && len(traffics) > 0 {
  3296. output := t.I18nBot("tgbot.messages.exhaustedCount", "Type=="+t.I18nBot("tgbot.clients"))
  3297. for _, traffic := range traffics {
  3298. if traffic.Enable {
  3299. if (traffic.ExpiryTime > 0 && (traffic.ExpiryTime-now < exDiff)) ||
  3300. (traffic.Total > 0 && (traffic.Total-(traffic.Up+traffic.Down) < trDiff)) {
  3301. exhaustedClients = append(exhaustedClients, *traffic)
  3302. }
  3303. } else {
  3304. disabledClients = append(disabledClients, *traffic)
  3305. }
  3306. }
  3307. if len(exhaustedClients) > 0 {
  3308. output += t.I18nBot("tgbot.messages.disabled", "Disabled=="+strconv.Itoa(len(disabledClients)))
  3309. if len(disabledClients) > 0 {
  3310. output += t.I18nBot("tgbot.clients") + ":\r\n"
  3311. for _, traffic := range disabledClients {
  3312. output += " " + traffic.Email
  3313. }
  3314. output += "\r\n"
  3315. }
  3316. output += "\r\n"
  3317. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+strconv.Itoa(len(exhaustedClients)))
  3318. for _, traffic := range exhaustedClients {
  3319. output += t.clientInfoMsg(&traffic, true, false, false, true, true, false)
  3320. output += "\r\n"
  3321. }
  3322. t.SendMsgToTgbot(chatID, output)
  3323. }
  3324. chatIDsDone = append(chatIDsDone, chatID)
  3325. }
  3326. }
  3327. }
  3328. }
  3329. }
  3330. }
  3331. }
  3332. }
  3333. }
  3334. // int64Contains checks if an int64 slice contains a specific item.
  3335. func int64Contains(slice []int64, item int64) bool {
  3336. for _, s := range slice {
  3337. if s == item {
  3338. return true
  3339. }
  3340. }
  3341. return false
  3342. }
  3343. // onlineClients retrieves and sends information about online clients.
  3344. func (t *Tgbot) onlineClients(chatId int64, messageID ...int) {
  3345. if !p.IsRunning() {
  3346. return
  3347. }
  3348. onlines := p.GetOnlineClients()
  3349. onlinesCount := len(onlines)
  3350. output := t.I18nBot("tgbot.messages.onlinesCount", "Count=="+fmt.Sprint(onlinesCount))
  3351. keyboard := tu.InlineKeyboard(tu.InlineKeyboardRow(
  3352. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(t.encodeQuery("onlines_refresh"))))
  3353. if onlinesCount > 0 {
  3354. var buttons []telego.InlineKeyboardButton
  3355. for _, online := range onlines {
  3356. buttons = append(buttons, tu.InlineKeyboardButton(online).WithCallbackData(t.encodeQuery("client_get_usage "+online)))
  3357. }
  3358. cols := 0
  3359. if onlinesCount < 21 {
  3360. cols = 2
  3361. } else if onlinesCount < 61 {
  3362. cols = 3
  3363. } else {
  3364. cols = 4
  3365. }
  3366. keyboard.InlineKeyboard = append(keyboard.InlineKeyboard, tu.InlineKeyboardCols(cols, buttons...)...)
  3367. }
  3368. if len(messageID) > 0 {
  3369. t.editMessageTgBot(chatId, messageID[0], output, keyboard)
  3370. } else {
  3371. t.SendMsgToTgbot(chatId, output, keyboard)
  3372. }
  3373. }
  3374. // sendBackup sends a backup of the database and configuration files.
  3375. func (t *Tgbot) sendBackup(chatId int64) {
  3376. output := t.I18nBot("tgbot.messages.backupTime", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  3377. t.SendMsgToTgbot(chatId, output)
  3378. // Update by manually trigger a checkpoint operation
  3379. err := database.Checkpoint()
  3380. if err != nil {
  3381. logger.Error("Error in trigger a checkpoint operation: ", err)
  3382. }
  3383. // Send database backup
  3384. file, err := os.Open(config.GetDBPath())
  3385. if err == nil {
  3386. defer file.Close()
  3387. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  3388. defer cancel()
  3389. document := tu.Document(
  3390. tu.ID(chatId),
  3391. tu.File(file),
  3392. )
  3393. _, err = bot.SendDocument(ctx, document)
  3394. if err != nil {
  3395. logger.Error("Error in uploading backup: ", err)
  3396. }
  3397. } else {
  3398. logger.Error("Error in opening db file for backup: ", err)
  3399. }
  3400. // Small delay between file sends
  3401. time.Sleep(500 * time.Millisecond)
  3402. // Send config.json backup
  3403. file, err = os.Open(xray.GetConfigPath())
  3404. if err == nil {
  3405. defer file.Close()
  3406. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  3407. defer cancel()
  3408. document := tu.Document(
  3409. tu.ID(chatId),
  3410. tu.File(file),
  3411. )
  3412. _, err = bot.SendDocument(ctx, document)
  3413. if err != nil {
  3414. logger.Error("Error in uploading config.json: ", err)
  3415. }
  3416. } else {
  3417. logger.Error("Error in opening config.json file for backup: ", err)
  3418. }
  3419. }
  3420. // sendBanLogs sends the ban logs to the specified chat.
  3421. func (t *Tgbot) sendBanLogs(chatId int64, dt bool) {
  3422. if dt {
  3423. output := t.I18nBot("tgbot.messages.datetime", "DateTime=="+time.Now().Format("2006-01-02 15:04:05"))
  3424. t.SendMsgToTgbot(chatId, output)
  3425. }
  3426. file, err := os.Open(xray.GetIPLimitBannedPrevLogPath())
  3427. if err == nil {
  3428. // Check if the file is non-empty before attempting to upload
  3429. fileInfo, _ := file.Stat()
  3430. if fileInfo.Size() > 0 {
  3431. document := tu.Document(
  3432. tu.ID(chatId),
  3433. tu.File(file),
  3434. )
  3435. _, err = bot.SendDocument(context.Background(), document)
  3436. if err != nil {
  3437. logger.Error("Error in uploading IPLimitBannedPrevLog: ", err)
  3438. }
  3439. } else {
  3440. logger.Warning("IPLimitBannedPrevLog file is empty, not uploading.")
  3441. }
  3442. file.Close()
  3443. } else {
  3444. logger.Error("Error in opening IPLimitBannedPrevLog file for backup: ", err)
  3445. }
  3446. file, err = os.Open(xray.GetIPLimitBannedLogPath())
  3447. if err == nil {
  3448. // Check if the file is non-empty before attempting to upload
  3449. fileInfo, _ := file.Stat()
  3450. if fileInfo.Size() > 0 {
  3451. document := tu.Document(
  3452. tu.ID(chatId),
  3453. tu.File(file),
  3454. )
  3455. _, err = bot.SendDocument(context.Background(), document)
  3456. if err != nil {
  3457. logger.Error("Error in uploading IPLimitBannedLog: ", err)
  3458. }
  3459. } else {
  3460. logger.Warning("IPLimitBannedLog file is empty, not uploading.")
  3461. }
  3462. file.Close()
  3463. } else {
  3464. logger.Error("Error in opening IPLimitBannedLog file for backup: ", err)
  3465. }
  3466. }
  3467. // sendCallbackAnswerTgBot answers a callback query with a message.
  3468. func (t *Tgbot) sendCallbackAnswerTgBot(id string, message string) {
  3469. params := telego.AnswerCallbackQueryParams{
  3470. CallbackQueryID: id,
  3471. Text: message,
  3472. }
  3473. if err := bot.AnswerCallbackQuery(context.Background(), &params); err != nil {
  3474. logger.Warning(err)
  3475. }
  3476. }
  3477. // editMessageCallbackTgBot edits the reply markup of a message.
  3478. func (t *Tgbot) editMessageCallbackTgBot(chatId int64, messageID int, inlineKeyboard *telego.InlineKeyboardMarkup) {
  3479. params := telego.EditMessageReplyMarkupParams{
  3480. ChatID: tu.ID(chatId),
  3481. MessageID: messageID,
  3482. ReplyMarkup: inlineKeyboard,
  3483. }
  3484. if _, err := bot.EditMessageReplyMarkup(context.Background(), &params); err != nil {
  3485. logger.Warning(err)
  3486. }
  3487. }
  3488. // editMessageTgBot edits the text and reply markup of a message.
  3489. func (t *Tgbot) editMessageTgBot(chatId int64, messageID int, text string, inlineKeyboard ...*telego.InlineKeyboardMarkup) {
  3490. params := telego.EditMessageTextParams{
  3491. ChatID: tu.ID(chatId),
  3492. MessageID: messageID,
  3493. Text: text,
  3494. ParseMode: "HTML",
  3495. }
  3496. if len(inlineKeyboard) > 0 {
  3497. params.ReplyMarkup = inlineKeyboard[0]
  3498. }
  3499. if _, err := bot.EditMessageText(context.Background(), &params); err != nil {
  3500. logger.Warning(err)
  3501. }
  3502. }
  3503. // SendMsgToTgbotDeleteAfter sends a message and deletes it after a specified delay.
  3504. func (t *Tgbot) SendMsgToTgbotDeleteAfter(chatId int64, msg string, delayInSeconds int, replyMarkup ...telego.ReplyMarkup) {
  3505. // Determine if replyMarkup was passed; otherwise, set it to nil
  3506. var replyMarkupParam telego.ReplyMarkup
  3507. if len(replyMarkup) > 0 {
  3508. replyMarkupParam = replyMarkup[0] // Use the first element
  3509. }
  3510. // Send the message
  3511. sentMsg, err := bot.SendMessage(context.Background(), &telego.SendMessageParams{
  3512. ChatID: tu.ID(chatId),
  3513. Text: msg,
  3514. ReplyMarkup: replyMarkupParam, // Use the correct replyMarkup value
  3515. })
  3516. if err != nil {
  3517. logger.Warning("Failed to send message:", err)
  3518. return
  3519. }
  3520. // Delete the sent message after the specified number of seconds
  3521. go func() {
  3522. time.Sleep(time.Duration(delayInSeconds) * time.Second) // Wait for the specified delay
  3523. t.deleteMessageTgBot(chatId, sentMsg.MessageID) // Delete the message
  3524. delete(userStates, chatId)
  3525. }()
  3526. }
  3527. // deleteMessageTgBot deletes a message from the chat.
  3528. func (t *Tgbot) deleteMessageTgBot(chatId int64, messageID int) {
  3529. params := telego.DeleteMessageParams{
  3530. ChatID: tu.ID(chatId),
  3531. MessageID: messageID,
  3532. }
  3533. if err := bot.DeleteMessage(context.Background(), &params); err != nil {
  3534. logger.Warning("Failed to delete message:", err)
  3535. } else {
  3536. logger.Info("Message deleted successfully")
  3537. }
  3538. }
  3539. // isSingleWord checks if the text contains only a single word.
  3540. func (t *Tgbot) isSingleWord(text string) bool {
  3541. text = strings.TrimSpace(text)
  3542. re := regexp.MustCompile(`\s+`)
  3543. return re.MatchString(text)
  3544. }