tgbot.go 142 KB

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