tgbot.go 142 KB

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