1
0

inbound.go 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184
  1. // Package service provides business logic services for the 3x-ui web panel,
  2. // including inbound/outbound management, user administration, settings, and Xray integration.
  3. package service
  4. import (
  5. "encoding/json"
  6. "fmt"
  7. "sort"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/google/uuid"
  12. "github.com/mhsanaei/3x-ui/v2/database"
  13. "github.com/mhsanaei/3x-ui/v2/database/model"
  14. "github.com/mhsanaei/3x-ui/v2/logger"
  15. "github.com/mhsanaei/3x-ui/v2/util/common"
  16. "github.com/mhsanaei/3x-ui/v2/xray"
  17. "gorm.io/gorm"
  18. )
  19. // InboundService provides business logic for managing Xray inbound configurations.
  20. // It handles CRUD operations for inbounds, client management, traffic monitoring,
  21. // and integration with the Xray API for real-time updates.
  22. type InboundService struct {
  23. xrayApi xray.XrayAPI
  24. }
  25. type CopyClientsResult struct {
  26. Added []string `json:"added"`
  27. Skipped []string `json:"skipped"`
  28. Errors []string `json:"errors"`
  29. }
  30. // GetInbounds retrieves all inbounds for a specific user.
  31. // Returns a slice of inbound models with their associated client statistics.
  32. func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) {
  33. db := database.GetDB()
  34. var inbounds []*model.Inbound
  35. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Find(&inbounds).Error
  36. if err != nil && err != gorm.ErrRecordNotFound {
  37. return nil, err
  38. }
  39. // Enrich client stats with UUID/SubId from inbound settings
  40. for _, inbound := range inbounds {
  41. clients, _ := s.GetClients(inbound)
  42. if len(clients) == 0 || len(inbound.ClientStats) == 0 {
  43. continue
  44. }
  45. // Build a map email -> client
  46. cMap := make(map[string]model.Client, len(clients))
  47. for _, c := range clients {
  48. cMap[strings.ToLower(c.Email)] = c
  49. }
  50. for i := range inbound.ClientStats {
  51. email := strings.ToLower(inbound.ClientStats[i].Email)
  52. if c, ok := cMap[email]; ok {
  53. inbound.ClientStats[i].UUID = c.ID
  54. inbound.ClientStats[i].SubId = c.SubID
  55. }
  56. }
  57. }
  58. return inbounds, nil
  59. }
  60. // GetAllInbounds retrieves all inbounds from the database.
  61. // Returns a slice of all inbound models with their associated client statistics.
  62. func (s *InboundService) GetAllInbounds() ([]*model.Inbound, error) {
  63. db := database.GetDB()
  64. var inbounds []*model.Inbound
  65. err := db.Model(model.Inbound{}).Preload("ClientStats").Find(&inbounds).Error
  66. if err != nil && err != gorm.ErrRecordNotFound {
  67. return nil, err
  68. }
  69. // Enrich client stats with UUID/SubId from inbound settings
  70. for _, inbound := range inbounds {
  71. clients, _ := s.GetClients(inbound)
  72. if len(clients) == 0 || len(inbound.ClientStats) == 0 {
  73. continue
  74. }
  75. cMap := make(map[string]model.Client, len(clients))
  76. for _, c := range clients {
  77. cMap[strings.ToLower(c.Email)] = c
  78. }
  79. for i := range inbound.ClientStats {
  80. email := strings.ToLower(inbound.ClientStats[i].Email)
  81. if c, ok := cMap[email]; ok {
  82. inbound.ClientStats[i].UUID = c.ID
  83. inbound.ClientStats[i].SubId = c.SubID
  84. }
  85. }
  86. }
  87. return inbounds, nil
  88. }
  89. func (s *InboundService) GetInboundsByTrafficReset(period string) ([]*model.Inbound, error) {
  90. db := database.GetDB()
  91. var inbounds []*model.Inbound
  92. err := db.Model(model.Inbound{}).Where("traffic_reset = ?", period).Find(&inbounds).Error
  93. if err != nil && err != gorm.ErrRecordNotFound {
  94. return nil, err
  95. }
  96. return inbounds, nil
  97. }
  98. func (s *InboundService) GetClients(inbound *model.Inbound) ([]model.Client, error) {
  99. settings := map[string][]model.Client{}
  100. json.Unmarshal([]byte(inbound.Settings), &settings)
  101. if settings == nil {
  102. return nil, fmt.Errorf("setting is null")
  103. }
  104. clients := settings["clients"]
  105. if clients == nil {
  106. return nil, nil
  107. }
  108. return clients, nil
  109. }
  110. func (s *InboundService) getAllEmails() ([]string, error) {
  111. db := database.GetDB()
  112. var emails []string
  113. err := db.Raw(`
  114. SELECT JSON_EXTRACT(client.value, '$.email')
  115. FROM inbounds,
  116. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  117. `).Scan(&emails).Error
  118. if err != nil {
  119. return nil, err
  120. }
  121. return emails, nil
  122. }
  123. func (s *InboundService) contains(slice []string, str string) bool {
  124. lowerStr := strings.ToLower(str)
  125. for _, s := range slice {
  126. if strings.ToLower(s) == lowerStr {
  127. return true
  128. }
  129. }
  130. return false
  131. }
  132. func (s *InboundService) checkEmailsExistForClients(clients []model.Client) (string, error) {
  133. allEmails, err := s.getAllEmails()
  134. if err != nil {
  135. return "", err
  136. }
  137. var emails []string
  138. for _, client := range clients {
  139. if client.Email != "" {
  140. if s.contains(emails, client.Email) {
  141. return client.Email, nil
  142. }
  143. if s.contains(allEmails, client.Email) {
  144. return client.Email, nil
  145. }
  146. emails = append(emails, client.Email)
  147. }
  148. }
  149. return "", nil
  150. }
  151. func (s *InboundService) checkEmailExistForInbound(inbound *model.Inbound) (string, error) {
  152. clients, err := s.GetClients(inbound)
  153. if err != nil {
  154. return "", err
  155. }
  156. allEmails, err := s.getAllEmails()
  157. if err != nil {
  158. return "", err
  159. }
  160. var emails []string
  161. for _, client := range clients {
  162. if client.Email != "" {
  163. if s.contains(emails, client.Email) {
  164. return client.Email, nil
  165. }
  166. if s.contains(allEmails, client.Email) {
  167. return client.Email, nil
  168. }
  169. emails = append(emails, client.Email)
  170. }
  171. }
  172. return "", nil
  173. }
  174. // AddInbound creates a new inbound configuration.
  175. // It validates port uniqueness, client email uniqueness, and required fields,
  176. // then saves the inbound to the database and optionally adds it to the running Xray instance.
  177. // Returns the created inbound, whether Xray needs restart, and any error.
  178. func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  179. exist, err := s.checkPortConflict(inbound, 0)
  180. if err != nil {
  181. return inbound, false, err
  182. }
  183. if exist {
  184. return inbound, false, common.NewError("Port already exists:", inbound.Port)
  185. }
  186. // pick a tag that won't collide with an existing row. for the common
  187. // case this is the same "inbound-<port>" string the controller already
  188. // set; only when this port already has another inbound on a different
  189. // transport (now possible after the transport-aware port check) does
  190. // this disambiguate with a -tcp/-udp suffix. see #4103.
  191. inbound.Tag, err = s.generateInboundTag(inbound, 0)
  192. if err != nil {
  193. return inbound, false, err
  194. }
  195. existEmail, err := s.checkEmailExistForInbound(inbound)
  196. if err != nil {
  197. return inbound, false, err
  198. }
  199. if existEmail != "" {
  200. return inbound, false, common.NewError("Duplicate email:", existEmail)
  201. }
  202. clients, err := s.GetClients(inbound)
  203. if err != nil {
  204. return inbound, false, err
  205. }
  206. // Ensure created_at and updated_at on clients in settings
  207. if len(clients) > 0 {
  208. var settings map[string]any
  209. if err2 := json.Unmarshal([]byte(inbound.Settings), &settings); err2 == nil && settings != nil {
  210. now := time.Now().Unix() * 1000
  211. updatedClients := make([]model.Client, 0, len(clients))
  212. for _, c := range clients {
  213. if c.CreatedAt == 0 {
  214. c.CreatedAt = now
  215. }
  216. c.UpdatedAt = now
  217. updatedClients = append(updatedClients, c)
  218. }
  219. settings["clients"] = updatedClients
  220. if bs, err3 := json.MarshalIndent(settings, "", " "); err3 == nil {
  221. inbound.Settings = string(bs)
  222. } else {
  223. logger.Debug("Unable to marshal inbound settings with timestamps:", err3)
  224. }
  225. } else if err2 != nil {
  226. logger.Debug("Unable to parse inbound settings for timestamps:", err2)
  227. }
  228. }
  229. // Secure client ID
  230. for _, client := range clients {
  231. switch inbound.Protocol {
  232. case "trojan":
  233. if client.Password == "" {
  234. return inbound, false, common.NewError("empty client ID")
  235. }
  236. case "shadowsocks":
  237. if client.Email == "" {
  238. return inbound, false, common.NewError("empty client ID")
  239. }
  240. case "hysteria", "hysteria2":
  241. if client.Auth == "" {
  242. return inbound, false, common.NewError("empty client ID")
  243. }
  244. default:
  245. if client.ID == "" {
  246. return inbound, false, common.NewError("empty client ID")
  247. }
  248. }
  249. }
  250. db := database.GetDB()
  251. tx := db.Begin()
  252. defer func() {
  253. if err == nil {
  254. tx.Commit()
  255. } else {
  256. tx.Rollback()
  257. }
  258. }()
  259. err = tx.Save(inbound).Error
  260. if err == nil {
  261. if len(inbound.ClientStats) == 0 {
  262. for _, client := range clients {
  263. s.AddClientStat(tx, inbound.Id, &client)
  264. }
  265. }
  266. } else {
  267. return inbound, false, err
  268. }
  269. needRestart := false
  270. if inbound.Enable {
  271. s.xrayApi.Init(p.GetAPIPort())
  272. inboundJson, err1 := json.MarshalIndent(inbound.GenXrayInboundConfig(), "", " ")
  273. if err1 != nil {
  274. logger.Debug("Unable to marshal inbound config:", err1)
  275. }
  276. err1 = s.xrayApi.AddInbound(inboundJson)
  277. if err1 == nil {
  278. logger.Debug("New inbound added by api:", inbound.Tag)
  279. } else {
  280. logger.Debug("Unable to add inbound by api:", err1)
  281. needRestart = true
  282. }
  283. s.xrayApi.Close()
  284. }
  285. return inbound, needRestart, err
  286. }
  287. // DelInbound deletes an inbound configuration by ID.
  288. // It removes the inbound from the database and the running Xray instance if active.
  289. // Returns whether Xray needs restart and any error.
  290. func (s *InboundService) DelInbound(id int) (bool, error) {
  291. db := database.GetDB()
  292. var tag string
  293. needRestart := false
  294. result := db.Model(model.Inbound{}).Select("tag").Where("id = ? and enable = ?", id, true).First(&tag)
  295. if result.Error == nil {
  296. s.xrayApi.Init(p.GetAPIPort())
  297. err1 := s.xrayApi.DelInbound(tag)
  298. if err1 == nil {
  299. logger.Debug("Inbound deleted by api:", tag)
  300. } else {
  301. logger.Debug("Unable to delete inbound by api:", err1)
  302. needRestart = true
  303. }
  304. s.xrayApi.Close()
  305. } else {
  306. logger.Debug("No enabled inbound founded to removing by api", tag)
  307. }
  308. // Delete client traffics of inbounds
  309. err := db.Where("inbound_id = ?", id).Delete(xray.ClientTraffic{}).Error
  310. if err != nil {
  311. return false, err
  312. }
  313. inbound, err := s.GetInbound(id)
  314. if err != nil {
  315. return false, err
  316. }
  317. clients, err := s.GetClients(inbound)
  318. if err != nil {
  319. return false, err
  320. }
  321. // Bulk-delete client IPs for every email in this inbound. The previous
  322. // per-client loop fired one DELETE per row — at 7k+ clients that meant
  323. // thousands of synchronous SQL roundtrips and a multi-second freeze.
  324. // Chunked to stay under SQLite's bind-variable limit on huge inbounds.
  325. if len(clients) > 0 {
  326. emails := make([]string, 0, len(clients))
  327. for i := range clients {
  328. if clients[i].Email != "" {
  329. emails = append(emails, clients[i].Email)
  330. }
  331. }
  332. for _, batch := range chunkStrings(uniqueNonEmptyStrings(emails), sqliteMaxVars) {
  333. if err := db.Where("client_email IN ?", batch).
  334. Delete(model.InboundClientIps{}).Error; err != nil {
  335. return false, err
  336. }
  337. }
  338. }
  339. return needRestart, db.Delete(model.Inbound{}, id).Error
  340. }
  341. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  342. db := database.GetDB()
  343. inbound := &model.Inbound{}
  344. err := db.Model(model.Inbound{}).First(inbound, id).Error
  345. if err != nil {
  346. return nil, err
  347. }
  348. return inbound, nil
  349. }
  350. // SetInboundEnable toggles only the enable flag of an inbound, without
  351. // rewriting the (potentially multi-MB) settings JSON. Used by the UI's
  352. // per-row enable switch — for inbounds with thousands of clients the full
  353. // UpdateInbound path is an order of magnitude too slow for an interactive
  354. // toggle (parses + reserialises every client, runs O(N) traffic diff).
  355. //
  356. // Returns (needRestart, error). needRestart is true when the xray runtime
  357. // could not be re-synced from the cached config and a full restart is
  358. // required to pick up the change.
  359. func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
  360. inbound, err := s.GetInbound(id)
  361. if err != nil {
  362. return false, err
  363. }
  364. if inbound.Enable == enable {
  365. return false, nil
  366. }
  367. db := database.GetDB()
  368. if err := db.Model(model.Inbound{}).Where("id = ?", id).
  369. Update("enable", enable).Error; err != nil {
  370. return false, err
  371. }
  372. inbound.Enable = enable
  373. // Sync xray runtime: drop the live inbound, add it back if we're enabling.
  374. // "User not found"-style errors from DelInbound mean the inbound was
  375. // already absent from the live config — that's fine. Any other error
  376. // means the live config and DB diverged, so we ask the caller to
  377. // schedule a restart.
  378. needRestart := false
  379. s.xrayApi.Init(p.GetAPIPort())
  380. defer s.xrayApi.Close()
  381. if err := s.xrayApi.DelInbound(inbound.Tag); err != nil &&
  382. !strings.Contains(err.Error(), "not found") {
  383. logger.Debug("SetInboundEnable: DelInbound via api failed:", err)
  384. needRestart = true
  385. }
  386. if !enable {
  387. return needRestart, nil
  388. }
  389. runtimeInbound, err := s.buildRuntimeInboundForAPI(db, inbound)
  390. if err != nil {
  391. logger.Debug("SetInboundEnable: build runtime config failed:", err)
  392. return true, nil
  393. }
  394. inboundJson, err := json.MarshalIndent(runtimeInbound.GenXrayInboundConfig(), "", " ")
  395. if err != nil {
  396. logger.Debug("SetInboundEnable: marshal runtime config failed:", err)
  397. return true, nil
  398. }
  399. if err := s.xrayApi.AddInbound(inboundJson); err != nil {
  400. logger.Debug("SetInboundEnable: AddInbound via api failed:", err)
  401. needRestart = true
  402. }
  403. return needRestart, nil
  404. }
  405. // UpdateInbound modifies an existing inbound configuration.
  406. // It validates changes, updates the database, and syncs with the running Xray instance.
  407. // Returns the updated inbound, whether Xray needs restart, and any error.
  408. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  409. exist, err := s.checkPortConflict(inbound, inbound.Id)
  410. if err != nil {
  411. return inbound, false, err
  412. }
  413. if exist {
  414. return inbound, false, common.NewError("Port already exists:", inbound.Port)
  415. }
  416. oldInbound, err := s.GetInbound(inbound.Id)
  417. if err != nil {
  418. return inbound, false, err
  419. }
  420. tag := oldInbound.Tag
  421. db := database.GetDB()
  422. tx := db.Begin()
  423. defer func() {
  424. if err != nil {
  425. tx.Rollback()
  426. } else {
  427. tx.Commit()
  428. }
  429. }()
  430. err = s.updateClientTraffics(tx, oldInbound, inbound)
  431. if err != nil {
  432. return inbound, false, err
  433. }
  434. // Ensure created_at and updated_at exist in inbound.Settings clients
  435. {
  436. var oldSettings map[string]any
  437. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  438. emailToCreated := map[string]int64{}
  439. emailToUpdated := map[string]int64{}
  440. if oldSettings != nil {
  441. if oc, ok := oldSettings["clients"].([]any); ok {
  442. for _, it := range oc {
  443. if m, ok2 := it.(map[string]any); ok2 {
  444. if email, ok3 := m["email"].(string); ok3 {
  445. switch v := m["created_at"].(type) {
  446. case float64:
  447. emailToCreated[email] = int64(v)
  448. case int64:
  449. emailToCreated[email] = v
  450. }
  451. switch v := m["updated_at"].(type) {
  452. case float64:
  453. emailToUpdated[email] = int64(v)
  454. case int64:
  455. emailToUpdated[email] = v
  456. }
  457. }
  458. }
  459. }
  460. }
  461. }
  462. var newSettings map[string]any
  463. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  464. now := time.Now().Unix() * 1000
  465. if nSlice, ok := newSettings["clients"].([]any); ok {
  466. for i := range nSlice {
  467. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  468. email, _ := m["email"].(string)
  469. if _, ok3 := m["created_at"]; !ok3 {
  470. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  471. m["created_at"] = v
  472. } else {
  473. m["created_at"] = now
  474. }
  475. }
  476. // Preserve client's updated_at if present; do not bump on parent inbound update
  477. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  478. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  479. m["updated_at"] = v
  480. }
  481. }
  482. nSlice[i] = m
  483. }
  484. }
  485. newSettings["clients"] = nSlice
  486. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  487. inbound.Settings = string(bs)
  488. }
  489. }
  490. }
  491. }
  492. oldInbound.Up = inbound.Up
  493. oldInbound.Down = inbound.Down
  494. oldInbound.Total = inbound.Total
  495. oldInbound.Remark = inbound.Remark
  496. oldInbound.Enable = inbound.Enable
  497. oldInbound.ExpiryTime = inbound.ExpiryTime
  498. oldInbound.TrafficReset = inbound.TrafficReset
  499. oldInbound.Listen = inbound.Listen
  500. oldInbound.Port = inbound.Port
  501. oldInbound.Protocol = inbound.Protocol
  502. oldInbound.Settings = inbound.Settings
  503. oldInbound.StreamSettings = inbound.StreamSettings
  504. oldInbound.Sniffing = inbound.Sniffing
  505. // regenerate tag with collision-aware logic. for this row we pass
  506. // inbound.Id as ignoreId so it doesn't see its own old tag in the db.
  507. oldInbound.Tag, err = s.generateInboundTag(inbound, inbound.Id)
  508. if err != nil {
  509. return inbound, false, err
  510. }
  511. needRestart := false
  512. s.xrayApi.Init(p.GetAPIPort())
  513. if s.xrayApi.DelInbound(tag) == nil {
  514. logger.Debug("Old inbound deleted by api:", tag)
  515. }
  516. if inbound.Enable {
  517. runtimeInbound, err2 := s.buildRuntimeInboundForAPI(tx, oldInbound)
  518. if err2 != nil {
  519. logger.Debug("Unable to prepare runtime inbound config:", err2)
  520. needRestart = true
  521. } else {
  522. inboundJson, err2 := json.MarshalIndent(runtimeInbound.GenXrayInboundConfig(), "", " ")
  523. if err2 != nil {
  524. logger.Debug("Unable to marshal updated inbound config:", err2)
  525. needRestart = true
  526. } else {
  527. err2 = s.xrayApi.AddInbound(inboundJson)
  528. if err2 == nil {
  529. logger.Debug("Updated inbound added by api:", oldInbound.Tag)
  530. } else {
  531. logger.Debug("Unable to update inbound by api:", err2)
  532. needRestart = true
  533. }
  534. }
  535. }
  536. }
  537. s.xrayApi.Close()
  538. return inbound, needRestart, tx.Save(oldInbound).Error
  539. }
  540. func (s *InboundService) buildRuntimeInboundForAPI(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  541. if inbound == nil {
  542. return nil, fmt.Errorf("inbound is nil")
  543. }
  544. runtimeInbound := *inbound
  545. settings := map[string]any{}
  546. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  547. return nil, err
  548. }
  549. clients, ok := settings["clients"].([]any)
  550. if !ok {
  551. return &runtimeInbound, nil
  552. }
  553. var clientStats []xray.ClientTraffic
  554. err := tx.Model(xray.ClientTraffic{}).
  555. Where("inbound_id = ?", inbound.Id).
  556. Select("email", "enable").
  557. Find(&clientStats).Error
  558. if err != nil {
  559. return nil, err
  560. }
  561. enableMap := make(map[string]bool, len(clientStats))
  562. for _, clientTraffic := range clientStats {
  563. enableMap[clientTraffic.Email] = clientTraffic.Enable
  564. }
  565. finalClients := make([]any, 0, len(clients))
  566. for _, client := range clients {
  567. c, ok := client.(map[string]any)
  568. if !ok {
  569. continue
  570. }
  571. email, _ := c["email"].(string)
  572. if enable, exists := enableMap[email]; exists && !enable {
  573. continue
  574. }
  575. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  576. continue
  577. }
  578. finalClients = append(finalClients, c)
  579. }
  580. settings["clients"] = finalClients
  581. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  582. if err != nil {
  583. return nil, err
  584. }
  585. runtimeInbound.Settings = string(modifiedSettings)
  586. return &runtimeInbound, nil
  587. }
  588. // updateClientTraffics syncs the ClientTraffic rows with the inbound's clients
  589. // list: removes rows for emails that disappeared, inserts rows for newly-added
  590. // emails. Uses sets for O(N) lookup — the previous nested-loop implementation
  591. // was O(N²) and degraded into multi-second pauses on inbounds with thousands
  592. // of clients (toggling, saving, or deleting any such inbound felt frozen).
  593. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  594. oldClients, err := s.GetClients(oldInbound)
  595. if err != nil {
  596. return err
  597. }
  598. newClients, err := s.GetClients(newInbound)
  599. if err != nil {
  600. return err
  601. }
  602. // Email is the unique key for ClientTraffic rows. Clients without an
  603. // email have no stats row to sync — skip them on both sides instead of
  604. // risking a unique-constraint hit or accidental delete of an unrelated row.
  605. oldEmails := make(map[string]struct{}, len(oldClients))
  606. for i := range oldClients {
  607. if oldClients[i].Email == "" {
  608. continue
  609. }
  610. oldEmails[oldClients[i].Email] = struct{}{}
  611. }
  612. newEmails := make(map[string]struct{}, len(newClients))
  613. for i := range newClients {
  614. if newClients[i].Email == "" {
  615. continue
  616. }
  617. newEmails[newClients[i].Email] = struct{}{}
  618. }
  619. // Removed clients — drop their stats rows.
  620. for i := range oldClients {
  621. email := oldClients[i].Email
  622. if email == "" {
  623. continue
  624. }
  625. if _, kept := newEmails[email]; kept {
  626. continue
  627. }
  628. if err := s.DelClientStat(tx, email); err != nil {
  629. return err
  630. }
  631. }
  632. // Added clients — create their stats rows.
  633. for i := range newClients {
  634. email := newClients[i].Email
  635. if email == "" {
  636. continue
  637. }
  638. if _, existed := oldEmails[email]; existed {
  639. continue
  640. }
  641. if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil {
  642. return err
  643. }
  644. }
  645. return nil
  646. }
  647. func (s *InboundService) AddInboundClient(data *model.Inbound) (bool, error) {
  648. clients, err := s.GetClients(data)
  649. if err != nil {
  650. return false, err
  651. }
  652. var settings map[string]any
  653. err = json.Unmarshal([]byte(data.Settings), &settings)
  654. if err != nil {
  655. return false, err
  656. }
  657. interfaceClients := settings["clients"].([]any)
  658. // Add timestamps for new clients being appended
  659. nowTs := time.Now().Unix() * 1000
  660. for i := range interfaceClients {
  661. if cm, ok := interfaceClients[i].(map[string]any); ok {
  662. if _, ok2 := cm["created_at"]; !ok2 {
  663. cm["created_at"] = nowTs
  664. }
  665. cm["updated_at"] = nowTs
  666. interfaceClients[i] = cm
  667. }
  668. }
  669. existEmail, err := s.checkEmailsExistForClients(clients)
  670. if err != nil {
  671. return false, err
  672. }
  673. if existEmail != "" {
  674. return false, common.NewError("Duplicate email:", existEmail)
  675. }
  676. oldInbound, err := s.GetInbound(data.Id)
  677. if err != nil {
  678. return false, err
  679. }
  680. // Secure client ID
  681. for _, client := range clients {
  682. switch oldInbound.Protocol {
  683. case "trojan":
  684. if client.Password == "" {
  685. return false, common.NewError("empty client ID")
  686. }
  687. case "shadowsocks":
  688. if client.Email == "" {
  689. return false, common.NewError("empty client ID")
  690. }
  691. case "hysteria", "hysteria2":
  692. if client.Auth == "" {
  693. return false, common.NewError("empty client ID")
  694. }
  695. default:
  696. if client.ID == "" {
  697. return false, common.NewError("empty client ID")
  698. }
  699. }
  700. }
  701. var oldSettings map[string]any
  702. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  703. if err != nil {
  704. return false, err
  705. }
  706. oldClients := oldSettings["clients"].([]any)
  707. oldClients = append(oldClients, interfaceClients...)
  708. oldSettings["clients"] = oldClients
  709. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  710. if err != nil {
  711. return false, err
  712. }
  713. oldInbound.Settings = string(newSettings)
  714. db := database.GetDB()
  715. tx := db.Begin()
  716. defer func() {
  717. if err != nil {
  718. tx.Rollback()
  719. } else {
  720. tx.Commit()
  721. }
  722. }()
  723. needRestart := false
  724. s.xrayApi.Init(p.GetAPIPort())
  725. for _, client := range clients {
  726. if len(client.Email) > 0 {
  727. s.AddClientStat(tx, data.Id, &client)
  728. if client.Enable {
  729. cipher := ""
  730. if oldInbound.Protocol == "shadowsocks" {
  731. cipher = oldSettings["method"].(string)
  732. }
  733. err1 := s.xrayApi.AddUser(string(oldInbound.Protocol), oldInbound.Tag, map[string]any{
  734. "email": client.Email,
  735. "id": client.ID,
  736. "auth": client.Auth,
  737. "security": client.Security,
  738. "flow": client.Flow,
  739. "password": client.Password,
  740. "cipher": cipher,
  741. })
  742. if err1 == nil {
  743. logger.Debug("Client added by api:", client.Email)
  744. } else {
  745. logger.Debug("Error in adding client by api:", err1)
  746. needRestart = true
  747. }
  748. }
  749. } else {
  750. needRestart = true
  751. }
  752. }
  753. s.xrayApi.Close()
  754. return needRestart, tx.Save(oldInbound).Error
  755. }
  756. func (s *InboundService) getClientPrimaryKey(protocol model.Protocol, client model.Client) string {
  757. switch protocol {
  758. case model.Trojan:
  759. return client.Password
  760. case model.Shadowsocks:
  761. return client.Email
  762. case model.Hysteria:
  763. return client.Auth
  764. default:
  765. return client.ID
  766. }
  767. }
  768. func (s *InboundService) writeBackClientSubID(sourceInboundID int, sourceProtocol model.Protocol, client model.Client, subID string) (bool, error) {
  769. client.SubID = subID
  770. client.UpdatedAt = time.Now().UnixMilli()
  771. clientID := s.getClientPrimaryKey(sourceProtocol, client)
  772. if clientID == "" {
  773. return false, common.NewError("empty client ID")
  774. }
  775. settingsBytes, err := json.Marshal(map[string][]model.Client{
  776. "clients": {client},
  777. })
  778. if err != nil {
  779. return false, err
  780. }
  781. updatePayload := &model.Inbound{
  782. Id: sourceInboundID,
  783. Settings: string(settingsBytes),
  784. }
  785. return s.UpdateInboundClient(updatePayload, clientID)
  786. }
  787. func (s *InboundService) generateRandomCredential(targetProtocol model.Protocol) string {
  788. switch targetProtocol {
  789. case model.VMESS, model.VLESS:
  790. return uuid.NewString()
  791. default:
  792. return strings.ReplaceAll(uuid.NewString(), "-", "")
  793. }
  794. }
  795. func (s *InboundService) buildTargetClientFromSource(source model.Client, targetProtocol model.Protocol, email string, flow string) (model.Client, error) {
  796. nowTs := time.Now().UnixMilli()
  797. target := source
  798. target.Email = email
  799. target.CreatedAt = nowTs
  800. target.UpdatedAt = nowTs
  801. target.ID = ""
  802. target.Password = ""
  803. target.Auth = ""
  804. target.Flow = ""
  805. switch targetProtocol {
  806. case model.VMESS:
  807. target.ID = s.generateRandomCredential(targetProtocol)
  808. case model.VLESS:
  809. target.ID = s.generateRandomCredential(targetProtocol)
  810. if flow == "xtls-rprx-vision" || flow == "xtls-rprx-vision-udp443" {
  811. target.Flow = flow
  812. }
  813. case model.Trojan, model.Shadowsocks:
  814. target.Password = s.generateRandomCredential(targetProtocol)
  815. case model.Hysteria:
  816. target.Auth = s.generateRandomCredential(targetProtocol)
  817. default:
  818. target.ID = s.generateRandomCredential(targetProtocol)
  819. }
  820. return target, nil
  821. }
  822. func (s *InboundService) nextAvailableCopiedEmail(originalEmail string, targetID int, occupied map[string]struct{}) string {
  823. base := fmt.Sprintf("%s_%d", originalEmail, targetID)
  824. candidate := base
  825. suffix := 0
  826. for {
  827. if _, exists := occupied[strings.ToLower(candidate)]; !exists {
  828. occupied[strings.ToLower(candidate)] = struct{}{}
  829. return candidate
  830. }
  831. suffix++
  832. candidate = fmt.Sprintf("%s_%d", base, suffix)
  833. }
  834. }
  835. func (s *InboundService) CopyInboundClients(targetInboundID int, sourceInboundID int, clientEmails []string, flow string) (*CopyClientsResult, bool, error) {
  836. result := &CopyClientsResult{
  837. Added: []string{},
  838. Skipped: []string{},
  839. Errors: []string{},
  840. }
  841. if targetInboundID == sourceInboundID {
  842. return result, false, common.NewError("source and target inbounds must be different")
  843. }
  844. targetInbound, err := s.GetInbound(targetInboundID)
  845. if err != nil {
  846. return result, false, err
  847. }
  848. sourceInbound, err := s.GetInbound(sourceInboundID)
  849. if err != nil {
  850. return result, false, err
  851. }
  852. sourceClients, err := s.GetClients(sourceInbound)
  853. if err != nil {
  854. return result, false, err
  855. }
  856. if len(sourceClients) == 0 {
  857. return result, false, nil
  858. }
  859. allowedEmails := map[string]struct{}{}
  860. if len(clientEmails) > 0 {
  861. for _, email := range clientEmails {
  862. allowedEmails[strings.ToLower(strings.TrimSpace(email))] = struct{}{}
  863. }
  864. }
  865. occupiedEmails := map[string]struct{}{}
  866. allEmails, err := s.getAllEmails()
  867. if err != nil {
  868. return result, false, err
  869. }
  870. for _, email := range allEmails {
  871. clean := strings.Trim(email, "\"")
  872. if clean != "" {
  873. occupiedEmails[strings.ToLower(clean)] = struct{}{}
  874. }
  875. }
  876. newClients := make([]model.Client, 0)
  877. needRestart := false
  878. for _, sourceClient := range sourceClients {
  879. originalEmail := strings.TrimSpace(sourceClient.Email)
  880. if originalEmail == "" {
  881. continue
  882. }
  883. if len(allowedEmails) > 0 {
  884. if _, ok := allowedEmails[strings.ToLower(originalEmail)]; !ok {
  885. continue
  886. }
  887. }
  888. if sourceClient.SubID == "" {
  889. newSubID := uuid.NewString()
  890. subNeedRestart, subErr := s.writeBackClientSubID(sourceInbound.Id, sourceInbound.Protocol, sourceClient, newSubID)
  891. if subErr != nil {
  892. result.Errors = append(result.Errors, fmt.Sprintf("%s: failed to write source subId: %v", originalEmail, subErr))
  893. continue
  894. }
  895. if subNeedRestart {
  896. needRestart = true
  897. }
  898. sourceClient.SubID = newSubID
  899. }
  900. targetEmail := s.nextAvailableCopiedEmail(originalEmail, targetInboundID, occupiedEmails)
  901. targetClient, buildErr := s.buildTargetClientFromSource(sourceClient, targetInbound.Protocol, targetEmail, flow)
  902. if buildErr != nil {
  903. result.Errors = append(result.Errors, fmt.Sprintf("%s: %v", originalEmail, buildErr))
  904. continue
  905. }
  906. newClients = append(newClients, targetClient)
  907. result.Added = append(result.Added, targetEmail)
  908. }
  909. if len(newClients) == 0 {
  910. return result, needRestart, nil
  911. }
  912. settingsPayload, err := json.Marshal(map[string][]model.Client{
  913. "clients": newClients,
  914. })
  915. if err != nil {
  916. return result, needRestart, err
  917. }
  918. addNeedRestart, err := s.AddInboundClient(&model.Inbound{
  919. Id: targetInboundID,
  920. Settings: string(settingsPayload),
  921. })
  922. if err != nil {
  923. return result, needRestart, err
  924. }
  925. if addNeedRestart {
  926. needRestart = true
  927. }
  928. return result, needRestart, nil
  929. }
  930. func (s *InboundService) DelInboundClient(inboundId int, clientId string) (bool, error) {
  931. oldInbound, err := s.GetInbound(inboundId)
  932. if err != nil {
  933. logger.Error("Load Old Data Error")
  934. return false, err
  935. }
  936. var settings map[string]any
  937. err = json.Unmarshal([]byte(oldInbound.Settings), &settings)
  938. if err != nil {
  939. return false, err
  940. }
  941. email := ""
  942. client_key := "id"
  943. switch oldInbound.Protocol {
  944. case "trojan":
  945. client_key = "password"
  946. case "shadowsocks":
  947. client_key = "email"
  948. case "hysteria", "hysteria2":
  949. client_key = "auth"
  950. }
  951. interfaceClients := settings["clients"].([]any)
  952. var newClients []any
  953. needApiDel := false
  954. clientFound := false
  955. for _, client := range interfaceClients {
  956. c := client.(map[string]any)
  957. c_id := c[client_key].(string)
  958. if c_id == clientId {
  959. clientFound = true
  960. email, _ = c["email"].(string)
  961. needApiDel, _ = c["enable"].(bool)
  962. } else {
  963. newClients = append(newClients, client)
  964. }
  965. }
  966. if !clientFound {
  967. return false, common.NewError("Client Not Found In Inbound For ID:", clientId)
  968. }
  969. if len(newClients) == 0 {
  970. return false, common.NewError("no client remained in Inbound")
  971. }
  972. settings["clients"] = newClients
  973. newSettings, err := json.MarshalIndent(settings, "", " ")
  974. if err != nil {
  975. return false, err
  976. }
  977. oldInbound.Settings = string(newSettings)
  978. db := database.GetDB()
  979. err = s.DelClientIPs(db, email)
  980. if err != nil {
  981. logger.Error("Error in delete client IPs")
  982. return false, err
  983. }
  984. needRestart := false
  985. if len(email) > 0 {
  986. notDepleted := true
  987. err = db.Model(xray.ClientTraffic{}).Select("enable").Where("email = ?", email).First(&notDepleted).Error
  988. if err != nil {
  989. logger.Error("Get stats error")
  990. return false, err
  991. }
  992. err = s.DelClientStat(db, email)
  993. if err != nil {
  994. logger.Error("Delete stats Data Error")
  995. return false, err
  996. }
  997. if needApiDel && notDepleted {
  998. s.xrayApi.Init(p.GetAPIPort())
  999. err1 := s.xrayApi.RemoveUser(oldInbound.Tag, email)
  1000. if err1 == nil {
  1001. logger.Debug("Client deleted by api:", email)
  1002. needRestart = false
  1003. } else {
  1004. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  1005. logger.Debug("User is already deleted. Nothing to do more...")
  1006. } else {
  1007. logger.Debug("Error in deleting client by api:", err1)
  1008. needRestart = true
  1009. }
  1010. }
  1011. s.xrayApi.Close()
  1012. }
  1013. }
  1014. return needRestart, db.Save(oldInbound).Error
  1015. }
  1016. func (s *InboundService) UpdateInboundClient(data *model.Inbound, clientId string) (bool, error) {
  1017. // TODO: check if TrafficReset field is updating
  1018. clients, err := s.GetClients(data)
  1019. if err != nil {
  1020. return false, err
  1021. }
  1022. var settings map[string]any
  1023. err = json.Unmarshal([]byte(data.Settings), &settings)
  1024. if err != nil {
  1025. return false, err
  1026. }
  1027. interfaceClients := settings["clients"].([]any)
  1028. oldInbound, err := s.GetInbound(data.Id)
  1029. if err != nil {
  1030. return false, err
  1031. }
  1032. oldClients, err := s.GetClients(oldInbound)
  1033. if err != nil {
  1034. return false, err
  1035. }
  1036. oldEmail := ""
  1037. newClientId := ""
  1038. clientIndex := -1
  1039. for index, oldClient := range oldClients {
  1040. oldClientId := ""
  1041. switch oldInbound.Protocol {
  1042. case "trojan":
  1043. oldClientId = oldClient.Password
  1044. newClientId = clients[0].Password
  1045. case "shadowsocks":
  1046. oldClientId = oldClient.Email
  1047. newClientId = clients[0].Email
  1048. case "hysteria", "hysteria2":
  1049. oldClientId = oldClient.Auth
  1050. newClientId = clients[0].Auth
  1051. default:
  1052. oldClientId = oldClient.ID
  1053. newClientId = clients[0].ID
  1054. }
  1055. if clientId == oldClientId {
  1056. oldEmail = oldClient.Email
  1057. clientIndex = index
  1058. break
  1059. }
  1060. }
  1061. // Validate new client ID
  1062. if newClientId == "" || clientIndex == -1 {
  1063. return false, common.NewError("empty client ID")
  1064. }
  1065. if len(clients[0].Email) > 0 && clients[0].Email != oldEmail {
  1066. existEmail, err := s.checkEmailsExistForClients(clients)
  1067. if err != nil {
  1068. return false, err
  1069. }
  1070. if existEmail != "" {
  1071. return false, common.NewError("Duplicate email:", existEmail)
  1072. }
  1073. }
  1074. var oldSettings map[string]any
  1075. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1076. if err != nil {
  1077. return false, err
  1078. }
  1079. settingsClients := oldSettings["clients"].([]any)
  1080. // Preserve created_at and set updated_at for the replacing client
  1081. var preservedCreated any
  1082. if clientIndex >= 0 && clientIndex < len(settingsClients) {
  1083. if oldMap, ok := settingsClients[clientIndex].(map[string]any); ok {
  1084. if v, ok2 := oldMap["created_at"]; ok2 {
  1085. preservedCreated = v
  1086. }
  1087. }
  1088. }
  1089. if len(interfaceClients) > 0 {
  1090. if newMap, ok := interfaceClients[0].(map[string]any); ok {
  1091. if preservedCreated == nil {
  1092. preservedCreated = time.Now().Unix() * 1000
  1093. }
  1094. newMap["created_at"] = preservedCreated
  1095. newMap["updated_at"] = time.Now().Unix() * 1000
  1096. interfaceClients[0] = newMap
  1097. }
  1098. }
  1099. settingsClients[clientIndex] = interfaceClients[0]
  1100. oldSettings["clients"] = settingsClients
  1101. // testseed is only meaningful when at least one VLESS client uses the exact
  1102. // xtls-rprx-vision flow. The client-edit path only rewrites a single client,
  1103. // so re-check the flow set here and strip a stale testseed when nothing in the
  1104. // inbound still warrants it. The full-inbound update path already handles this
  1105. // on the JS side via VLESSSettings.toJson().
  1106. if oldInbound.Protocol == model.VLESS {
  1107. hasVisionFlow := false
  1108. for _, c := range settingsClients {
  1109. cm, ok := c.(map[string]any)
  1110. if !ok {
  1111. continue
  1112. }
  1113. if flow, _ := cm["flow"].(string); flow == "xtls-rprx-vision" {
  1114. hasVisionFlow = true
  1115. break
  1116. }
  1117. }
  1118. if !hasVisionFlow {
  1119. delete(oldSettings, "testseed")
  1120. }
  1121. }
  1122. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  1123. if err != nil {
  1124. return false, err
  1125. }
  1126. oldInbound.Settings = string(newSettings)
  1127. db := database.GetDB()
  1128. tx := db.Begin()
  1129. defer func() {
  1130. if err != nil {
  1131. tx.Rollback()
  1132. } else {
  1133. tx.Commit()
  1134. }
  1135. }()
  1136. if len(clients[0].Email) > 0 {
  1137. if len(oldEmail) > 0 {
  1138. err = s.UpdateClientStat(tx, oldEmail, &clients[0])
  1139. if err != nil {
  1140. return false, err
  1141. }
  1142. err = s.UpdateClientIPs(tx, oldEmail, clients[0].Email)
  1143. if err != nil {
  1144. return false, err
  1145. }
  1146. } else {
  1147. s.AddClientStat(tx, data.Id, &clients[0])
  1148. }
  1149. } else {
  1150. err = s.DelClientStat(tx, oldEmail)
  1151. if err != nil {
  1152. return false, err
  1153. }
  1154. err = s.DelClientIPs(tx, oldEmail)
  1155. if err != nil {
  1156. return false, err
  1157. }
  1158. }
  1159. needRestart := false
  1160. if len(oldEmail) > 0 {
  1161. s.xrayApi.Init(p.GetAPIPort())
  1162. if oldClients[clientIndex].Enable {
  1163. err1 := s.xrayApi.RemoveUser(oldInbound.Tag, oldEmail)
  1164. if err1 == nil {
  1165. logger.Debug("Old client deleted by api:", oldEmail)
  1166. } else {
  1167. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", oldEmail)) {
  1168. logger.Debug("User is already deleted. Nothing to do more...")
  1169. } else {
  1170. logger.Debug("Error in deleting client by api:", err1)
  1171. needRestart = true
  1172. }
  1173. }
  1174. }
  1175. if clients[0].Enable {
  1176. cipher := ""
  1177. if oldInbound.Protocol == "shadowsocks" {
  1178. cipher = oldSettings["method"].(string)
  1179. }
  1180. err1 := s.xrayApi.AddUser(string(oldInbound.Protocol), oldInbound.Tag, map[string]any{
  1181. "email": clients[0].Email,
  1182. "id": clients[0].ID,
  1183. "security": clients[0].Security,
  1184. "flow": clients[0].Flow,
  1185. "auth": clients[0].Auth,
  1186. "password": clients[0].Password,
  1187. "cipher": cipher,
  1188. })
  1189. if err1 == nil {
  1190. logger.Debug("Client edited by api:", clients[0].Email)
  1191. } else {
  1192. logger.Debug("Error in adding client by api:", err1)
  1193. needRestart = true
  1194. }
  1195. }
  1196. s.xrayApi.Close()
  1197. } else {
  1198. logger.Debug("Client old email not found")
  1199. needRestart = true
  1200. }
  1201. return needRestart, tx.Save(oldInbound).Error
  1202. }
  1203. func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (bool, bool, error) {
  1204. var err error
  1205. db := database.GetDB()
  1206. tx := db.Begin()
  1207. defer func() {
  1208. if err != nil {
  1209. tx.Rollback()
  1210. } else {
  1211. tx.Commit()
  1212. }
  1213. }()
  1214. err = s.addInboundTraffic(tx, inboundTraffics)
  1215. if err != nil {
  1216. return false, false, err
  1217. }
  1218. err = s.addClientTraffic(tx, clientTraffics)
  1219. if err != nil {
  1220. return false, false, err
  1221. }
  1222. needRestart0, count, err := s.autoRenewClients(tx)
  1223. if err != nil {
  1224. logger.Warning("Error in renew clients:", err)
  1225. } else if count > 0 {
  1226. logger.Debugf("%v clients renewed", count)
  1227. }
  1228. disabledClientsCount := int64(0)
  1229. needRestart1, count, err := s.disableInvalidClients(tx)
  1230. if err != nil {
  1231. logger.Warning("Error in disabling invalid clients:", err)
  1232. } else if count > 0 {
  1233. logger.Debugf("%v clients disabled", count)
  1234. disabledClientsCount = count
  1235. }
  1236. needRestart2, count, err := s.disableInvalidInbounds(tx)
  1237. if err != nil {
  1238. logger.Warning("Error in disabling invalid inbounds:", err)
  1239. } else if count > 0 {
  1240. logger.Debugf("%v inbounds disabled", count)
  1241. }
  1242. return needRestart0 || needRestart1 || needRestart2, disabledClientsCount > 0, nil
  1243. }
  1244. func (s *InboundService) addInboundTraffic(tx *gorm.DB, traffics []*xray.Traffic) error {
  1245. if len(traffics) == 0 {
  1246. return nil
  1247. }
  1248. var err error
  1249. for _, traffic := range traffics {
  1250. if traffic.IsInbound {
  1251. err = tx.Model(&model.Inbound{}).Where("tag = ?", traffic.Tag).
  1252. Updates(map[string]any{
  1253. "up": gorm.Expr("up + ?", traffic.Up),
  1254. "down": gorm.Expr("down + ?", traffic.Down),
  1255. "all_time": gorm.Expr("COALESCE(all_time, 0) + ?", traffic.Up+traffic.Down),
  1256. }).Error
  1257. if err != nil {
  1258. return err
  1259. }
  1260. }
  1261. }
  1262. return nil
  1263. }
  1264. func (s *InboundService) addClientTraffic(tx *gorm.DB, traffics []*xray.ClientTraffic) (err error) {
  1265. if len(traffics) == 0 {
  1266. // Empty onlineUsers
  1267. if p != nil {
  1268. p.SetOnlineClients(make([]string, 0))
  1269. }
  1270. return nil
  1271. }
  1272. onlineClients := make([]string, 0)
  1273. emails := make([]string, 0, len(traffics))
  1274. for _, traffic := range traffics {
  1275. emails = append(emails, traffic.Email)
  1276. }
  1277. dbClientTraffics := make([]*xray.ClientTraffic, 0, len(traffics))
  1278. err = tx.Model(xray.ClientTraffic{}).Where("email IN (?)", emails).Find(&dbClientTraffics).Error
  1279. if err != nil {
  1280. return err
  1281. }
  1282. // Avoid empty slice error
  1283. if len(dbClientTraffics) == 0 {
  1284. return nil
  1285. }
  1286. dbClientTraffics, err = s.adjustTraffics(tx, dbClientTraffics)
  1287. if err != nil {
  1288. return err
  1289. }
  1290. // Index by email for O(N) merge — the previous nested loop was O(N²)
  1291. // and dominated each cron tick on inbounds with thousands of active
  1292. // clients (7500 × 7500 = 56M string comparisons every 10 seconds).
  1293. trafficByEmail := make(map[string]*xray.ClientTraffic, len(traffics))
  1294. for i := range traffics {
  1295. if traffics[i] != nil {
  1296. trafficByEmail[traffics[i].Email] = traffics[i]
  1297. }
  1298. }
  1299. now := time.Now().UnixMilli()
  1300. for dbTraffic_index := range dbClientTraffics {
  1301. t, ok := trafficByEmail[dbClientTraffics[dbTraffic_index].Email]
  1302. if !ok {
  1303. continue
  1304. }
  1305. dbClientTraffics[dbTraffic_index].Up += t.Up
  1306. dbClientTraffics[dbTraffic_index].Down += t.Down
  1307. dbClientTraffics[dbTraffic_index].AllTime += t.Up + t.Down
  1308. if t.Up+t.Down > 0 {
  1309. onlineClients = append(onlineClients, t.Email)
  1310. dbClientTraffics[dbTraffic_index].LastOnline = now
  1311. }
  1312. }
  1313. // Set onlineUsers
  1314. p.SetOnlineClients(onlineClients)
  1315. err = tx.Save(dbClientTraffics).Error
  1316. if err != nil {
  1317. logger.Warning("AddClientTraffic update data ", err)
  1318. }
  1319. return nil
  1320. }
  1321. func (s *InboundService) adjustTraffics(tx *gorm.DB, dbClientTraffics []*xray.ClientTraffic) ([]*xray.ClientTraffic, error) {
  1322. inboundIds := make([]int, 0, len(dbClientTraffics))
  1323. for _, dbClientTraffic := range dbClientTraffics {
  1324. if dbClientTraffic.ExpiryTime < 0 {
  1325. inboundIds = append(inboundIds, dbClientTraffic.InboundId)
  1326. }
  1327. }
  1328. if len(inboundIds) > 0 {
  1329. var inbounds []*model.Inbound
  1330. err := tx.Model(model.Inbound{}).Where("id IN (?)", inboundIds).Find(&inbounds).Error
  1331. if err != nil {
  1332. return nil, err
  1333. }
  1334. for inbound_index := range inbounds {
  1335. settings := map[string]any{}
  1336. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1337. clients, ok := settings["clients"].([]any)
  1338. if ok {
  1339. var newClients []any
  1340. for client_index := range clients {
  1341. c := clients[client_index].(map[string]any)
  1342. for traffic_index := range dbClientTraffics {
  1343. if dbClientTraffics[traffic_index].ExpiryTime < 0 && c["email"] == dbClientTraffics[traffic_index].Email {
  1344. oldExpiryTime := c["expiryTime"].(float64)
  1345. newExpiryTime := (time.Now().Unix() * 1000) - int64(oldExpiryTime)
  1346. c["expiryTime"] = newExpiryTime
  1347. c["updated_at"] = time.Now().Unix() * 1000
  1348. dbClientTraffics[traffic_index].ExpiryTime = newExpiryTime
  1349. break
  1350. }
  1351. }
  1352. // Backfill created_at and updated_at
  1353. if _, ok := c["created_at"]; !ok {
  1354. c["created_at"] = time.Now().Unix() * 1000
  1355. }
  1356. c["updated_at"] = time.Now().Unix() * 1000
  1357. newClients = append(newClients, any(c))
  1358. }
  1359. settings["clients"] = newClients
  1360. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1361. if err != nil {
  1362. return nil, err
  1363. }
  1364. inbounds[inbound_index].Settings = string(modifiedSettings)
  1365. }
  1366. }
  1367. err = tx.Save(inbounds).Error
  1368. if err != nil {
  1369. logger.Warning("AddClientTraffic update inbounds ", err)
  1370. logger.Error(inbounds)
  1371. }
  1372. }
  1373. return dbClientTraffics, nil
  1374. }
  1375. func (s *InboundService) autoRenewClients(tx *gorm.DB) (bool, int64, error) {
  1376. // check for time expired
  1377. var traffics []*xray.ClientTraffic
  1378. now := time.Now().Unix() * 1000
  1379. var err, err1 error
  1380. err = tx.Model(xray.ClientTraffic{}).Where("reset > 0 and expiry_time > 0 and expiry_time <= ?", now).Find(&traffics).Error
  1381. if err != nil {
  1382. return false, 0, err
  1383. }
  1384. // return if there is no client to renew
  1385. if len(traffics) == 0 {
  1386. return false, 0, nil
  1387. }
  1388. var inbound_ids []int
  1389. var inbounds []*model.Inbound
  1390. needRestart := false
  1391. var clientsToAdd []struct {
  1392. protocol string
  1393. tag string
  1394. client map[string]any
  1395. }
  1396. for _, traffic := range traffics {
  1397. inbound_ids = append(inbound_ids, traffic.InboundId)
  1398. }
  1399. // Dedupe so an inbound hosting N expired clients is fetched and saved once
  1400. // per tick instead of N times across chunk boundaries.
  1401. inbound_ids = uniqueInts(inbound_ids)
  1402. // Chunked to stay under SQLite's bind-variable limit when many inbounds
  1403. // are touched in a single tick.
  1404. for _, batch := range chunkInts(inbound_ids, sqliteMaxVars) {
  1405. var page []*model.Inbound
  1406. if err = tx.Model(model.Inbound{}).Where("id IN ?", batch).Find(&page).Error; err != nil {
  1407. return false, 0, err
  1408. }
  1409. inbounds = append(inbounds, page...)
  1410. }
  1411. for inbound_index := range inbounds {
  1412. settings := map[string]any{}
  1413. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1414. clients := settings["clients"].([]any)
  1415. for client_index := range clients {
  1416. c := clients[client_index].(map[string]any)
  1417. for traffic_index, traffic := range traffics {
  1418. if traffic.Email == c["email"].(string) {
  1419. newExpiryTime := traffic.ExpiryTime
  1420. for newExpiryTime < now {
  1421. newExpiryTime += (int64(traffic.Reset) * 86400000)
  1422. }
  1423. c["expiryTime"] = newExpiryTime
  1424. traffics[traffic_index].ExpiryTime = newExpiryTime
  1425. traffics[traffic_index].Down = 0
  1426. traffics[traffic_index].Up = 0
  1427. if !traffic.Enable {
  1428. traffics[traffic_index].Enable = true
  1429. clientsToAdd = append(clientsToAdd,
  1430. struct {
  1431. protocol string
  1432. tag string
  1433. client map[string]any
  1434. }{
  1435. protocol: string(inbounds[inbound_index].Protocol),
  1436. tag: inbounds[inbound_index].Tag,
  1437. client: c,
  1438. })
  1439. }
  1440. clients[client_index] = any(c)
  1441. break
  1442. }
  1443. }
  1444. }
  1445. settings["clients"] = clients
  1446. newSettings, err := json.MarshalIndent(settings, "", " ")
  1447. if err != nil {
  1448. return false, 0, err
  1449. }
  1450. inbounds[inbound_index].Settings = string(newSettings)
  1451. }
  1452. err = tx.Save(inbounds).Error
  1453. if err != nil {
  1454. return false, 0, err
  1455. }
  1456. err = tx.Save(traffics).Error
  1457. if err != nil {
  1458. return false, 0, err
  1459. }
  1460. if p != nil {
  1461. err1 = s.xrayApi.Init(p.GetAPIPort())
  1462. if err1 != nil {
  1463. return true, int64(len(traffics)), nil
  1464. }
  1465. for _, clientToAdd := range clientsToAdd {
  1466. err1 = s.xrayApi.AddUser(clientToAdd.protocol, clientToAdd.tag, clientToAdd.client)
  1467. if err1 != nil {
  1468. needRestart = true
  1469. }
  1470. }
  1471. s.xrayApi.Close()
  1472. }
  1473. return needRestart, int64(len(traffics)), nil
  1474. }
  1475. func (s *InboundService) disableInvalidInbounds(tx *gorm.DB) (bool, int64, error) {
  1476. now := time.Now().Unix() * 1000
  1477. needRestart := false
  1478. if p != nil {
  1479. var tags []string
  1480. err := tx.Table("inbounds").
  1481. Select("inbounds.tag").
  1482. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  1483. Scan(&tags).Error
  1484. if err != nil {
  1485. return false, 0, err
  1486. }
  1487. s.xrayApi.Init(p.GetAPIPort())
  1488. for _, tag := range tags {
  1489. err1 := s.xrayApi.DelInbound(tag)
  1490. if err1 == nil {
  1491. logger.Debug("Inbound disabled by api:", tag)
  1492. } else {
  1493. logger.Debug("Error in disabling inbound by api:", err1)
  1494. needRestart = true
  1495. }
  1496. }
  1497. s.xrayApi.Close()
  1498. }
  1499. result := tx.Model(model.Inbound{}).
  1500. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  1501. Update("enable", false)
  1502. err := result.Error
  1503. count := result.RowsAffected
  1504. return needRestart, count, err
  1505. }
  1506. func (s *InboundService) disableInvalidClients(tx *gorm.DB) (bool, int64, error) {
  1507. now := time.Now().Unix() * 1000
  1508. needRestart := false
  1509. var clientsToDisable []struct {
  1510. InboundId int
  1511. Tag string
  1512. Email string
  1513. }
  1514. err := tx.Table("inbounds").
  1515. Select("inbounds.id as inbound_id, inbounds.tag, client_traffics.email").
  1516. Joins("JOIN client_traffics ON inbounds.id = client_traffics.inbound_id").
  1517. Where("((client_traffics.total > 0 AND client_traffics.up + client_traffics.down >= client_traffics.total) OR (client_traffics.expiry_time > 0 AND client_traffics.expiry_time <= ?)) AND client_traffics.enable = ?", now, true).
  1518. Scan(&clientsToDisable).Error
  1519. if err != nil {
  1520. return false, 0, err
  1521. }
  1522. if p != nil {
  1523. s.xrayApi.Init(p.GetAPIPort())
  1524. for _, client := range clientsToDisable {
  1525. err1 := s.xrayApi.RemoveUser(client.Tag, client.Email)
  1526. if err1 == nil {
  1527. logger.Debug("Client disabled by api:", client.Email)
  1528. } else {
  1529. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", client.Email)) {
  1530. logger.Debug("User is already disabled. Nothing to do more...")
  1531. } else {
  1532. logger.Debug("Error in disabling client by api:", err1)
  1533. needRestart = true
  1534. }
  1535. }
  1536. }
  1537. s.xrayApi.Close()
  1538. }
  1539. result := tx.Model(xray.ClientTraffic{}).
  1540. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  1541. Update("enable", false)
  1542. err = result.Error
  1543. count := result.RowsAffected
  1544. if err != nil {
  1545. return needRestart, count, err
  1546. }
  1547. // Also set enable=false in inbounds.settings JSON so clients are visibly disabled
  1548. if len(clientsToDisable) > 0 {
  1549. inboundEmailMap := make(map[int]map[string]struct{})
  1550. for _, c := range clientsToDisable {
  1551. if inboundEmailMap[c.InboundId] == nil {
  1552. inboundEmailMap[c.InboundId] = make(map[string]struct{})
  1553. }
  1554. inboundEmailMap[c.InboundId][c.Email] = struct{}{}
  1555. }
  1556. inboundIds := make([]int, 0, len(inboundEmailMap))
  1557. for id := range inboundEmailMap {
  1558. inboundIds = append(inboundIds, id)
  1559. }
  1560. var inbounds []*model.Inbound
  1561. if err = tx.Model(model.Inbound{}).Where("id IN ?", inboundIds).Find(&inbounds).Error; err != nil {
  1562. logger.Warning("disableInvalidClients fetch inbounds:", err)
  1563. return needRestart, count, nil
  1564. }
  1565. for _, inbound := range inbounds {
  1566. settings := map[string]any{}
  1567. if jsonErr := json.Unmarshal([]byte(inbound.Settings), &settings); jsonErr != nil {
  1568. continue
  1569. }
  1570. clients, ok := settings["clients"].([]any)
  1571. if !ok {
  1572. continue
  1573. }
  1574. emailSet := inboundEmailMap[inbound.Id]
  1575. changed := false
  1576. for i := range clients {
  1577. c, ok := clients[i].(map[string]any)
  1578. if !ok {
  1579. continue
  1580. }
  1581. email, _ := c["email"].(string)
  1582. if _, shouldDisable := emailSet[email]; shouldDisable {
  1583. c["enable"] = false
  1584. c["updated_at"] = time.Now().Unix() * 1000
  1585. clients[i] = c
  1586. changed = true
  1587. }
  1588. }
  1589. if changed {
  1590. settings["clients"] = clients
  1591. modifiedSettings, jsonErr := json.MarshalIndent(settings, "", " ")
  1592. if jsonErr != nil {
  1593. continue
  1594. }
  1595. inbound.Settings = string(modifiedSettings)
  1596. }
  1597. }
  1598. if err = tx.Save(inbounds).Error; err != nil {
  1599. logger.Warning("disableInvalidClients update inbound settings:", err)
  1600. }
  1601. }
  1602. return needRestart, count, nil
  1603. }
  1604. func (s *InboundService) GetInboundTags() (string, error) {
  1605. db := database.GetDB()
  1606. var inboundTags []string
  1607. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  1608. if err != nil && err != gorm.ErrRecordNotFound {
  1609. return "", err
  1610. }
  1611. tags, _ := json.Marshal(inboundTags)
  1612. return string(tags), nil
  1613. }
  1614. func (s *InboundService) GetClientReverseTags() (string, error) {
  1615. db := database.GetDB()
  1616. var inbounds []model.Inbound
  1617. err := db.Model(model.Inbound{}).Select("settings").Where("protocol = ?", "vless").Find(&inbounds).Error
  1618. if err != nil && err != gorm.ErrRecordNotFound {
  1619. return "[]", err
  1620. }
  1621. tagSet := make(map[string]struct{})
  1622. for _, inbound := range inbounds {
  1623. var settings map[string]any
  1624. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1625. continue
  1626. }
  1627. clients, ok := settings["clients"].([]any)
  1628. if !ok {
  1629. continue
  1630. }
  1631. for _, client := range clients {
  1632. clientMap, ok := client.(map[string]any)
  1633. if !ok {
  1634. continue
  1635. }
  1636. reverse, ok := clientMap["reverse"].(map[string]any)
  1637. if !ok {
  1638. continue
  1639. }
  1640. tag, _ := reverse["tag"].(string)
  1641. tag = strings.TrimSpace(tag)
  1642. if tag != "" {
  1643. tagSet[tag] = struct{}{}
  1644. }
  1645. }
  1646. }
  1647. rawTags := make([]string, 0, len(tagSet))
  1648. for tag := range tagSet {
  1649. rawTags = append(rawTags, tag)
  1650. }
  1651. sort.Strings(rawTags)
  1652. result, _ := json.Marshal(rawTags)
  1653. return string(result), nil
  1654. }
  1655. func (s *InboundService) MigrationRemoveOrphanedTraffics() {
  1656. db := database.GetDB()
  1657. db.Exec(`
  1658. DELETE FROM client_traffics
  1659. WHERE email NOT IN (
  1660. SELECT JSON_EXTRACT(client.value, '$.email')
  1661. FROM inbounds,
  1662. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  1663. )
  1664. `)
  1665. }
  1666. func (s *InboundService) AddClientStat(tx *gorm.DB, inboundId int, client *model.Client) error {
  1667. clientTraffic := xray.ClientTraffic{}
  1668. clientTraffic.InboundId = inboundId
  1669. clientTraffic.Email = client.Email
  1670. clientTraffic.Total = client.TotalGB
  1671. clientTraffic.ExpiryTime = client.ExpiryTime
  1672. clientTraffic.Enable = client.Enable
  1673. clientTraffic.Up = 0
  1674. clientTraffic.Down = 0
  1675. clientTraffic.Reset = client.Reset
  1676. result := tx.Create(&clientTraffic)
  1677. err := result.Error
  1678. return err
  1679. }
  1680. func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *model.Client) error {
  1681. result := tx.Model(xray.ClientTraffic{}).
  1682. Where("email = ?", email).
  1683. Updates(map[string]any{
  1684. "enable": client.Enable,
  1685. "email": client.Email,
  1686. "total": client.TotalGB,
  1687. "expiry_time": client.ExpiryTime,
  1688. "reset": client.Reset,
  1689. })
  1690. err := result.Error
  1691. return err
  1692. }
  1693. func (s *InboundService) UpdateClientIPs(tx *gorm.DB, oldEmail string, newEmail string) error {
  1694. return tx.Model(model.InboundClientIps{}).Where("client_email = ?", oldEmail).Update("client_email", newEmail).Error
  1695. }
  1696. func (s *InboundService) DelClientStat(tx *gorm.DB, email string) error {
  1697. return tx.Where("email = ?", email).Delete(xray.ClientTraffic{}).Error
  1698. }
  1699. func (s *InboundService) DelClientIPs(tx *gorm.DB, email string) error {
  1700. return tx.Where("client_email = ?", email).Delete(model.InboundClientIps{}).Error
  1701. }
  1702. func (s *InboundService) GetClientInboundByTrafficID(trafficId int) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  1703. db := database.GetDB()
  1704. var traffics []*xray.ClientTraffic
  1705. err = db.Model(xray.ClientTraffic{}).Where("id = ?", trafficId).Find(&traffics).Error
  1706. if err != nil {
  1707. logger.Warningf("Error retrieving ClientTraffic with trafficId %d: %v", trafficId, err)
  1708. return nil, nil, err
  1709. }
  1710. if len(traffics) > 0 {
  1711. inbound, err = s.GetInbound(traffics[0].InboundId)
  1712. return traffics[0], inbound, err
  1713. }
  1714. return nil, nil, nil
  1715. }
  1716. func (s *InboundService) GetClientInboundByEmail(email string) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  1717. db := database.GetDB()
  1718. var traffics []*xray.ClientTraffic
  1719. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error
  1720. if err != nil {
  1721. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  1722. return nil, nil, err
  1723. }
  1724. if len(traffics) > 0 {
  1725. inbound, err = s.GetInbound(traffics[0].InboundId)
  1726. return traffics[0], inbound, err
  1727. }
  1728. return nil, nil, nil
  1729. }
  1730. func (s *InboundService) GetClientByEmail(clientEmail string) (*xray.ClientTraffic, *model.Client, error) {
  1731. traffic, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1732. if err != nil {
  1733. return nil, nil, err
  1734. }
  1735. if inbound == nil {
  1736. return nil, nil, common.NewError("Inbound Not Found For Email:", clientEmail)
  1737. }
  1738. clients, err := s.GetClients(inbound)
  1739. if err != nil {
  1740. return nil, nil, err
  1741. }
  1742. for _, client := range clients {
  1743. if client.Email == clientEmail {
  1744. return traffic, &client, nil
  1745. }
  1746. }
  1747. return nil, nil, common.NewError("Client Not Found In Inbound For Email:", clientEmail)
  1748. }
  1749. func (s *InboundService) SetClientTelegramUserID(trafficId int, tgId int64) (bool, error) {
  1750. traffic, inbound, err := s.GetClientInboundByTrafficID(trafficId)
  1751. if err != nil {
  1752. return false, err
  1753. }
  1754. if inbound == nil {
  1755. return false, common.NewError("Inbound Not Found For Traffic ID:", trafficId)
  1756. }
  1757. clientEmail := traffic.Email
  1758. oldClients, err := s.GetClients(inbound)
  1759. if err != nil {
  1760. return false, err
  1761. }
  1762. clientId := ""
  1763. for _, oldClient := range oldClients {
  1764. if oldClient.Email == clientEmail {
  1765. switch inbound.Protocol {
  1766. case "trojan":
  1767. clientId = oldClient.Password
  1768. case "shadowsocks":
  1769. clientId = oldClient.Email
  1770. default:
  1771. clientId = oldClient.ID
  1772. }
  1773. break
  1774. }
  1775. }
  1776. if len(clientId) == 0 {
  1777. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1778. }
  1779. var settings map[string]any
  1780. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1781. if err != nil {
  1782. return false, err
  1783. }
  1784. clients := settings["clients"].([]any)
  1785. var newClients []any
  1786. for client_index := range clients {
  1787. c := clients[client_index].(map[string]any)
  1788. if c["email"] == clientEmail {
  1789. c["tgId"] = tgId
  1790. c["updated_at"] = time.Now().Unix() * 1000
  1791. newClients = append(newClients, any(c))
  1792. }
  1793. }
  1794. settings["clients"] = newClients
  1795. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1796. if err != nil {
  1797. return false, err
  1798. }
  1799. inbound.Settings = string(modifiedSettings)
  1800. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1801. return needRestart, err
  1802. }
  1803. func (s *InboundService) checkIsEnabledByEmail(clientEmail string) (bool, error) {
  1804. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1805. if err != nil {
  1806. return false, err
  1807. }
  1808. if inbound == nil {
  1809. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1810. }
  1811. clients, err := s.GetClients(inbound)
  1812. if err != nil {
  1813. return false, err
  1814. }
  1815. isEnable := false
  1816. for _, client := range clients {
  1817. if client.Email == clientEmail {
  1818. isEnable = client.Enable
  1819. break
  1820. }
  1821. }
  1822. return isEnable, err
  1823. }
  1824. func (s *InboundService) ToggleClientEnableByEmail(clientEmail string) (bool, bool, error) {
  1825. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1826. if err != nil {
  1827. return false, false, err
  1828. }
  1829. if inbound == nil {
  1830. return false, false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1831. }
  1832. oldClients, err := s.GetClients(inbound)
  1833. if err != nil {
  1834. return false, false, err
  1835. }
  1836. clientId := ""
  1837. clientOldEnabled := false
  1838. for _, oldClient := range oldClients {
  1839. if oldClient.Email == clientEmail {
  1840. switch inbound.Protocol {
  1841. case "trojan":
  1842. clientId = oldClient.Password
  1843. case "shadowsocks":
  1844. clientId = oldClient.Email
  1845. default:
  1846. clientId = oldClient.ID
  1847. }
  1848. clientOldEnabled = oldClient.Enable
  1849. break
  1850. }
  1851. }
  1852. if len(clientId) == 0 {
  1853. return false, false, common.NewError("Client Not Found For Email:", clientEmail)
  1854. }
  1855. var settings map[string]any
  1856. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1857. if err != nil {
  1858. return false, false, err
  1859. }
  1860. clients := settings["clients"].([]any)
  1861. var newClients []any
  1862. for client_index := range clients {
  1863. c := clients[client_index].(map[string]any)
  1864. if c["email"] == clientEmail {
  1865. c["enable"] = !clientOldEnabled
  1866. c["updated_at"] = time.Now().Unix() * 1000
  1867. newClients = append(newClients, any(c))
  1868. }
  1869. }
  1870. settings["clients"] = newClients
  1871. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1872. if err != nil {
  1873. return false, false, err
  1874. }
  1875. inbound.Settings = string(modifiedSettings)
  1876. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1877. if err != nil {
  1878. return false, needRestart, err
  1879. }
  1880. return !clientOldEnabled, needRestart, nil
  1881. }
  1882. // SetClientEnableByEmail sets client enable state to desired value; returns (changed, needRestart, error)
  1883. func (s *InboundService) SetClientEnableByEmail(clientEmail string, enable bool) (bool, bool, error) {
  1884. current, err := s.checkIsEnabledByEmail(clientEmail)
  1885. if err != nil {
  1886. return false, false, err
  1887. }
  1888. if current == enable {
  1889. return false, false, nil
  1890. }
  1891. newEnabled, needRestart, err := s.ToggleClientEnableByEmail(clientEmail)
  1892. if err != nil {
  1893. return false, needRestart, err
  1894. }
  1895. return newEnabled == enable, needRestart, nil
  1896. }
  1897. func (s *InboundService) ResetClientIpLimitByEmail(clientEmail string, count int) (bool, error) {
  1898. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1899. if err != nil {
  1900. return false, err
  1901. }
  1902. if inbound == nil {
  1903. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1904. }
  1905. oldClients, err := s.GetClients(inbound)
  1906. if err != nil {
  1907. return false, err
  1908. }
  1909. clientId := ""
  1910. for _, oldClient := range oldClients {
  1911. if oldClient.Email == clientEmail {
  1912. switch inbound.Protocol {
  1913. case "trojan":
  1914. clientId = oldClient.Password
  1915. case "shadowsocks":
  1916. clientId = oldClient.Email
  1917. default:
  1918. clientId = oldClient.ID
  1919. }
  1920. break
  1921. }
  1922. }
  1923. if len(clientId) == 0 {
  1924. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1925. }
  1926. var settings map[string]any
  1927. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1928. if err != nil {
  1929. return false, err
  1930. }
  1931. clients := settings["clients"].([]any)
  1932. var newClients []any
  1933. for client_index := range clients {
  1934. c := clients[client_index].(map[string]any)
  1935. if c["email"] == clientEmail {
  1936. c["limitIp"] = count
  1937. c["updated_at"] = time.Now().Unix() * 1000
  1938. newClients = append(newClients, any(c))
  1939. }
  1940. }
  1941. settings["clients"] = newClients
  1942. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1943. if err != nil {
  1944. return false, err
  1945. }
  1946. inbound.Settings = string(modifiedSettings)
  1947. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1948. return needRestart, err
  1949. }
  1950. func (s *InboundService) ResetClientExpiryTimeByEmail(clientEmail string, expiry_time int64) (bool, error) {
  1951. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1952. if err != nil {
  1953. return false, err
  1954. }
  1955. if inbound == nil {
  1956. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1957. }
  1958. oldClients, err := s.GetClients(inbound)
  1959. if err != nil {
  1960. return false, err
  1961. }
  1962. clientId := ""
  1963. for _, oldClient := range oldClients {
  1964. if oldClient.Email == clientEmail {
  1965. switch inbound.Protocol {
  1966. case "trojan":
  1967. clientId = oldClient.Password
  1968. case "shadowsocks":
  1969. clientId = oldClient.Email
  1970. default:
  1971. clientId = oldClient.ID
  1972. }
  1973. break
  1974. }
  1975. }
  1976. if len(clientId) == 0 {
  1977. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1978. }
  1979. var settings map[string]any
  1980. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1981. if err != nil {
  1982. return false, err
  1983. }
  1984. clients := settings["clients"].([]any)
  1985. var newClients []any
  1986. for client_index := range clients {
  1987. c := clients[client_index].(map[string]any)
  1988. if c["email"] == clientEmail {
  1989. c["expiryTime"] = expiry_time
  1990. c["updated_at"] = time.Now().Unix() * 1000
  1991. newClients = append(newClients, any(c))
  1992. }
  1993. }
  1994. settings["clients"] = newClients
  1995. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1996. if err != nil {
  1997. return false, err
  1998. }
  1999. inbound.Settings = string(modifiedSettings)
  2000. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  2001. return needRestart, err
  2002. }
  2003. func (s *InboundService) ResetClientTrafficLimitByEmail(clientEmail string, totalGB int) (bool, error) {
  2004. if totalGB < 0 {
  2005. return false, common.NewError("totalGB must be >= 0")
  2006. }
  2007. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  2008. if err != nil {
  2009. return false, err
  2010. }
  2011. if inbound == nil {
  2012. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  2013. }
  2014. oldClients, err := s.GetClients(inbound)
  2015. if err != nil {
  2016. return false, err
  2017. }
  2018. clientId := ""
  2019. for _, oldClient := range oldClients {
  2020. if oldClient.Email == clientEmail {
  2021. switch inbound.Protocol {
  2022. case "trojan":
  2023. clientId = oldClient.Password
  2024. case "shadowsocks":
  2025. clientId = oldClient.Email
  2026. default:
  2027. clientId = oldClient.ID
  2028. }
  2029. break
  2030. }
  2031. }
  2032. if len(clientId) == 0 {
  2033. return false, common.NewError("Client Not Found For Email:", clientEmail)
  2034. }
  2035. var settings map[string]any
  2036. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  2037. if err != nil {
  2038. return false, err
  2039. }
  2040. clients := settings["clients"].([]any)
  2041. var newClients []any
  2042. for client_index := range clients {
  2043. c := clients[client_index].(map[string]any)
  2044. if c["email"] == clientEmail {
  2045. c["totalGB"] = totalGB * 1024 * 1024 * 1024
  2046. c["updated_at"] = time.Now().Unix() * 1000
  2047. newClients = append(newClients, any(c))
  2048. }
  2049. }
  2050. settings["clients"] = newClients
  2051. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2052. if err != nil {
  2053. return false, err
  2054. }
  2055. inbound.Settings = string(modifiedSettings)
  2056. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  2057. return needRestart, err
  2058. }
  2059. func (s *InboundService) ResetClientTrafficByEmail(clientEmail string) error {
  2060. db := database.GetDB()
  2061. // Reset traffic stats in ClientTraffic table
  2062. result := db.Model(xray.ClientTraffic{}).
  2063. Where("email = ?", clientEmail).
  2064. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  2065. err := result.Error
  2066. if err != nil {
  2067. return err
  2068. }
  2069. return nil
  2070. }
  2071. func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (bool, error) {
  2072. needRestart := false
  2073. traffic, err := s.GetClientTrafficByEmail(clientEmail)
  2074. if err != nil {
  2075. return false, err
  2076. }
  2077. if !traffic.Enable {
  2078. inbound, err := s.GetInbound(id)
  2079. if err != nil {
  2080. return false, err
  2081. }
  2082. clients, err := s.GetClients(inbound)
  2083. if err != nil {
  2084. return false, err
  2085. }
  2086. for _, client := range clients {
  2087. if client.Email == clientEmail && client.Enable {
  2088. s.xrayApi.Init(p.GetAPIPort())
  2089. cipher := ""
  2090. if string(inbound.Protocol) == "shadowsocks" {
  2091. var oldSettings map[string]any
  2092. err = json.Unmarshal([]byte(inbound.Settings), &oldSettings)
  2093. if err != nil {
  2094. return false, err
  2095. }
  2096. cipher = oldSettings["method"].(string)
  2097. }
  2098. err1 := s.xrayApi.AddUser(string(inbound.Protocol), inbound.Tag, map[string]any{
  2099. "email": client.Email,
  2100. "id": client.ID,
  2101. "auth": client.Auth,
  2102. "security": client.Security,
  2103. "flow": client.Flow,
  2104. "password": client.Password,
  2105. "cipher": cipher,
  2106. })
  2107. if err1 == nil {
  2108. logger.Debug("Client enabled due to reset traffic:", clientEmail)
  2109. } else {
  2110. logger.Debug("Error in enabling client by api:", err1)
  2111. needRestart = true
  2112. }
  2113. s.xrayApi.Close()
  2114. break
  2115. }
  2116. }
  2117. }
  2118. traffic.Up = 0
  2119. traffic.Down = 0
  2120. traffic.Enable = true
  2121. db := database.GetDB()
  2122. err = db.Save(traffic).Error
  2123. if err != nil {
  2124. return false, err
  2125. }
  2126. return needRestart, nil
  2127. }
  2128. func (s *InboundService) ResetAllClientTraffics(id int) error {
  2129. db := database.GetDB()
  2130. now := time.Now().Unix() * 1000
  2131. return db.Transaction(func(tx *gorm.DB) error {
  2132. whereText := "inbound_id "
  2133. if id == -1 {
  2134. whereText += " > ?"
  2135. } else {
  2136. whereText += " = ?"
  2137. }
  2138. // Reset client traffics
  2139. result := tx.Model(xray.ClientTraffic{}).
  2140. Where(whereText, id).
  2141. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  2142. if result.Error != nil {
  2143. return result.Error
  2144. }
  2145. // Update lastTrafficResetTime for the inbound(s)
  2146. inboundWhereText := "id "
  2147. if id == -1 {
  2148. inboundWhereText += " > ?"
  2149. } else {
  2150. inboundWhereText += " = ?"
  2151. }
  2152. result = tx.Model(model.Inbound{}).
  2153. Where(inboundWhereText, id).
  2154. Update("last_traffic_reset_time", now)
  2155. return result.Error
  2156. })
  2157. }
  2158. func (s *InboundService) ResetAllTraffics() error {
  2159. db := database.GetDB()
  2160. result := db.Model(model.Inbound{}).
  2161. Where("user_id > ?", 0).
  2162. Updates(map[string]any{"up": 0, "down": 0})
  2163. err := result.Error
  2164. return err
  2165. }
  2166. func (s *InboundService) ResetInboundTraffic(id int) error {
  2167. db := database.GetDB()
  2168. result := db.Model(model.Inbound{}).
  2169. Where("id = ?", id).
  2170. Updates(map[string]any{"up": 0, "down": 0})
  2171. return result.Error
  2172. }
  2173. func (s *InboundService) DelDepletedClients(id int) (err error) {
  2174. db := database.GetDB()
  2175. tx := db.Begin()
  2176. defer func() {
  2177. if err == nil {
  2178. tx.Commit()
  2179. } else {
  2180. tx.Rollback()
  2181. }
  2182. }()
  2183. whereText := "reset = 0 and inbound_id "
  2184. if id < 0 {
  2185. whereText += "> ?"
  2186. } else {
  2187. whereText += "= ?"
  2188. }
  2189. // Only consider truly depleted clients: expired OR traffic exhausted
  2190. now := time.Now().Unix() * 1000
  2191. depletedClients := []xray.ClientTraffic{}
  2192. err = db.Model(xray.ClientTraffic{}).
  2193. Where(whereText+" and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))", id, now).
  2194. Select("inbound_id, GROUP_CONCAT(email) as email").
  2195. Group("inbound_id").
  2196. Find(&depletedClients).Error
  2197. if err != nil {
  2198. return err
  2199. }
  2200. for _, depletedClient := range depletedClients {
  2201. emails := strings.Split(depletedClient.Email, ",")
  2202. oldInbound, err := s.GetInbound(depletedClient.InboundId)
  2203. if err != nil {
  2204. return err
  2205. }
  2206. var oldSettings map[string]any
  2207. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  2208. if err != nil {
  2209. return err
  2210. }
  2211. oldClients := oldSettings["clients"].([]any)
  2212. var newClients []any
  2213. for _, client := range oldClients {
  2214. deplete := false
  2215. c := client.(map[string]any)
  2216. for _, email := range emails {
  2217. if email == c["email"].(string) {
  2218. deplete = true
  2219. break
  2220. }
  2221. }
  2222. if !deplete {
  2223. newClients = append(newClients, client)
  2224. }
  2225. }
  2226. if len(newClients) > 0 {
  2227. oldSettings["clients"] = newClients
  2228. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  2229. if err != nil {
  2230. return err
  2231. }
  2232. oldInbound.Settings = string(newSettings)
  2233. err = tx.Save(oldInbound).Error
  2234. if err != nil {
  2235. return err
  2236. }
  2237. } else {
  2238. // Delete inbound if no client remains
  2239. s.DelInbound(depletedClient.InboundId)
  2240. }
  2241. }
  2242. // Delete stats only for truly depleted clients
  2243. err = tx.Where(whereText+" and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))", id, now).Delete(xray.ClientTraffic{}).Error
  2244. if err != nil {
  2245. return err
  2246. }
  2247. return nil
  2248. }
  2249. func (s *InboundService) GetClientTrafficTgBot(tgId int64) ([]*xray.ClientTraffic, error) {
  2250. db := database.GetDB()
  2251. var inbounds []*model.Inbound
  2252. // Retrieve inbounds where settings contain the given tgId
  2253. err := db.Model(model.Inbound{}).Where("settings LIKE ?", fmt.Sprintf(`%%"tgId": %d%%`, tgId)).Find(&inbounds).Error
  2254. if err != nil && err != gorm.ErrRecordNotFound {
  2255. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  2256. return nil, err
  2257. }
  2258. var emails []string
  2259. for _, inbound := range inbounds {
  2260. clients, err := s.GetClients(inbound)
  2261. if err != nil {
  2262. logger.Errorf("Error retrieving clients for inbound %d: %v", inbound.Id, err)
  2263. continue
  2264. }
  2265. for _, client := range clients {
  2266. if client.TgID == tgId {
  2267. emails = append(emails, client.Email)
  2268. }
  2269. }
  2270. }
  2271. // Chunked to stay under SQLite's bind-variable limit when a single Telegram
  2272. // account owns thousands of clients across inbounds.
  2273. uniqEmails := uniqueNonEmptyStrings(emails)
  2274. traffics := make([]*xray.ClientTraffic, 0, len(uniqEmails))
  2275. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  2276. var page []*xray.ClientTraffic
  2277. if err = db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  2278. if err == gorm.ErrRecordNotFound {
  2279. continue
  2280. }
  2281. logger.Errorf("Error retrieving ClientTraffic for emails %v: %v", batch, err)
  2282. return nil, err
  2283. }
  2284. traffics = append(traffics, page...)
  2285. }
  2286. if len(traffics) == 0 {
  2287. logger.Warning("No ClientTraffic records found for emails:", emails)
  2288. return nil, nil
  2289. }
  2290. // Populate UUID and other client data for each traffic record
  2291. for i := range traffics {
  2292. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  2293. traffics[i].Enable = client.Enable
  2294. traffics[i].UUID = client.ID
  2295. traffics[i].SubId = client.SubID
  2296. }
  2297. }
  2298. return traffics, nil
  2299. }
  2300. // sqliteMaxVars is a safe ceiling for the number of bind parameters in a
  2301. // single SQL statement. SQLite's SQLITE_MAX_VARIABLE_NUMBER is 999 on builds
  2302. // before 3.32 and 32766 after; staying under 999 keeps queries portable
  2303. // across forks/old binaries and also bounds per-query memory on truly large
  2304. // installs (>32k clients) where even modern SQLite would refuse a single IN.
  2305. const sqliteMaxVars = 900
  2306. // uniqueNonEmptyStrings returns a deduplicated copy of in with empty strings
  2307. // removed, preserving the order of first occurrence.
  2308. func uniqueNonEmptyStrings(in []string) []string {
  2309. if len(in) == 0 {
  2310. return nil
  2311. }
  2312. seen := make(map[string]struct{}, len(in))
  2313. out := make([]string, 0, len(in))
  2314. for _, v := range in {
  2315. if v == "" {
  2316. continue
  2317. }
  2318. if _, ok := seen[v]; ok {
  2319. continue
  2320. }
  2321. seen[v] = struct{}{}
  2322. out = append(out, v)
  2323. }
  2324. return out
  2325. }
  2326. // uniqueInts returns a deduplicated copy of in, preserving order of first occurrence.
  2327. func uniqueInts(in []int) []int {
  2328. if len(in) == 0 {
  2329. return nil
  2330. }
  2331. seen := make(map[int]struct{}, len(in))
  2332. out := make([]int, 0, len(in))
  2333. for _, v := range in {
  2334. if _, ok := seen[v]; ok {
  2335. continue
  2336. }
  2337. seen[v] = struct{}{}
  2338. out = append(out, v)
  2339. }
  2340. return out
  2341. }
  2342. // chunkStrings splits s into consecutive sub-slices of at most size elements.
  2343. // Returns nil for an empty input or non-positive size.
  2344. func chunkStrings(s []string, size int) [][]string {
  2345. if size <= 0 || len(s) == 0 {
  2346. return nil
  2347. }
  2348. out := make([][]string, 0, (len(s)+size-1)/size)
  2349. for i := 0; i < len(s); i += size {
  2350. end := i + size
  2351. if end > len(s) {
  2352. end = len(s)
  2353. }
  2354. out = append(out, s[i:end])
  2355. }
  2356. return out
  2357. }
  2358. // chunkInts splits s into consecutive sub-slices of at most size elements.
  2359. // Returns nil for an empty input or non-positive size.
  2360. func chunkInts(s []int, size int) [][]int {
  2361. if size <= 0 || len(s) == 0 {
  2362. return nil
  2363. }
  2364. out := make([][]int, 0, (len(s)+size-1)/size)
  2365. for i := 0; i < len(s); i += size {
  2366. end := i + size
  2367. if end > len(s) {
  2368. end = len(s)
  2369. }
  2370. out = append(out, s[i:end])
  2371. }
  2372. return out
  2373. }
  2374. // GetActiveClientTraffics returns the absolute ClientTraffic rows for the given
  2375. // emails. Used by the WebSocket delta path to push per-client absolute
  2376. // counters without re-serializing the full inbound list. The query is chunked
  2377. // to stay under SQLite's bind-variable limit on very large active sets.
  2378. // Empty input returns (nil, nil).
  2379. func (s *InboundService) GetActiveClientTraffics(emails []string) ([]*xray.ClientTraffic, error) {
  2380. uniq := uniqueNonEmptyStrings(emails)
  2381. if len(uniq) == 0 {
  2382. return nil, nil
  2383. }
  2384. db := database.GetDB()
  2385. traffics := make([]*xray.ClientTraffic, 0, len(uniq))
  2386. for _, batch := range chunkStrings(uniq, sqliteMaxVars) {
  2387. var page []*xray.ClientTraffic
  2388. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  2389. return nil, err
  2390. }
  2391. traffics = append(traffics, page...)
  2392. }
  2393. return traffics, nil
  2394. }
  2395. // InboundTrafficSummary is the minimal projection of an inbound's traffic
  2396. // counters used by the WebSocket delta path. Excludes Settings/StreamSettings
  2397. // blobs so the broadcast stays compact even with many inbounds.
  2398. type InboundTrafficSummary struct {
  2399. Id int `json:"id"`
  2400. Up int64 `json:"up"`
  2401. Down int64 `json:"down"`
  2402. Total int64 `json:"total"`
  2403. AllTime int64 `json:"allTime"`
  2404. Enable bool `json:"enable"`
  2405. }
  2406. // GetInboundsTrafficSummary returns inbound-level absolute traffic counters
  2407. // (no per-client expansion). Companion to GetActiveClientTraffics — together
  2408. // they replace the heavy "full inbound list" broadcast on each cron tick.
  2409. func (s *InboundService) GetInboundsTrafficSummary() ([]InboundTrafficSummary, error) {
  2410. db := database.GetDB()
  2411. var summaries []InboundTrafficSummary
  2412. if err := db.Model(&model.Inbound{}).
  2413. Select("id, up, down, total, all_time, enable").
  2414. Find(&summaries).Error; err != nil {
  2415. return nil, err
  2416. }
  2417. return summaries, nil
  2418. }
  2419. func (s *InboundService) GetClientTrafficByEmail(email string) (traffic *xray.ClientTraffic, err error) {
  2420. // Prefer retrieving along with client to reflect actual enabled state from inbound settings
  2421. t, client, err := s.GetClientByEmail(email)
  2422. if err != nil {
  2423. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  2424. return nil, err
  2425. }
  2426. if t != nil && client != nil {
  2427. t.UUID = client.ID
  2428. t.SubId = client.SubID
  2429. return t, nil
  2430. }
  2431. return nil, nil
  2432. }
  2433. func (s *InboundService) UpdateClientTrafficByEmail(email string, upload int64, download int64) error {
  2434. db := database.GetDB()
  2435. // Keep all_time monotonic: it represents historical cumulative usage and
  2436. // must never be less than the currently-tracked up+down. Without this,
  2437. // the UI showed "Общий трафик" (allTime) below the live consumed value
  2438. // after admins manually edited a client's counters.
  2439. result := db.Model(xray.ClientTraffic{}).
  2440. Where("email = ?", email).
  2441. Updates(map[string]any{
  2442. "up": upload,
  2443. "down": download,
  2444. "all_time": gorm.Expr("CASE WHEN COALESCE(all_time, 0) < ? THEN ? ELSE all_time END", upload+download, upload+download),
  2445. })
  2446. err := result.Error
  2447. if err != nil {
  2448. logger.Warningf("Error updating ClientTraffic with email %s: %v", email, err)
  2449. return err
  2450. }
  2451. return nil
  2452. }
  2453. func (s *InboundService) GetClientTrafficByID(id string) ([]xray.ClientTraffic, error) {
  2454. db := database.GetDB()
  2455. var traffics []xray.ClientTraffic
  2456. err := db.Model(xray.ClientTraffic{}).Where(`email IN(
  2457. SELECT JSON_EXTRACT(client.value, '$.email') as email
  2458. FROM inbounds,
  2459. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  2460. WHERE
  2461. JSON_EXTRACT(client.value, '$.id') in (?)
  2462. )`, id).Find(&traffics).Error
  2463. if err != nil {
  2464. logger.Debug(err)
  2465. return nil, err
  2466. }
  2467. // Reconcile enable flag with client settings per email to avoid stale DB value
  2468. for i := range traffics {
  2469. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  2470. traffics[i].Enable = client.Enable
  2471. traffics[i].UUID = client.ID
  2472. traffics[i].SubId = client.SubID
  2473. }
  2474. }
  2475. return traffics, err
  2476. }
  2477. func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.ClientTraffic, err error) {
  2478. db := database.GetDB()
  2479. inbound := &model.Inbound{}
  2480. traffic = &xray.ClientTraffic{}
  2481. // Search for inbound settings that contain the query
  2482. err = db.Model(model.Inbound{}).Where("settings LIKE ?", "%\""+query+"\"%").First(inbound).Error
  2483. if err != nil {
  2484. if err == gorm.ErrRecordNotFound {
  2485. logger.Warningf("Inbound settings containing query %s not found: %v", query, err)
  2486. return nil, err
  2487. }
  2488. logger.Errorf("Error searching for inbound settings with query %s: %v", query, err)
  2489. return nil, err
  2490. }
  2491. traffic.InboundId = inbound.Id
  2492. // Unmarshal settings to get clients
  2493. settings := map[string][]model.Client{}
  2494. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  2495. logger.Errorf("Error unmarshalling inbound settings for inbound ID %d: %v", inbound.Id, err)
  2496. return nil, err
  2497. }
  2498. clients := settings["clients"]
  2499. for _, client := range clients {
  2500. if (client.ID == query || client.Password == query) && client.Email != "" {
  2501. traffic.Email = client.Email
  2502. break
  2503. }
  2504. }
  2505. if traffic.Email == "" {
  2506. logger.Warningf("No client found with query %s in inbound ID %d", query, inbound.Id)
  2507. return nil, gorm.ErrRecordNotFound
  2508. }
  2509. // Retrieve ClientTraffic based on the found email
  2510. err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error
  2511. if err != nil {
  2512. if err == gorm.ErrRecordNotFound {
  2513. logger.Warningf("ClientTraffic for email %s not found: %v", traffic.Email, err)
  2514. return nil, err
  2515. }
  2516. logger.Errorf("Error retrieving ClientTraffic for email %s: %v", traffic.Email, err)
  2517. return nil, err
  2518. }
  2519. return traffic, nil
  2520. }
  2521. func (s *InboundService) GetInboundClientIps(clientEmail string) (string, error) {
  2522. db := database.GetDB()
  2523. InboundClientIps := &model.InboundClientIps{}
  2524. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  2525. if err != nil {
  2526. return "", err
  2527. }
  2528. if InboundClientIps.Ips == "" {
  2529. return "", nil
  2530. }
  2531. // Try to parse as new format (with timestamps)
  2532. type IPWithTimestamp struct {
  2533. IP string `json:"ip"`
  2534. Timestamp int64 `json:"timestamp"`
  2535. }
  2536. var ipsWithTime []IPWithTimestamp
  2537. err = json.Unmarshal([]byte(InboundClientIps.Ips), &ipsWithTime)
  2538. // If successfully parsed as new format, return with timestamps
  2539. if err == nil && len(ipsWithTime) > 0 {
  2540. return InboundClientIps.Ips, nil
  2541. }
  2542. // Otherwise, assume it's old format (simple string array)
  2543. // Try to parse as simple array and convert to new format
  2544. var oldIps []string
  2545. err = json.Unmarshal([]byte(InboundClientIps.Ips), &oldIps)
  2546. if err == nil && len(oldIps) > 0 {
  2547. // Convert old format to new format with current timestamp
  2548. newIpsWithTime := make([]IPWithTimestamp, len(oldIps))
  2549. for i, ip := range oldIps {
  2550. newIpsWithTime[i] = IPWithTimestamp{
  2551. IP: ip,
  2552. Timestamp: time.Now().Unix(),
  2553. }
  2554. }
  2555. result, _ := json.Marshal(newIpsWithTime)
  2556. return string(result), nil
  2557. }
  2558. // Return as-is if parsing fails
  2559. return InboundClientIps.Ips, nil
  2560. }
  2561. func (s *InboundService) ClearClientIps(clientEmail string) error {
  2562. db := database.GetDB()
  2563. result := db.Model(model.InboundClientIps{}).
  2564. Where("client_email = ?", clientEmail).
  2565. Update("ips", "")
  2566. err := result.Error
  2567. if err != nil {
  2568. return err
  2569. }
  2570. return nil
  2571. }
  2572. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  2573. db := database.GetDB()
  2574. var inbounds []*model.Inbound
  2575. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  2576. if err != nil && err != gorm.ErrRecordNotFound {
  2577. return nil, err
  2578. }
  2579. return inbounds, nil
  2580. }
  2581. func (s *InboundService) MigrationRequirements() {
  2582. db := database.GetDB()
  2583. tx := db.Begin()
  2584. var err error
  2585. defer func() {
  2586. if err == nil {
  2587. tx.Commit()
  2588. if dbErr := db.Exec(`VACUUM "main"`).Error; dbErr != nil {
  2589. logger.Warningf("VACUUM failed: %v", dbErr)
  2590. }
  2591. } else {
  2592. tx.Rollback()
  2593. }
  2594. }()
  2595. // Calculate and backfill all_time from up+down for inbounds and clients
  2596. err = tx.Exec(`
  2597. UPDATE inbounds
  2598. SET all_time = IFNULL(up, 0) + IFNULL(down, 0)
  2599. WHERE IFNULL(all_time, 0) = 0 AND (IFNULL(up, 0) + IFNULL(down, 0)) > 0
  2600. `).Error
  2601. if err != nil {
  2602. return
  2603. }
  2604. err = tx.Exec(`
  2605. UPDATE client_traffics
  2606. SET all_time = IFNULL(up, 0) + IFNULL(down, 0)
  2607. WHERE IFNULL(all_time, 0) = 0 AND (IFNULL(up, 0) + IFNULL(down, 0)) > 0
  2608. `).Error
  2609. if err != nil {
  2610. return
  2611. }
  2612. // Fix inbounds based problems
  2613. var inbounds []*model.Inbound
  2614. err = tx.Model(model.Inbound{}).Where("protocol IN (?)", []string{"vmess", "vless", "trojan"}).Find(&inbounds).Error
  2615. if err != nil && err != gorm.ErrRecordNotFound {
  2616. return
  2617. }
  2618. for inbound_index := range inbounds {
  2619. settings := map[string]any{}
  2620. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  2621. clients, ok := settings["clients"].([]any)
  2622. if ok {
  2623. // Fix Client configuration problems
  2624. var newClients []any
  2625. hasVisionFlow := false
  2626. for client_index := range clients {
  2627. c := clients[client_index].(map[string]any)
  2628. // Add email='' if it is not exists
  2629. if _, ok := c["email"]; !ok {
  2630. c["email"] = ""
  2631. }
  2632. // Convert string tgId to int64
  2633. if _, ok := c["tgId"]; ok {
  2634. var tgId any = c["tgId"]
  2635. if tgIdStr, ok2 := tgId.(string); ok2 {
  2636. tgIdInt64, err := strconv.ParseInt(strings.ReplaceAll(tgIdStr, " ", ""), 10, 64)
  2637. if err == nil {
  2638. c["tgId"] = tgIdInt64
  2639. }
  2640. }
  2641. }
  2642. // Remove "flow": "xtls-rprx-direct"
  2643. if _, ok := c["flow"]; ok {
  2644. if c["flow"] == "xtls-rprx-direct" {
  2645. c["flow"] = ""
  2646. }
  2647. }
  2648. if flow, _ := c["flow"].(string); flow == "xtls-rprx-vision" {
  2649. hasVisionFlow = true
  2650. }
  2651. // Backfill created_at and updated_at
  2652. if _, ok := c["created_at"]; !ok {
  2653. c["created_at"] = time.Now().Unix() * 1000
  2654. }
  2655. c["updated_at"] = time.Now().Unix() * 1000
  2656. newClients = append(newClients, any(c))
  2657. }
  2658. settings["clients"] = newClients
  2659. // Drop orphaned testseed: VLESS-only field, only meaningful when at least
  2660. // one client uses the exact xtls-rprx-vision flow. Older versions saved it
  2661. // for any non-empty flow (including the UDP variant) or kept it after the
  2662. // flow was cleared from the client modal — clean those up here.
  2663. if inbounds[inbound_index].Protocol == model.VLESS && !hasVisionFlow {
  2664. delete(settings, "testseed")
  2665. }
  2666. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2667. if err != nil {
  2668. return
  2669. }
  2670. inbounds[inbound_index].Settings = string(modifiedSettings)
  2671. }
  2672. // Add client traffic row for all clients which has email
  2673. modelClients, err := s.GetClients(inbounds[inbound_index])
  2674. if err != nil {
  2675. return
  2676. }
  2677. for _, modelClient := range modelClients {
  2678. if len(modelClient.Email) > 0 {
  2679. var count int64
  2680. tx.Model(xray.ClientTraffic{}).Where("email = ?", modelClient.Email).Count(&count)
  2681. if count == 0 {
  2682. s.AddClientStat(tx, inbounds[inbound_index].Id, &modelClient)
  2683. }
  2684. }
  2685. }
  2686. }
  2687. tx.Save(inbounds)
  2688. // Remove orphaned traffics
  2689. tx.Where("inbound_id = 0").Delete(xray.ClientTraffic{})
  2690. // Migrate old MultiDomain to External Proxy
  2691. var externalProxy []struct {
  2692. Id int
  2693. Port int
  2694. StreamSettings []byte
  2695. }
  2696. err = tx.Raw(`select id, port, stream_settings
  2697. from inbounds
  2698. WHERE protocol in ('vmess','vless','trojan')
  2699. AND json_extract(stream_settings, '$.security') = 'tls'
  2700. AND json_extract(stream_settings, '$.tlsSettings.settings.domains') IS NOT NULL`).Scan(&externalProxy).Error
  2701. if err != nil || len(externalProxy) == 0 {
  2702. return
  2703. }
  2704. for _, ep := range externalProxy {
  2705. var reverses any
  2706. var stream map[string]any
  2707. json.Unmarshal(ep.StreamSettings, &stream)
  2708. if tlsSettings, ok := stream["tlsSettings"].(map[string]any); ok {
  2709. if settings, ok := tlsSettings["settings"].(map[string]any); ok {
  2710. if domains, ok := settings["domains"].([]any); ok {
  2711. for _, domain := range domains {
  2712. if domainMap, ok := domain.(map[string]any); ok {
  2713. domainMap["forceTls"] = "same"
  2714. domainMap["port"] = ep.Port
  2715. domainMap["dest"] = domainMap["domain"].(string)
  2716. delete(domainMap, "domain")
  2717. }
  2718. }
  2719. }
  2720. reverses = settings["domains"]
  2721. delete(settings, "domains")
  2722. }
  2723. }
  2724. stream["externalProxy"] = reverses
  2725. newStream, _ := json.MarshalIndent(stream, " ", " ")
  2726. tx.Model(model.Inbound{}).Where("id = ?", ep.Id).Update("stream_settings", newStream)
  2727. }
  2728. err = tx.Raw(`UPDATE inbounds
  2729. SET tag = REPLACE(tag, '0.0.0.0:', '')
  2730. WHERE INSTR(tag, '0.0.0.0:') > 0;`).Error
  2731. if err != nil {
  2732. return
  2733. }
  2734. }
  2735. func (s *InboundService) MigrateDB() {
  2736. s.MigrationRequirements()
  2737. s.MigrationRemoveOrphanedTraffics()
  2738. }
  2739. func (s *InboundService) GetOnlineClients() []string {
  2740. return p.GetOnlineClients()
  2741. }
  2742. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  2743. db := database.GetDB()
  2744. var rows []xray.ClientTraffic
  2745. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  2746. if err != nil && err != gorm.ErrRecordNotFound {
  2747. return nil, err
  2748. }
  2749. result := make(map[string]int64, len(rows))
  2750. for _, r := range rows {
  2751. result[r.Email] = r.LastOnline
  2752. }
  2753. return result, nil
  2754. }
  2755. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  2756. db := database.GetDB()
  2757. // Step 1: Get ClientTraffic records for emails in the input list.
  2758. // Chunked to stay under SQLite's bind-variable limit on huge inputs.
  2759. uniqEmails := uniqueNonEmptyStrings(emails)
  2760. clients := make([]xray.ClientTraffic, 0, len(uniqEmails))
  2761. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  2762. var page []xray.ClientTraffic
  2763. if err := db.Where("email IN ?", batch).Find(&page).Error; err != nil && err != gorm.ErrRecordNotFound {
  2764. return nil, nil, err
  2765. }
  2766. clients = append(clients, page...)
  2767. }
  2768. // Step 2: Sort clients by (Up + Down) descending
  2769. sort.Slice(clients, func(i, j int) bool {
  2770. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  2771. })
  2772. // Step 3: Extract sorted valid emails and track found ones
  2773. validEmails := make([]string, 0, len(clients))
  2774. found := make(map[string]bool)
  2775. for _, client := range clients {
  2776. validEmails = append(validEmails, client.Email)
  2777. found[client.Email] = true
  2778. }
  2779. // Step 4: Identify emails that were not found in the database
  2780. extraEmails := make([]string, 0)
  2781. for _, email := range emails {
  2782. if !found[email] {
  2783. extraEmails = append(extraEmails, email)
  2784. }
  2785. }
  2786. return validEmails, extraEmails, nil
  2787. }
  2788. func (s *InboundService) DelInboundClientByEmail(inboundId int, email string) (bool, error) {
  2789. oldInbound, err := s.GetInbound(inboundId)
  2790. if err != nil {
  2791. logger.Error("Load Old Data Error")
  2792. return false, err
  2793. }
  2794. var settings map[string]any
  2795. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  2796. return false, err
  2797. }
  2798. interfaceClients, ok := settings["clients"].([]any)
  2799. if !ok {
  2800. return false, common.NewError("invalid clients format in inbound settings")
  2801. }
  2802. var newClients []any
  2803. needApiDel := false
  2804. found := false
  2805. for _, client := range interfaceClients {
  2806. c, ok := client.(map[string]any)
  2807. if !ok {
  2808. continue
  2809. }
  2810. if cEmail, ok := c["email"].(string); ok && cEmail == email {
  2811. // matched client, drop it
  2812. found = true
  2813. needApiDel, _ = c["enable"].(bool)
  2814. } else {
  2815. newClients = append(newClients, client)
  2816. }
  2817. }
  2818. if !found {
  2819. return false, common.NewError(fmt.Sprintf("client with email %s not found", email))
  2820. }
  2821. if len(newClients) == 0 {
  2822. return false, common.NewError("no client remained in Inbound")
  2823. }
  2824. settings["clients"] = newClients
  2825. newSettings, err := json.MarshalIndent(settings, "", " ")
  2826. if err != nil {
  2827. return false, err
  2828. }
  2829. oldInbound.Settings = string(newSettings)
  2830. db := database.GetDB()
  2831. // remove IP bindings
  2832. if err := s.DelClientIPs(db, email); err != nil {
  2833. logger.Error("Error in delete client IPs")
  2834. return false, err
  2835. }
  2836. needRestart := false
  2837. // remove stats too
  2838. if len(email) > 0 {
  2839. traffic, err := s.GetClientTrafficByEmail(email)
  2840. if err != nil {
  2841. return false, err
  2842. }
  2843. if traffic != nil {
  2844. if err := s.DelClientStat(db, email); err != nil {
  2845. logger.Error("Delete stats Data Error")
  2846. return false, err
  2847. }
  2848. }
  2849. if needApiDel {
  2850. s.xrayApi.Init(p.GetAPIPort())
  2851. if err1 := s.xrayApi.RemoveUser(oldInbound.Tag, email); err1 == nil {
  2852. logger.Debug("Client deleted by api:", email)
  2853. needRestart = false
  2854. } else {
  2855. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  2856. logger.Debug("User is already deleted. Nothing to do more...")
  2857. } else {
  2858. logger.Debug("Error in deleting client by api:", err1)
  2859. needRestart = true
  2860. }
  2861. }
  2862. s.xrayApi.Close()
  2863. }
  2864. }
  2865. return needRestart, db.Save(oldInbound).Error
  2866. }