tgbot.go 143 KB

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