tgbot.go 145 KB

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