1
0

tgbot.go 142 KB

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