tgbot.go 142 KB

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