client.go 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874
  1. package service
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "slices"
  9. "sort"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "time"
  14. "github.com/google/uuid"
  15. "github.com/mhsanaei/3x-ui/v3/database"
  16. "github.com/mhsanaei/3x-ui/v3/database/model"
  17. "github.com/mhsanaei/3x-ui/v3/logger"
  18. "github.com/mhsanaei/3x-ui/v3/util/common"
  19. "github.com/mhsanaei/3x-ui/v3/util/random"
  20. "github.com/mhsanaei/3x-ui/v3/xray"
  21. "gorm.io/gorm"
  22. )
  23. type ClientWithAttachments struct {
  24. model.ClientRecord
  25. InboundIds []int `json:"inboundIds"`
  26. Traffic *xray.ClientTraffic `json:"traffic,omitempty"`
  27. }
  28. // MarshalJSON is required because model.ClientRecord defines its own
  29. // MarshalJSON. Go promotes the embedded method to the outer struct, so without
  30. // this the encoder would call ClientRecord.MarshalJSON for the whole value and
  31. // silently drop InboundIds and Traffic from the API response.
  32. func (c ClientWithAttachments) MarshalJSON() ([]byte, error) {
  33. rec, err := json.Marshal(c.ClientRecord)
  34. if err != nil {
  35. return nil, err
  36. }
  37. extras := struct {
  38. InboundIds []int `json:"inboundIds"`
  39. Traffic *xray.ClientTraffic `json:"traffic,omitempty"`
  40. }{InboundIds: c.InboundIds, Traffic: c.Traffic}
  41. extra, err := json.Marshal(extras)
  42. if err != nil {
  43. return nil, err
  44. }
  45. if len(rec) < 2 || rec[len(rec)-1] != '}' || len(extra) <= 2 {
  46. return rec, nil
  47. }
  48. const maxMarshalSize = 256 << 20
  49. if len(rec) > maxMarshalSize || len(extra) > maxMarshalSize {
  50. return rec, nil
  51. }
  52. out := make([]byte, 0, len(rec)+len(extra))
  53. out = append(out, rec[:len(rec)-1]...)
  54. if len(rec) > 2 {
  55. out = append(out, ',')
  56. }
  57. out = append(out, extra[1:]...)
  58. return out, nil
  59. }
  60. func clientKeyForProtocol(p model.Protocol, rec *model.ClientRecord) string {
  61. if rec == nil {
  62. return ""
  63. }
  64. switch p {
  65. case model.Trojan:
  66. return rec.Password
  67. case model.Shadowsocks:
  68. return rec.Email
  69. case model.Hysteria:
  70. return rec.Auth
  71. default:
  72. return rec.UUID
  73. }
  74. }
  75. type ClientService struct{}
  76. // Short-lived tombstone of just-deleted client emails so that a node snapshot
  77. // arriving between delete and node-side processing doesn't resurrect them.
  78. var (
  79. recentlyDeletedMu sync.Mutex
  80. recentlyDeleted = map[string]time.Time{}
  81. )
  82. const deleteTombstoneTTL = 90 * time.Second
  83. var (
  84. inboundMutationLocksMu sync.Mutex
  85. inboundMutationLocks = map[int]*sync.Mutex{}
  86. )
  87. func lockInbound(inboundId int) *sync.Mutex {
  88. inboundMutationLocksMu.Lock()
  89. defer inboundMutationLocksMu.Unlock()
  90. m, ok := inboundMutationLocks[inboundId]
  91. if !ok {
  92. m = &sync.Mutex{}
  93. inboundMutationLocks[inboundId] = m
  94. }
  95. m.Lock()
  96. return m
  97. }
  98. func compactOrphans(db *gorm.DB, clients []any) []any {
  99. if len(clients) == 0 {
  100. return clients
  101. }
  102. emails := make([]string, 0, len(clients))
  103. for _, c := range clients {
  104. cm, ok := c.(map[string]any)
  105. if !ok {
  106. continue
  107. }
  108. if e, _ := cm["email"].(string); e != "" {
  109. emails = append(emails, e)
  110. }
  111. }
  112. if len(emails) == 0 {
  113. return clients
  114. }
  115. var existingEmails []string
  116. if err := db.Model(&model.ClientRecord{}).Where("email IN ?", emails).Pluck("email", &existingEmails).Error; err != nil {
  117. logger.Warning("compactOrphans pluck:", err)
  118. return clients
  119. }
  120. if len(existingEmails) == len(emails) {
  121. return clients
  122. }
  123. existing := make(map[string]struct{}, len(existingEmails))
  124. for _, e := range existingEmails {
  125. existing[e] = struct{}{}
  126. }
  127. out := make([]any, 0, len(existingEmails))
  128. for _, c := range clients {
  129. cm, ok := c.(map[string]any)
  130. if !ok {
  131. out = append(out, c)
  132. continue
  133. }
  134. e, _ := cm["email"].(string)
  135. if e == "" {
  136. out = append(out, c)
  137. continue
  138. }
  139. if _, ok := existing[e]; ok {
  140. out = append(out, c)
  141. }
  142. }
  143. return out
  144. }
  145. func tombstoneClientEmail(email string) {
  146. if email == "" {
  147. return
  148. }
  149. recentlyDeletedMu.Lock()
  150. defer recentlyDeletedMu.Unlock()
  151. recentlyDeleted[email] = time.Now()
  152. cutoff := time.Now().Add(-deleteTombstoneTTL)
  153. for e, ts := range recentlyDeleted {
  154. if ts.Before(cutoff) {
  155. delete(recentlyDeleted, e)
  156. }
  157. }
  158. }
  159. func isClientEmailTombstoned(email string) bool {
  160. if email == "" {
  161. return false
  162. }
  163. recentlyDeletedMu.Lock()
  164. defer recentlyDeletedMu.Unlock()
  165. ts, ok := recentlyDeleted[email]
  166. if !ok {
  167. return false
  168. }
  169. if time.Since(ts) > deleteTombstoneTTL {
  170. delete(recentlyDeleted, email)
  171. return false
  172. }
  173. return true
  174. }
  175. func (s *ClientService) SyncInbound(tx *gorm.DB, inboundId int, clients []model.Client) error {
  176. if tx == nil {
  177. tx = database.GetDB()
  178. }
  179. if err := tx.Where("inbound_id = ?", inboundId).Delete(&model.ClientInbound{}).Error; err != nil {
  180. return err
  181. }
  182. for i := range clients {
  183. c := clients[i]
  184. email := strings.TrimSpace(c.Email)
  185. if email == "" {
  186. continue
  187. }
  188. incoming := c.ToRecord()
  189. row := &model.ClientRecord{}
  190. err := tx.Where("email = ?", email).First(row).Error
  191. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  192. return err
  193. }
  194. if errors.Is(err, gorm.ErrRecordNotFound) {
  195. if err := tx.Create(incoming).Error; err != nil {
  196. return err
  197. }
  198. row = incoming
  199. } else {
  200. if incoming.UUID != "" {
  201. row.UUID = incoming.UUID
  202. }
  203. if incoming.Password != "" {
  204. row.Password = incoming.Password
  205. }
  206. if incoming.Auth != "" {
  207. row.Auth = incoming.Auth
  208. }
  209. row.Flow = incoming.Flow
  210. if incoming.Security != "" {
  211. row.Security = incoming.Security
  212. }
  213. if incoming.Reverse != "" {
  214. row.Reverse = incoming.Reverse
  215. }
  216. row.SubID = incoming.SubID
  217. row.LimitIP = incoming.LimitIP
  218. row.TotalGB = incoming.TotalGB
  219. row.ExpiryTime = incoming.ExpiryTime
  220. row.Enable = incoming.Enable
  221. row.TgID = incoming.TgID
  222. row.Group = incoming.Group
  223. row.Comment = incoming.Comment
  224. row.Reset = incoming.Reset
  225. if incoming.CreatedAt > 0 && (row.CreatedAt == 0 || incoming.CreatedAt < row.CreatedAt) {
  226. row.CreatedAt = incoming.CreatedAt
  227. }
  228. preservedUpdatedAt := row.UpdatedAt
  229. if incoming.UpdatedAt > preservedUpdatedAt {
  230. preservedUpdatedAt = incoming.UpdatedAt
  231. }
  232. row.UpdatedAt = preservedUpdatedAt
  233. if err := tx.Save(row).Error; err != nil {
  234. return err
  235. }
  236. if err := tx.Model(&model.ClientRecord{}).
  237. Where("id = ?", row.Id).
  238. UpdateColumn("updated_at", preservedUpdatedAt).Error; err != nil {
  239. return err
  240. }
  241. }
  242. link := model.ClientInbound{
  243. ClientId: row.Id,
  244. InboundId: inboundId,
  245. FlowOverride: c.Flow,
  246. }
  247. if err := tx.Create(&link).Error; err != nil {
  248. return err
  249. }
  250. }
  251. return nil
  252. }
  253. func (s *ClientService) DetachInbound(tx *gorm.DB, inboundId int) error {
  254. if tx == nil {
  255. tx = database.GetDB()
  256. }
  257. return tx.Where("inbound_id = ?", inboundId).Delete(&model.ClientInbound{}).Error
  258. }
  259. func (s *ClientService) ListForInbound(tx *gorm.DB, inboundId int) ([]model.Client, error) {
  260. if tx == nil {
  261. tx = database.GetDB()
  262. }
  263. type joinedRow struct {
  264. model.ClientRecord
  265. FlowOverride string
  266. }
  267. var rows []joinedRow
  268. err := tx.Table("clients").
  269. Select("clients.*, client_inbounds.flow_override AS flow_override").
  270. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  271. Where("client_inbounds.inbound_id = ?", inboundId).
  272. Order("clients.id ASC").
  273. Find(&rows).Error
  274. if err != nil {
  275. return nil, err
  276. }
  277. out := make([]model.Client, 0, len(rows))
  278. for i := range rows {
  279. c := rows[i].ToClient()
  280. if rows[i].FlowOverride != "" {
  281. c.Flow = rows[i].FlowOverride
  282. }
  283. out = append(out, *c)
  284. }
  285. return out, nil
  286. }
  287. func (s *ClientService) GetRecordByEmail(tx *gorm.DB, email string) (*model.ClientRecord, error) {
  288. if tx == nil {
  289. tx = database.GetDB()
  290. }
  291. row := &model.ClientRecord{}
  292. err := tx.Where("email = ?", email).First(row).Error
  293. if err != nil {
  294. return nil, err
  295. }
  296. return row, nil
  297. }
  298. func (s *ClientService) GetInboundIdsForEmail(tx *gorm.DB, email string) ([]int, error) {
  299. if tx == nil {
  300. tx = database.GetDB()
  301. }
  302. var ids []int
  303. err := tx.Table("client_inbounds").
  304. Select("client_inbounds.inbound_id").
  305. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  306. Where("clients.email = ?", email).
  307. Scan(&ids).Error
  308. if err != nil {
  309. return nil, err
  310. }
  311. return ids, nil
  312. }
  313. func (s *ClientService) GetByID(id int) (*model.ClientRecord, error) {
  314. row := &model.ClientRecord{}
  315. if err := database.GetDB().Where("id = ?", id).First(row).Error; err != nil {
  316. return nil, err
  317. }
  318. return row, nil
  319. }
  320. func (s *ClientService) GetInboundIdsForRecord(id int) ([]int, error) {
  321. var ids []int
  322. err := database.GetDB().Table("client_inbounds").
  323. Where("client_id = ?", id).
  324. Order("inbound_id ASC").
  325. Pluck("inbound_id", &ids).Error
  326. if err != nil {
  327. return nil, err
  328. }
  329. return ids, nil
  330. }
  331. func (s *ClientService) List() ([]ClientWithAttachments, error) {
  332. db := database.GetDB()
  333. var rows []model.ClientRecord
  334. if err := db.Order("id ASC").Find(&rows).Error; err != nil {
  335. return nil, err
  336. }
  337. if len(rows) == 0 {
  338. return []ClientWithAttachments{}, nil
  339. }
  340. clientIds := make([]int, 0, len(rows))
  341. emails := make([]string, 0, len(rows))
  342. for i := range rows {
  343. clientIds = append(clientIds, rows[i].Id)
  344. if rows[i].Email != "" {
  345. emails = append(emails, rows[i].Email)
  346. }
  347. }
  348. var links []model.ClientInbound
  349. if err := db.Where("client_id IN ?", clientIds).Find(&links).Error; err != nil {
  350. return nil, err
  351. }
  352. attachments := make(map[int][]int, len(rows))
  353. for _, l := range links {
  354. attachments[l.ClientId] = append(attachments[l.ClientId], l.InboundId)
  355. }
  356. trafficByEmail := make(map[string]*xray.ClientTraffic, len(emails))
  357. if len(emails) > 0 {
  358. var stats []xray.ClientTraffic
  359. if err := db.Where("email IN ?", emails).Find(&stats).Error; err != nil {
  360. return nil, err
  361. }
  362. for i := range stats {
  363. trafficByEmail[stats[i].Email] = &stats[i]
  364. }
  365. }
  366. out := make([]ClientWithAttachments, 0, len(rows))
  367. for i := range rows {
  368. out = append(out, ClientWithAttachments{
  369. ClientRecord: rows[i],
  370. InboundIds: attachments[rows[i].Id],
  371. Traffic: trafficByEmail[rows[i].Email],
  372. })
  373. }
  374. return out, nil
  375. }
  376. type ClientCreatePayload struct {
  377. Client model.Client `json:"client"`
  378. InboundIds []int `json:"inboundIds"`
  379. }
  380. func (s *ClientService) Create(inboundSvc *InboundService, payload *ClientCreatePayload) (bool, error) {
  381. if payload == nil {
  382. return false, common.NewError("empty payload")
  383. }
  384. client := payload.Client
  385. if strings.TrimSpace(client.Email) == "" {
  386. return false, common.NewError("client email is required")
  387. }
  388. if len(payload.InboundIds) == 0 {
  389. return false, common.NewError("at least one inbound is required")
  390. }
  391. if client.SubID == "" {
  392. client.SubID = uuid.NewString()
  393. }
  394. if !client.Enable {
  395. client.Enable = true
  396. }
  397. now := time.Now().UnixMilli()
  398. if client.CreatedAt == 0 {
  399. client.CreatedAt = now
  400. }
  401. client.UpdatedAt = now
  402. existing := &model.ClientRecord{}
  403. err := database.GetDB().Where("email = ?", client.Email).First(existing).Error
  404. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  405. return false, err
  406. }
  407. emailTaken := !errors.Is(err, gorm.ErrRecordNotFound)
  408. if emailTaken {
  409. if existing.SubID == "" || existing.SubID != client.SubID {
  410. return false, common.NewError("email already in use:", client.Email)
  411. }
  412. }
  413. needRestart := false
  414. for _, ibId := range payload.InboundIds {
  415. inbound, getErr := inboundSvc.GetInbound(ibId)
  416. if getErr != nil {
  417. return needRestart, getErr
  418. }
  419. if err := s.fillProtocolDefaults(&client, inbound); err != nil {
  420. return needRestart, err
  421. }
  422. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {client}})
  423. if mErr != nil {
  424. return needRestart, mErr
  425. }
  426. nr, addErr := s.AddInboundClient(inboundSvc, &model.Inbound{
  427. Id: ibId,
  428. Settings: string(settingsPayload),
  429. })
  430. if addErr != nil {
  431. return needRestart, addErr
  432. }
  433. if nr {
  434. needRestart = true
  435. }
  436. }
  437. return needRestart, nil
  438. }
  439. func (s *ClientService) fillProtocolDefaults(c *model.Client, ib *model.Inbound) error {
  440. switch ib.Protocol {
  441. case model.VMESS, model.VLESS:
  442. if c.ID == "" {
  443. c.ID = uuid.NewString()
  444. }
  445. case model.Trojan:
  446. if c.Password == "" {
  447. c.Password = strings.ReplaceAll(uuid.NewString(), "-", "")
  448. }
  449. case model.Shadowsocks:
  450. method := shadowsocksMethodFromSettings(ib.Settings)
  451. if c.Password == "" || !validShadowsocksClientKey(method, c.Password) {
  452. c.Password = randomShadowsocksClientKey(method)
  453. }
  454. case model.Hysteria:
  455. if c.Auth == "" {
  456. c.Auth = strings.ReplaceAll(uuid.NewString(), "-", "")
  457. }
  458. }
  459. return nil
  460. }
  461. // shadowsocksMethodFromSettings pulls the "method" field out of the inbound's
  462. // settings JSON. Returns "" when the field is missing or settings is invalid.
  463. func shadowsocksMethodFromSettings(settings string) string {
  464. if settings == "" {
  465. return ""
  466. }
  467. var m map[string]any
  468. if err := json.Unmarshal([]byte(settings), &m); err != nil {
  469. return ""
  470. }
  471. method, _ := m["method"].(string)
  472. return method
  473. }
  474. // randomShadowsocksClientKey returns a per-client key sized to the cipher.
  475. // The 2022-blake3 ciphers require a base64-encoded key of an exact byte
  476. // length (16 bytes for aes-128-gcm, 32 bytes for aes-256-gcm and
  477. // chacha20-poly1305) — anything else fails with "bad key" on xray start.
  478. // Older ciphers accept arbitrary passwords, so we keep the uuid-style.
  479. func randomShadowsocksClientKey(method string) string {
  480. if n := shadowsocksKeyBytes(method); n > 0 {
  481. return random.Base64Bytes(n)
  482. }
  483. return strings.ReplaceAll(uuid.NewString(), "-", "")
  484. }
  485. // validShadowsocksClientKey reports whether key is acceptable for the cipher.
  486. // For 2022-blake3 it must decode to the exact byte length the cipher needs;
  487. // any other method accepts any non-empty string.
  488. func validShadowsocksClientKey(method, key string) bool {
  489. n := shadowsocksKeyBytes(method)
  490. if n == 0 {
  491. return key != ""
  492. }
  493. decoded, err := base64.StdEncoding.DecodeString(key)
  494. if err != nil {
  495. return false
  496. }
  497. return len(decoded) == n
  498. }
  499. func shadowsocksKeyBytes(method string) int {
  500. switch method {
  501. case "2022-blake3-aes-128-gcm":
  502. return 16
  503. case "2022-blake3-aes-256-gcm", "2022-blake3-chacha20-poly1305":
  504. return 32
  505. }
  506. return 0
  507. }
  508. // applyShadowsocksClientMethod normalises the per-client "method" field
  509. // when an inbound is created or updated:
  510. // - Legacy ciphers: backfill `method` so xray's multi-user code is happy.
  511. // "unsupported cipher method:" otherwise.
  512. // - 2022-blake3-*: strip the per-client `method` because xray rejects
  513. // it with "users must have empty method". This matters after an admin
  514. // switches an existing inbound from a legacy cipher to a 2022 one.
  515. func applyShadowsocksClientMethod(clients []any, settings map[string]any) {
  516. method, _ := settings["method"].(string)
  517. is2022 := strings.HasPrefix(method, "2022-blake3-")
  518. for i := range clients {
  519. cm, ok := clients[i].(map[string]any)
  520. if !ok {
  521. continue
  522. }
  523. if is2022 {
  524. if _, hasKey := cm["method"]; hasKey {
  525. delete(cm, "method")
  526. clients[i] = cm
  527. }
  528. continue
  529. }
  530. if method == "" {
  531. continue
  532. }
  533. if existing, _ := cm["method"].(string); existing != "" {
  534. continue
  535. }
  536. cm["method"] = method
  537. clients[i] = cm
  538. }
  539. }
  540. func (s *ClientService) Update(inboundSvc *InboundService, id int, updated model.Client) (bool, error) {
  541. existing, err := s.GetByID(id)
  542. if err != nil {
  543. return false, err
  544. }
  545. inboundIds, err := s.GetInboundIdsForRecord(id)
  546. if err != nil {
  547. return false, err
  548. }
  549. if strings.TrimSpace(updated.Email) == "" {
  550. return false, common.NewError("client email is required")
  551. }
  552. if updated.SubID == "" {
  553. updated.SubID = existing.SubID
  554. }
  555. if updated.SubID == "" {
  556. updated.SubID = uuid.NewString()
  557. }
  558. updated.UpdatedAt = time.Now().UnixMilli()
  559. if updated.CreatedAt == 0 {
  560. updated.CreatedAt = existing.CreatedAt
  561. }
  562. // Rename the ClientRecord row up front when the email changes. SyncInbound
  563. // (invoked from UpdateInboundClient below) looks up by email — without
  564. // renaming first it would treat the new email as a brand-new client,
  565. // insert a duplicate ClientRecord, and leave the original orphaned.
  566. if updated.Email != existing.Email {
  567. var collisionCount int64
  568. if err := database.GetDB().Model(&model.ClientRecord{}).
  569. Where("email = ? AND id <> ?", updated.Email, id).
  570. Count(&collisionCount).Error; err != nil {
  571. return false, err
  572. }
  573. if collisionCount > 0 {
  574. return false, common.NewError("Duplicate email:", updated.Email)
  575. }
  576. if err := database.GetDB().Model(&model.ClientRecord{}).
  577. Where("id = ?", id).
  578. Update("email", updated.Email).Error; err != nil {
  579. return false, err
  580. }
  581. }
  582. needRestart := false
  583. for _, ibId := range inboundIds {
  584. inbound, getErr := inboundSvc.GetInbound(ibId)
  585. if getErr != nil {
  586. return needRestart, getErr
  587. }
  588. oldKey := clientKeyForProtocol(inbound.Protocol, existing)
  589. if oldKey == "" {
  590. continue
  591. }
  592. if err := s.fillProtocolDefaults(&updated, inbound); err != nil {
  593. return needRestart, err
  594. }
  595. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {updated}})
  596. if mErr != nil {
  597. return needRestart, mErr
  598. }
  599. nr, upErr := s.UpdateInboundClient(inboundSvc, &model.Inbound{
  600. Id: ibId,
  601. Settings: string(settingsPayload),
  602. }, oldKey)
  603. if upErr != nil {
  604. return needRestart, upErr
  605. }
  606. if nr {
  607. needRestart = true
  608. }
  609. }
  610. if err := database.GetDB().Model(&model.ClientRecord{}).
  611. Where("id = ?", id).
  612. UpdateColumn("updated_at", time.Now().UnixMilli()).Error; err != nil {
  613. return needRestart, err
  614. }
  615. return needRestart, nil
  616. }
  617. func (s *ClientService) Delete(inboundSvc *InboundService, id int, keepTraffic bool) (bool, error) {
  618. existing, err := s.GetByID(id)
  619. if err != nil {
  620. return false, err
  621. }
  622. tombstoneClientEmail(existing.Email)
  623. inboundIds, err := s.GetInboundIdsForRecord(id)
  624. if err != nil {
  625. return false, err
  626. }
  627. needRestart := false
  628. for _, ibId := range inboundIds {
  629. inbound, getErr := inboundSvc.GetInbound(ibId)
  630. if getErr != nil {
  631. if errors.Is(getErr, gorm.ErrRecordNotFound) {
  632. continue
  633. }
  634. return needRestart, getErr
  635. }
  636. key := clientKeyForProtocol(inbound.Protocol, existing)
  637. if key == "" {
  638. continue
  639. }
  640. nr, delErr := s.DelInboundClient(inboundSvc, ibId, key)
  641. if delErr != nil {
  642. return needRestart, delErr
  643. }
  644. if nr {
  645. needRestart = true
  646. }
  647. }
  648. db := database.GetDB()
  649. if err := db.Where("client_id = ?", id).Delete(&model.ClientInbound{}).Error; err != nil {
  650. return needRestart, err
  651. }
  652. if !keepTraffic && existing.Email != "" {
  653. if err := db.Where("email = ?", existing.Email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  654. return needRestart, err
  655. }
  656. if err := db.Where("client_email = ?", existing.Email).Delete(&model.InboundClientIps{}).Error; err != nil {
  657. return needRestart, err
  658. }
  659. }
  660. if err := db.Delete(&model.ClientRecord{}, id).Error; err != nil {
  661. return needRestart, err
  662. }
  663. return needRestart, nil
  664. }
  665. func (s *ClientService) Attach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  666. existing, err := s.GetByID(id)
  667. if err != nil {
  668. return false, err
  669. }
  670. currentIds, err := s.GetInboundIdsForRecord(id)
  671. if err != nil {
  672. return false, err
  673. }
  674. have := make(map[int]struct{}, len(currentIds))
  675. for _, x := range currentIds {
  676. have[x] = struct{}{}
  677. }
  678. clientWire := existing.ToClient()
  679. clientWire.UpdatedAt = time.Now().UnixMilli()
  680. needRestart := false
  681. for _, ibId := range inboundIds {
  682. if _, attached := have[ibId]; attached {
  683. continue
  684. }
  685. inbound, getErr := inboundSvc.GetInbound(ibId)
  686. if getErr != nil {
  687. return needRestart, getErr
  688. }
  689. copyClient := *clientWire
  690. if err := s.fillProtocolDefaults(&copyClient, inbound); err != nil {
  691. return needRestart, err
  692. }
  693. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {copyClient}})
  694. if mErr != nil {
  695. return needRestart, mErr
  696. }
  697. nr, addErr := s.AddInboundClient(inboundSvc, &model.Inbound{
  698. Id: ibId,
  699. Settings: string(settingsPayload),
  700. })
  701. if addErr != nil {
  702. return needRestart, addErr
  703. }
  704. if nr {
  705. needRestart = true
  706. }
  707. }
  708. return needRestart, nil
  709. }
  710. func (s *ClientService) CreateOne(inboundSvc *InboundService, inboundId int, client model.Client) (bool, error) {
  711. return s.Create(inboundSvc, &ClientCreatePayload{
  712. Client: client,
  713. InboundIds: []int{inboundId},
  714. })
  715. }
  716. func (s *ClientService) DetachByEmail(inboundSvc *InboundService, inboundId int, email string) (bool, error) {
  717. if email == "" {
  718. return false, common.NewError("client email is required")
  719. }
  720. rec, err := s.GetRecordByEmail(nil, email)
  721. if err != nil {
  722. return false, err
  723. }
  724. return s.Detach(inboundSvc, rec.Id, []int{inboundId})
  725. }
  726. func (s *ClientService) AttachByEmail(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  727. if email == "" {
  728. return false, common.NewError("client email is required")
  729. }
  730. rec, err := s.GetRecordByEmail(nil, email)
  731. if err != nil {
  732. return false, err
  733. }
  734. return s.Attach(inboundSvc, rec.Id, inboundIds)
  735. }
  736. // BulkAttachResult reports the outcome of a bulk attach across target inbounds.
  737. type BulkAttachResult struct {
  738. Attached []string `json:"attached"`
  739. Skipped []string `json:"skipped"`
  740. Errors []string `json:"errors"`
  741. }
  742. // BulkAttach attaches the given existing clients (by email) to each target inbound,
  743. // reusing their identity (email/UUID/password/subId) and a shared traffic row. It adds
  744. // all clients to a target in a single AddInboundClient call, and reports clients already
  745. // present on a target as skipped.
  746. func (s *ClientService) BulkAttach(inboundSvc *InboundService, emails []string, inboundIds []int) (*BulkAttachResult, bool, error) {
  747. result := &BulkAttachResult{}
  748. if len(emails) == 0 || len(inboundIds) == 0 {
  749. return result, false, nil
  750. }
  751. records := make([]*model.ClientRecord, 0, len(emails))
  752. seenEmail := make(map[string]struct{}, len(emails))
  753. for _, email := range emails {
  754. if email == "" {
  755. continue
  756. }
  757. key := strings.ToLower(email)
  758. if _, ok := seenEmail[key]; ok {
  759. continue
  760. }
  761. seenEmail[key] = struct{}{}
  762. rec, err := s.GetRecordByEmail(nil, email)
  763. if err != nil {
  764. result.Errors = append(result.Errors, fmt.Sprintf("%s: %v", email, err))
  765. continue
  766. }
  767. records = append(records, rec)
  768. }
  769. needRestart := false
  770. for _, ibId := range inboundIds {
  771. inbound, err := inboundSvc.GetInbound(ibId)
  772. if err != nil {
  773. result.Errors = append(result.Errors, fmt.Sprintf("inbound %d: %v", ibId, err))
  774. continue
  775. }
  776. existingClients, err := inboundSvc.GetClients(inbound)
  777. if err != nil {
  778. result.Errors = append(result.Errors, fmt.Sprintf("inbound %d: %v", ibId, err))
  779. continue
  780. }
  781. have := make(map[string]struct{}, len(existingClients))
  782. for _, c := range existingClients {
  783. have[strings.ToLower(c.Email)] = struct{}{}
  784. }
  785. clientsToAdd := make([]model.Client, 0, len(records))
  786. for _, rec := range records {
  787. if _, attached := have[strings.ToLower(rec.Email)]; attached {
  788. result.Skipped = append(result.Skipped, rec.Email)
  789. continue
  790. }
  791. client := *rec.ToClient()
  792. client.UpdatedAt = time.Now().UnixMilli()
  793. if err := s.fillProtocolDefaults(&client, inbound); err != nil {
  794. result.Errors = append(result.Errors, fmt.Sprintf("%s -> inbound %d: %v", rec.Email, ibId, err))
  795. continue
  796. }
  797. clientsToAdd = append(clientsToAdd, client)
  798. }
  799. if len(clientsToAdd) == 0 {
  800. continue
  801. }
  802. payload, err := json.Marshal(map[string][]model.Client{"clients": clientsToAdd})
  803. if err != nil {
  804. result.Errors = append(result.Errors, fmt.Sprintf("inbound %d: %v", ibId, err))
  805. continue
  806. }
  807. nr, err := s.AddInboundClient(inboundSvc, &model.Inbound{Id: ibId, Settings: string(payload)})
  808. if err != nil {
  809. result.Errors = append(result.Errors, fmt.Sprintf("inbound %d: %v", ibId, err))
  810. continue
  811. }
  812. if nr {
  813. needRestart = true
  814. }
  815. for _, c := range clientsToAdd {
  816. result.Attached = append(result.Attached, c.Email)
  817. }
  818. }
  819. return result, needRestart, nil
  820. }
  821. // BulkDetachResult reports the outcome of a bulk detach across target inbounds.
  822. type BulkDetachResult struct {
  823. Detached []string `json:"detached"`
  824. Skipped []string `json:"skipped"`
  825. Errors []string `json:"errors"`
  826. }
  827. // BulkDetach detaches the given existing clients (by email) from each target inbound.
  828. // (email, inbound) pairs where the client is not currently attached are silently skipped
  829. // at the inbound level; emails that aren't attached to any of the requested inbounds
  830. // are reported under skipped. ClientRecord rows are kept even when they become orphaned
  831. // (matches single-client detach semantics); callers should use bulkDelete for full removal.
  832. func (s *ClientService) BulkDetach(inboundSvc *InboundService, emails []string, inboundIds []int) (*BulkDetachResult, bool, error) {
  833. result := &BulkDetachResult{}
  834. if len(emails) == 0 || len(inboundIds) == 0 {
  835. return result, false, nil
  836. }
  837. requested := make(map[int]struct{}, len(inboundIds))
  838. for _, id := range inboundIds {
  839. requested[id] = struct{}{}
  840. }
  841. needRestart := false
  842. seenEmail := make(map[string]struct{}, len(emails))
  843. for _, email := range emails {
  844. if email == "" {
  845. continue
  846. }
  847. key := strings.ToLower(email)
  848. if _, ok := seenEmail[key]; ok {
  849. continue
  850. }
  851. seenEmail[key] = struct{}{}
  852. rec, err := s.GetRecordByEmail(nil, email)
  853. if err != nil {
  854. result.Errors = append(result.Errors, fmt.Sprintf("%s: %v", email, err))
  855. continue
  856. }
  857. currentIds, err := s.GetInboundIdsForRecord(rec.Id)
  858. if err != nil {
  859. result.Errors = append(result.Errors, fmt.Sprintf("%s: %v", email, err))
  860. continue
  861. }
  862. intersection := make([]int, 0, len(currentIds))
  863. for _, id := range currentIds {
  864. if _, ok := requested[id]; ok {
  865. intersection = append(intersection, id)
  866. }
  867. }
  868. if len(intersection) == 0 {
  869. result.Skipped = append(result.Skipped, rec.Email)
  870. continue
  871. }
  872. nr, err := s.Detach(inboundSvc, rec.Id, intersection)
  873. if err != nil {
  874. result.Errors = append(result.Errors, fmt.Sprintf("%s: %v", rec.Email, err))
  875. continue
  876. }
  877. if nr {
  878. needRestart = true
  879. }
  880. result.Detached = append(result.Detached, rec.Email)
  881. }
  882. return result, needRestart, nil
  883. }
  884. func (s *ClientService) DetachByEmailMany(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  885. if email == "" {
  886. return false, common.NewError("client email is required")
  887. }
  888. rec, err := s.GetRecordByEmail(nil, email)
  889. if err != nil {
  890. return false, err
  891. }
  892. return s.Detach(inboundSvc, rec.Id, inboundIds)
  893. }
  894. func (s *ClientService) DeleteByEmail(inboundSvc *InboundService, email string, keepTraffic bool) (bool, error) {
  895. if email == "" {
  896. return false, common.NewError("client email is required")
  897. }
  898. rec, err := s.GetRecordByEmail(nil, email)
  899. if err == nil {
  900. return s.Delete(inboundSvc, rec.Id, keepTraffic)
  901. }
  902. if !errors.Is(err, gorm.ErrRecordNotFound) {
  903. return false, err
  904. }
  905. inboundIds, idsErr := s.findInboundIdsByClientEmail(email)
  906. if idsErr != nil {
  907. return false, idsErr
  908. }
  909. if len(inboundIds) == 0 {
  910. return false, common.NewError(fmt.Sprintf("client %q not found in any inbound or client record", email))
  911. }
  912. needRestart := false
  913. for _, ibId := range inboundIds {
  914. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, email)
  915. if delErr != nil {
  916. return needRestart, delErr
  917. }
  918. if nr {
  919. needRestart = true
  920. }
  921. }
  922. if !keepTraffic {
  923. db := database.GetDB()
  924. if err := db.Where("email = ?", email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  925. return needRestart, err
  926. }
  927. if err := db.Where("client_email = ?", email).Delete(&model.InboundClientIps{}).Error; err != nil {
  928. return needRestart, err
  929. }
  930. }
  931. return needRestart, nil
  932. }
  933. // findInboundIdsByClientEmail returns every inbound whose settings.clients[]
  934. // JSON contains an entry with the given email. Driver-portable (no JSON
  935. // operators) by parsing in Go — fine for the rare fallback path.
  936. func (s *ClientService) findInboundIdsByClientEmail(email string) ([]int, error) {
  937. var inbounds []model.Inbound
  938. if err := database.GetDB().
  939. Select("id, settings").
  940. Where("settings LIKE ?", "%"+email+"%").
  941. Find(&inbounds).Error; err != nil {
  942. return nil, err
  943. }
  944. out := make([]int, 0, len(inbounds))
  945. for _, ib := range inbounds {
  946. var settings map[string]any
  947. if err := json.Unmarshal([]byte(ib.Settings), &settings); err != nil {
  948. continue
  949. }
  950. clients, ok := settings["clients"].([]any)
  951. if !ok {
  952. continue
  953. }
  954. for _, c := range clients {
  955. cm, ok := c.(map[string]any)
  956. if !ok {
  957. continue
  958. }
  959. if cEmail, _ := cm["email"].(string); cEmail == email {
  960. out = append(out, ib.Id)
  961. break
  962. }
  963. }
  964. }
  965. return out, nil
  966. }
  967. func (s *ClientService) UpdateByEmail(inboundSvc *InboundService, email string, updated model.Client) (bool, error) {
  968. if email == "" {
  969. return false, common.NewError("client email is required")
  970. }
  971. rec, err := s.GetRecordByEmail(nil, email)
  972. if err != nil {
  973. return false, err
  974. }
  975. return s.Update(inboundSvc, rec.Id, updated)
  976. }
  977. func (s *ClientService) ResetTrafficByEmail(inboundSvc *InboundService, email string) (bool, error) {
  978. if email == "" {
  979. return false, common.NewError("client email is required")
  980. }
  981. rec, err := s.GetRecordByEmail(nil, email)
  982. if err != nil {
  983. return false, err
  984. }
  985. inboundIds, err := s.GetInboundIdsForRecord(rec.Id)
  986. if err != nil {
  987. return false, err
  988. }
  989. if len(inboundIds) == 0 {
  990. if rErr := inboundSvc.ResetClientTrafficByEmail(email); rErr != nil {
  991. return false, rErr
  992. }
  993. return false, nil
  994. }
  995. needRestart := false
  996. for _, ibId := range inboundIds {
  997. nr, rErr := inboundSvc.ResetClientTraffic(ibId, email)
  998. if rErr != nil {
  999. return needRestart, rErr
  1000. }
  1001. if nr {
  1002. needRestart = true
  1003. }
  1004. }
  1005. return needRestart, nil
  1006. }
  1007. // ClientSlim is the row-shape used by the clients page. It drops fields the
  1008. // table never reads (UUID, password, auth, flow, security, reverse, tgId)
  1009. // so the list payload stays compact even when the panel manages thousands
  1010. // of clients. Modals that need the full record still call /get/:email.
  1011. type ClientSlim struct {
  1012. Email string `json:"email"`
  1013. SubID string `json:"subId"`
  1014. Enable bool `json:"enable"`
  1015. TotalGB int64 `json:"totalGB"`
  1016. ExpiryTime int64 `json:"expiryTime"`
  1017. LimitIP int `json:"limitIp"`
  1018. Reset int `json:"reset"`
  1019. Group string `json:"group,omitempty"`
  1020. Comment string `json:"comment,omitempty"`
  1021. InboundIds []int `json:"inboundIds"`
  1022. Traffic *xray.ClientTraffic `json:"traffic,omitempty"`
  1023. CreatedAt int64 `json:"createdAt"`
  1024. UpdatedAt int64 `json:"updatedAt"`
  1025. }
  1026. // ClientPageParams are the query params accepted by /panel/api/clients/list/paged.
  1027. // All fields are optional — the empty value means "no filter" / defaults.
  1028. //
  1029. // Filter / Protocol / Inbound accept either a single value or a comma-separated
  1030. // list; matching is OR within a field and AND across fields. The numeric range
  1031. // fields treat 0 as "unset" on the lower bound and 0 (or negative) as
  1032. // "unbounded" on the upper bound.
  1033. type ClientPageParams struct {
  1034. Page int `form:"page"`
  1035. PageSize int `form:"pageSize"`
  1036. Search string `form:"search"`
  1037. Filter string `form:"filter"`
  1038. Protocol string `form:"protocol"`
  1039. Inbound string `form:"inbound"`
  1040. Sort string `form:"sort"`
  1041. Order string `form:"order"`
  1042. ExpiryFrom int64 `form:"expiryFrom"`
  1043. ExpiryTo int64 `form:"expiryTo"`
  1044. UsageFrom int64 `form:"usageFrom"`
  1045. UsageTo int64 `form:"usageTo"`
  1046. AutoRenew string `form:"autoRenew"`
  1047. HasTgID string `form:"hasTgId"`
  1048. HasComment string `form:"hasComment"`
  1049. Group string `form:"group"`
  1050. }
  1051. // ClientPageResponse is the shape returned by ListPaged. `Total` is the
  1052. // row count in the DB; `Filtered` is the count after Search/Filter/Protocol
  1053. // were applied, before pagination. The page contains at most PageSize items.
  1054. // Summary is computed across the full DB row set so dashboard counters
  1055. // on the clients page stay stable as the user paginates/filters.
  1056. type ClientPageResponse struct {
  1057. Items []ClientSlim `json:"items"`
  1058. Total int `json:"total"`
  1059. Filtered int `json:"filtered"`
  1060. Page int `json:"page"`
  1061. PageSize int `json:"pageSize"`
  1062. Summary ClientsSummary `json:"summary"`
  1063. Groups []string `json:"groups"`
  1064. }
  1065. // ClientsSummary collects per-bucket counts plus the matching email lists so
  1066. // the clients page can render the dashboard stat cards and their hover
  1067. // popovers without shipping the full client array.
  1068. type ClientsSummary struct {
  1069. Total int `json:"total"`
  1070. Active int `json:"active"`
  1071. Online []string `json:"online"`
  1072. Depleted []string `json:"depleted"`
  1073. Expiring []string `json:"expiring"`
  1074. Deactive []string `json:"deactive"`
  1075. }
  1076. const (
  1077. clientPageDefaultSize = 25
  1078. clientPageMaxSize = 200
  1079. )
  1080. // ListPaged loads every client (with traffic + attachments) into memory,
  1081. // applies the requested filter / search / protocol predicates, sorts, and
  1082. // returns the requested page along with total and filtered counts. The DB
  1083. // query itself is unchanged from List(); the win is that the response
  1084. // only carries 25-ish slim rows over the wire instead of all 2000 full
  1085. // records, which on real panels was the dominant cost.
  1086. func (s *ClientService) ListPaged(inboundSvc *InboundService, settingSvc *SettingService, params ClientPageParams) (*ClientPageResponse, error) {
  1087. all, err := s.List()
  1088. if err != nil {
  1089. return nil, err
  1090. }
  1091. total := len(all)
  1092. pageSize := params.PageSize
  1093. if pageSize <= 0 {
  1094. pageSize = clientPageDefaultSize
  1095. }
  1096. if pageSize > clientPageMaxSize {
  1097. pageSize = clientPageMaxSize
  1098. }
  1099. page := params.Page
  1100. if page <= 0 {
  1101. page = 1
  1102. }
  1103. protocols := parseCSVStrings(params.Protocol)
  1104. inboundIDs := parseCSVInts(params.Inbound)
  1105. buckets := parseCSVStrings(params.Filter)
  1106. var protocolByInbound map[int]string
  1107. if len(protocols) > 0 {
  1108. inbounds, err := inboundSvc.GetAllInbounds()
  1109. if err == nil {
  1110. protocolByInbound = make(map[int]string, len(inbounds))
  1111. for _, ib := range inbounds {
  1112. protocolByInbound[ib.Id] = string(ib.Protocol)
  1113. }
  1114. }
  1115. }
  1116. onlines := inboundSvc.GetOnlineClients()
  1117. onlineSet := make(map[string]struct{}, len(onlines))
  1118. for _, e := range onlines {
  1119. onlineSet[e] = struct{}{}
  1120. }
  1121. var expireDiffMs, trafficDiffBytes int64
  1122. if settingSvc != nil {
  1123. if v, err := settingSvc.GetExpireDiff(); err == nil {
  1124. expireDiffMs = int64(v) * 86400000
  1125. }
  1126. if v, err := settingSvc.GetTrafficDiff(); err == nil {
  1127. trafficDiffBytes = int64(v) * 1073741824
  1128. }
  1129. }
  1130. nowMs := time.Now().UnixMilli()
  1131. summary := buildClientsSummary(all, onlineSet, nowMs, expireDiffMs, trafficDiffBytes)
  1132. needle := strings.ToLower(strings.TrimSpace(params.Search))
  1133. filtered := make([]ClientWithAttachments, 0, len(all))
  1134. for _, c := range all {
  1135. if needle != "" && !clientMatchesSearch(c, needle) {
  1136. continue
  1137. }
  1138. if len(protocols) > 0 && !clientMatchesAnyProtocol(c, protocols, protocolByInbound) {
  1139. continue
  1140. }
  1141. if len(inboundIDs) > 0 && !clientMatchesAnyInbound(c, inboundIDs) {
  1142. continue
  1143. }
  1144. if len(buckets) > 0 && !clientMatchesAnyBucket(c, buckets, onlineSet, nowMs, expireDiffMs, trafficDiffBytes) {
  1145. continue
  1146. }
  1147. if !clientMatchesExpiryRange(c, params.ExpiryFrom, params.ExpiryTo) {
  1148. continue
  1149. }
  1150. if !clientMatchesUsageRange(c, params.UsageFrom, params.UsageTo) {
  1151. continue
  1152. }
  1153. if !clientMatchesAutoRenew(c, params.AutoRenew) {
  1154. continue
  1155. }
  1156. if !clientMatchesHasTgID(c, params.HasTgID) {
  1157. continue
  1158. }
  1159. if !clientMatchesHasComment(c, params.HasComment) {
  1160. continue
  1161. }
  1162. if !clientMatchesAnyGroup(c, params.Group) {
  1163. continue
  1164. }
  1165. filtered = append(filtered, c)
  1166. }
  1167. sortClients(filtered, params.Sort, params.Order)
  1168. filteredCount := len(filtered)
  1169. start := (page - 1) * pageSize
  1170. end := start + pageSize
  1171. if start > filteredCount {
  1172. start = filteredCount
  1173. }
  1174. if end > filteredCount {
  1175. end = filteredCount
  1176. }
  1177. pageRows := filtered[start:end]
  1178. items := make([]ClientSlim, 0, len(pageRows))
  1179. for _, c := range pageRows {
  1180. items = append(items, toClientSlim(c))
  1181. }
  1182. groupRows, gErr := s.ListGroups()
  1183. if gErr != nil {
  1184. return nil, gErr
  1185. }
  1186. groups := make([]string, 0, len(groupRows))
  1187. for _, g := range groupRows {
  1188. groups = append(groups, g.Name)
  1189. }
  1190. return &ClientPageResponse{
  1191. Items: items,
  1192. Total: total,
  1193. Filtered: filteredCount,
  1194. Page: page,
  1195. PageSize: pageSize,
  1196. Summary: summary,
  1197. Groups: groups,
  1198. }, nil
  1199. }
  1200. type GroupSummary struct {
  1201. Name string `json:"name"`
  1202. ClientCount int `json:"clientCount"`
  1203. }
  1204. func (s *ClientService) ListGroups() ([]GroupSummary, error) {
  1205. db := database.GetDB()
  1206. var derived []GroupSummary
  1207. if err := db.Model(&model.ClientRecord{}).
  1208. Select("group_name AS name, COUNT(*) AS client_count").
  1209. Where("group_name <> ''").
  1210. Group("group_name").
  1211. Scan(&derived).Error; err != nil {
  1212. return nil, err
  1213. }
  1214. var stored []model.ClientGroup
  1215. if err := db.Find(&stored).Error; err != nil {
  1216. return nil, err
  1217. }
  1218. merged := make(map[string]int, len(derived)+len(stored))
  1219. for _, g := range stored {
  1220. merged[g.Name] = 0
  1221. }
  1222. for _, g := range derived {
  1223. merged[g.Name] = g.ClientCount
  1224. }
  1225. out := make([]GroupSummary, 0, len(merged))
  1226. for name, count := range merged {
  1227. out = append(out, GroupSummary{Name: name, ClientCount: count})
  1228. }
  1229. sort.Slice(out, func(i, j int) bool {
  1230. return strings.ToLower(out[i].Name) < strings.ToLower(out[j].Name)
  1231. })
  1232. return out, nil
  1233. }
  1234. func (s *ClientService) EmailsByGroup(name string) ([]string, error) {
  1235. name = strings.TrimSpace(name)
  1236. if name == "" {
  1237. return []string{}, nil
  1238. }
  1239. db := database.GetDB()
  1240. var emails []string
  1241. if err := db.Model(&model.ClientRecord{}).
  1242. Where("group_name = ?", name).
  1243. Order("email ASC").
  1244. Pluck("email", &emails).Error; err != nil {
  1245. return nil, err
  1246. }
  1247. if emails == nil {
  1248. emails = []string{}
  1249. }
  1250. return emails, nil
  1251. }
  1252. func (s *ClientService) BulkResetTraffic(inboundSvc *InboundService, emails []string) (int, error) {
  1253. if len(emails) == 0 {
  1254. return 0, nil
  1255. }
  1256. count := 0
  1257. for _, email := range emails {
  1258. if _, err := s.ResetTrafficByEmail(inboundSvc, email); err != nil {
  1259. return count, err
  1260. }
  1261. count++
  1262. }
  1263. return count, nil
  1264. }
  1265. func (s *ClientService) CreateGroup(name string) error {
  1266. name = strings.TrimSpace(name)
  1267. if name == "" {
  1268. return common.NewError("group name is required")
  1269. }
  1270. db := database.GetDB()
  1271. var count int64
  1272. if err := db.Model(&model.ClientGroup{}).Where("name = ?", name).Count(&count).Error; err != nil {
  1273. return err
  1274. }
  1275. if count > 0 {
  1276. return common.NewError("group already exists")
  1277. }
  1278. return db.Create(&model.ClientGroup{Name: name}).Error
  1279. }
  1280. func (s *ClientService) RenameGroup(oldName, newName string) (int, error) {
  1281. oldName = strings.TrimSpace(oldName)
  1282. newName = strings.TrimSpace(newName)
  1283. if oldName == "" {
  1284. return 0, common.NewError("old group name is required")
  1285. }
  1286. if newName == "" {
  1287. return 0, common.NewError("new group name is required")
  1288. }
  1289. if oldName == newName {
  1290. return 0, nil
  1291. }
  1292. return s.replaceGroupValue(oldName, newName)
  1293. }
  1294. func (s *ClientService) DeleteGroup(name string) (int, error) {
  1295. name = strings.TrimSpace(name)
  1296. if name == "" {
  1297. return 0, common.NewError("group name is required")
  1298. }
  1299. return s.replaceGroupValue(name, "")
  1300. }
  1301. func (s *ClientService) RemoveFromGroup(emails []string) (int, error) {
  1302. return s.AddToGroup(emails, "")
  1303. }
  1304. func (s *ClientService) AddToGroup(emails []string, group string) (int, error) {
  1305. group = strings.TrimSpace(group)
  1306. if len(emails) == 0 {
  1307. return 0, nil
  1308. }
  1309. db := database.GetDB()
  1310. if group != "" {
  1311. var exists int64
  1312. if err := db.Model(&model.ClientGroup{}).Where("name = ?", group).Count(&exists).Error; err != nil {
  1313. return 0, err
  1314. }
  1315. if exists == 0 {
  1316. var derived int64
  1317. if err := db.Model(&model.ClientRecord{}).Where("group_name = ?", group).Count(&derived).Error; err != nil {
  1318. return 0, err
  1319. }
  1320. if derived == 0 {
  1321. if err := db.Create(&model.ClientGroup{Name: group}).Error; err != nil {
  1322. return 0, err
  1323. }
  1324. }
  1325. }
  1326. }
  1327. var records []model.ClientRecord
  1328. if err := db.Where("email IN ?", emails).Find(&records).Error; err != nil {
  1329. return 0, err
  1330. }
  1331. if len(records) == 0 {
  1332. return 0, nil
  1333. }
  1334. affectedEmails := make([]string, 0, len(records))
  1335. for _, r := range records {
  1336. affectedEmails = append(affectedEmails, r.Email)
  1337. }
  1338. tx := db.Begin()
  1339. if err := tx.Model(&model.ClientRecord{}).
  1340. Where("email IN ?", affectedEmails).
  1341. UpdateColumn("group_name", group).Error; err != nil {
  1342. tx.Rollback()
  1343. return 0, err
  1344. }
  1345. var inboundIDs []int
  1346. if err := tx.Table("client_inbounds").
  1347. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  1348. Where("clients.email IN ?", affectedEmails).
  1349. Distinct("client_inbounds.inbound_id").
  1350. Pluck("inbound_id", &inboundIDs).Error; err != nil {
  1351. tx.Rollback()
  1352. return 0, err
  1353. }
  1354. emailSet := make(map[string]struct{}, len(affectedEmails))
  1355. for _, e := range affectedEmails {
  1356. emailSet[e] = struct{}{}
  1357. }
  1358. for _, ibID := range inboundIDs {
  1359. var ib model.Inbound
  1360. if err := tx.First(&ib, ibID).Error; err != nil {
  1361. tx.Rollback()
  1362. return 0, err
  1363. }
  1364. var settings map[string]any
  1365. if err := json.Unmarshal([]byte(ib.Settings), &settings); err != nil {
  1366. continue
  1367. }
  1368. clients, ok := settings["clients"].([]any)
  1369. if !ok {
  1370. continue
  1371. }
  1372. modified := false
  1373. for i := range clients {
  1374. cm, ok := clients[i].(map[string]any)
  1375. if !ok {
  1376. continue
  1377. }
  1378. email, _ := cm["email"].(string)
  1379. if _, hit := emailSet[email]; !hit {
  1380. continue
  1381. }
  1382. if group == "" {
  1383. delete(cm, "group")
  1384. } else {
  1385. cm["group"] = group
  1386. }
  1387. clients[i] = cm
  1388. modified = true
  1389. }
  1390. if modified {
  1391. settings["clients"] = clients
  1392. newSettings, err := json.Marshal(settings)
  1393. if err != nil {
  1394. continue
  1395. }
  1396. ib.Settings = string(newSettings)
  1397. if err := tx.Save(&ib).Error; err != nil {
  1398. tx.Rollback()
  1399. return 0, err
  1400. }
  1401. }
  1402. }
  1403. if err := tx.Commit().Error; err != nil {
  1404. return 0, err
  1405. }
  1406. return len(records), nil
  1407. }
  1408. func (s *ClientService) replaceGroupValue(oldName, newName string) (int, error) {
  1409. db := database.GetDB()
  1410. if newName == "" {
  1411. if err := db.Where("name = ?", oldName).Delete(&model.ClientGroup{}).Error; err != nil {
  1412. return 0, err
  1413. }
  1414. } else {
  1415. if err := db.Model(&model.ClientGroup{}).Where("name = ?", oldName).Update("name", newName).Error; err != nil {
  1416. return 0, err
  1417. }
  1418. }
  1419. var records []model.ClientRecord
  1420. if err := db.Where("group_name = ?", oldName).Find(&records).Error; err != nil {
  1421. return 0, err
  1422. }
  1423. if len(records) == 0 {
  1424. return 0, nil
  1425. }
  1426. affectedEmails := make([]string, 0, len(records))
  1427. for _, r := range records {
  1428. affectedEmails = append(affectedEmails, r.Email)
  1429. }
  1430. tx := db.Begin()
  1431. if err := tx.Model(&model.ClientRecord{}).
  1432. Where("group_name = ?", oldName).
  1433. UpdateColumn("group_name", newName).Error; err != nil {
  1434. tx.Rollback()
  1435. return 0, err
  1436. }
  1437. var inboundIDs []int
  1438. if err := tx.Table("client_inbounds").
  1439. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  1440. Where("clients.email IN ?", affectedEmails).
  1441. Distinct("client_inbounds.inbound_id").
  1442. Pluck("inbound_id", &inboundIDs).Error; err != nil {
  1443. tx.Rollback()
  1444. return 0, err
  1445. }
  1446. for _, ibID := range inboundIDs {
  1447. var ib model.Inbound
  1448. if err := tx.First(&ib, ibID).Error; err != nil {
  1449. tx.Rollback()
  1450. return 0, err
  1451. }
  1452. var settings map[string]any
  1453. if err := json.Unmarshal([]byte(ib.Settings), &settings); err != nil {
  1454. continue
  1455. }
  1456. clients, ok := settings["clients"].([]any)
  1457. if !ok {
  1458. continue
  1459. }
  1460. modified := false
  1461. for i := range clients {
  1462. cm, ok := clients[i].(map[string]any)
  1463. if !ok {
  1464. continue
  1465. }
  1466. if g, ok := cm["group"].(string); ok && g == oldName {
  1467. if newName == "" {
  1468. delete(cm, "group")
  1469. } else {
  1470. cm["group"] = newName
  1471. }
  1472. clients[i] = cm
  1473. modified = true
  1474. }
  1475. }
  1476. if modified {
  1477. settings["clients"] = clients
  1478. newSettings, err := json.Marshal(settings)
  1479. if err != nil {
  1480. continue
  1481. }
  1482. ib.Settings = string(newSettings)
  1483. if err := tx.Save(&ib).Error; err != nil {
  1484. tx.Rollback()
  1485. return 0, err
  1486. }
  1487. }
  1488. }
  1489. if err := tx.Commit().Error; err != nil {
  1490. return 0, err
  1491. }
  1492. return len(records), nil
  1493. }
  1494. func buildClientsSummary(all []ClientWithAttachments, onlineSet map[string]struct{}, nowMs, expireDiffMs, trafficDiffBytes int64) ClientsSummary {
  1495. s := ClientsSummary{
  1496. Total: len(all),
  1497. Online: []string{},
  1498. Depleted: []string{},
  1499. Expiring: []string{},
  1500. Deactive: []string{},
  1501. }
  1502. for _, c := range all {
  1503. used := int64(0)
  1504. if c.Traffic != nil {
  1505. used = c.Traffic.Up + c.Traffic.Down
  1506. }
  1507. exhausted := c.TotalGB > 0 && used >= c.TotalGB
  1508. expired := c.ExpiryTime > 0 && c.ExpiryTime <= nowMs
  1509. if c.Enable {
  1510. if _, ok := onlineSet[c.Email]; ok {
  1511. s.Online = append(s.Online, c.Email)
  1512. }
  1513. }
  1514. if exhausted || expired {
  1515. s.Depleted = append(s.Depleted, c.Email)
  1516. continue
  1517. }
  1518. if !c.Enable {
  1519. s.Deactive = append(s.Deactive, c.Email)
  1520. continue
  1521. }
  1522. nearExpiry := c.ExpiryTime > 0 && c.ExpiryTime-nowMs < expireDiffMs
  1523. nearLimit := c.TotalGB > 0 && c.TotalGB-used < trafficDiffBytes
  1524. if nearExpiry || nearLimit {
  1525. s.Expiring = append(s.Expiring, c.Email)
  1526. } else {
  1527. s.Active++
  1528. }
  1529. }
  1530. return s
  1531. }
  1532. func toClientSlim(c ClientWithAttachments) ClientSlim {
  1533. return ClientSlim{
  1534. Email: c.Email,
  1535. SubID: c.SubID,
  1536. Enable: c.Enable,
  1537. TotalGB: c.TotalGB,
  1538. ExpiryTime: c.ExpiryTime,
  1539. LimitIP: c.LimitIP,
  1540. Reset: c.Reset,
  1541. Group: c.Group,
  1542. Comment: c.Comment,
  1543. InboundIds: c.InboundIds,
  1544. Traffic: c.Traffic,
  1545. CreatedAt: c.CreatedAt,
  1546. UpdatedAt: c.UpdatedAt,
  1547. }
  1548. }
  1549. func clientMatchesSearch(c ClientWithAttachments, needle string) bool {
  1550. if needle == "" {
  1551. return true
  1552. }
  1553. candidates := [...]string{c.Email, c.SubID, c.Comment, c.UUID, c.Password, c.Auth}
  1554. for _, v := range candidates {
  1555. if v != "" && strings.Contains(strings.ToLower(v), needle) {
  1556. return true
  1557. }
  1558. }
  1559. return false
  1560. }
  1561. // parseCSVStrings splits a comma-separated list, trims/lower-cases each item,
  1562. // and drops blanks. Returns nil when the input has no usable entries — the
  1563. // caller can then skip the predicate entirely.
  1564. func parseCSVStrings(raw string) []string {
  1565. if raw == "" {
  1566. return nil
  1567. }
  1568. parts := strings.Split(raw, ",")
  1569. out := make([]string, 0, len(parts))
  1570. for _, p := range parts {
  1571. s := strings.ToLower(strings.TrimSpace(p))
  1572. if s != "" {
  1573. out = append(out, s)
  1574. }
  1575. }
  1576. if len(out) == 0 {
  1577. return nil
  1578. }
  1579. return out
  1580. }
  1581. // parseCSVInts is parseCSVStrings for positive integer IDs; non-numeric or
  1582. // non-positive entries are silently dropped.
  1583. func parseCSVInts(raw string) []int {
  1584. if raw == "" {
  1585. return nil
  1586. }
  1587. parts := strings.Split(raw, ",")
  1588. out := make([]int, 0, len(parts))
  1589. for _, p := range parts {
  1590. s := strings.TrimSpace(p)
  1591. if s == "" {
  1592. continue
  1593. }
  1594. if n, err := strconv.Atoi(s); err == nil && n > 0 {
  1595. out = append(out, n)
  1596. }
  1597. }
  1598. if len(out) == 0 {
  1599. return nil
  1600. }
  1601. return out
  1602. }
  1603. func clientMatchesAnyProtocol(c ClientWithAttachments, protocols []string, byInbound map[int]string) bool {
  1604. for _, id := range c.InboundIds {
  1605. p := byInbound[id]
  1606. if p == "" {
  1607. continue
  1608. }
  1609. if slices.Contains(protocols, strings.ToLower(p)) {
  1610. return true
  1611. }
  1612. }
  1613. return false
  1614. }
  1615. func clientMatchesAnyInbound(c ClientWithAttachments, inboundIds []int) bool {
  1616. for _, id := range c.InboundIds {
  1617. if slices.Contains(inboundIds, id) {
  1618. return true
  1619. }
  1620. }
  1621. return false
  1622. }
  1623. func clientMatchesAnyBucket(c ClientWithAttachments, buckets []string, onlineSet map[string]struct{}, nowMs, expireDiffMs, trafficDiffBytes int64) bool {
  1624. for _, b := range buckets {
  1625. if clientMatchesBucket(c, b, onlineSet, nowMs, expireDiffMs, trafficDiffBytes) {
  1626. return true
  1627. }
  1628. }
  1629. return false
  1630. }
  1631. func clientMatchesExpiryRange(c ClientWithAttachments, fromMs, toMs int64) bool {
  1632. if fromMs <= 0 && toMs <= 0 {
  1633. return true
  1634. }
  1635. // expiryTime of 0 means "never expires"; treat it as outside any bounded
  1636. // range so users filtering by date see only clients with concrete expiries.
  1637. if c.ExpiryTime == 0 {
  1638. return false
  1639. }
  1640. // Negative expiry is the "delayed start" sentinel; same treatment as never.
  1641. if c.ExpiryTime < 0 {
  1642. return false
  1643. }
  1644. if fromMs > 0 && c.ExpiryTime < fromMs {
  1645. return false
  1646. }
  1647. if toMs > 0 && c.ExpiryTime > toMs {
  1648. return false
  1649. }
  1650. return true
  1651. }
  1652. func clientMatchesUsageRange(c ClientWithAttachments, fromBytes, toBytes int64) bool {
  1653. if fromBytes <= 0 && toBytes <= 0 {
  1654. return true
  1655. }
  1656. used := int64(0)
  1657. if c.Traffic != nil {
  1658. used = c.Traffic.Up + c.Traffic.Down
  1659. }
  1660. if fromBytes > 0 && used < fromBytes {
  1661. return false
  1662. }
  1663. if toBytes > 0 && used > toBytes {
  1664. return false
  1665. }
  1666. return true
  1667. }
  1668. func clientMatchesAutoRenew(c ClientWithAttachments, mode string) bool {
  1669. switch strings.ToLower(strings.TrimSpace(mode)) {
  1670. case "on":
  1671. return c.Reset > 0
  1672. case "off":
  1673. return c.Reset <= 0
  1674. }
  1675. return true
  1676. }
  1677. func clientMatchesHasTgID(c ClientWithAttachments, mode string) bool {
  1678. switch strings.ToLower(strings.TrimSpace(mode)) {
  1679. case "yes":
  1680. return c.TgID != 0
  1681. case "no":
  1682. return c.TgID == 0
  1683. }
  1684. return true
  1685. }
  1686. func clientMatchesHasComment(c ClientWithAttachments, mode string) bool {
  1687. switch strings.ToLower(strings.TrimSpace(mode)) {
  1688. case "yes":
  1689. return strings.TrimSpace(c.Comment) != ""
  1690. case "no":
  1691. return strings.TrimSpace(c.Comment) == ""
  1692. }
  1693. return true
  1694. }
  1695. func clientMatchesAnyGroup(c ClientWithAttachments, csv string) bool {
  1696. groups := parseCSVStrings(csv)
  1697. if len(groups) == 0 {
  1698. return true
  1699. }
  1700. current := strings.TrimSpace(c.Group)
  1701. for _, g := range groups {
  1702. if g == "" {
  1703. if current == "" {
  1704. return true
  1705. }
  1706. continue
  1707. }
  1708. if strings.EqualFold(g, current) {
  1709. return true
  1710. }
  1711. }
  1712. return false
  1713. }
  1714. func clientMatchesBucket(c ClientWithAttachments, bucket string, onlineSet map[string]struct{}, nowMs, expireDiffMs, trafficDiffBytes int64) bool {
  1715. if bucket == "" {
  1716. return true
  1717. }
  1718. used := int64(0)
  1719. if c.Traffic != nil {
  1720. used = c.Traffic.Up + c.Traffic.Down
  1721. }
  1722. exhausted := c.TotalGB > 0 && used >= c.TotalGB
  1723. expired := c.ExpiryTime > 0 && c.ExpiryTime <= nowMs
  1724. switch bucket {
  1725. case "online":
  1726. if onlineSet == nil {
  1727. return false
  1728. }
  1729. _, ok := onlineSet[c.Email]
  1730. return ok && c.Enable
  1731. case "depleted":
  1732. return exhausted || expired
  1733. case "deactive":
  1734. return !c.Enable
  1735. case "active":
  1736. return c.Enable && !exhausted && !expired
  1737. case "expiring":
  1738. if !c.Enable || exhausted || expired {
  1739. return false
  1740. }
  1741. nearExpiry := c.ExpiryTime > 0 && c.ExpiryTime-nowMs < expireDiffMs
  1742. nearLimit := c.TotalGB > 0 && c.TotalGB-used < trafficDiffBytes
  1743. return nearExpiry || nearLimit
  1744. }
  1745. return true
  1746. }
  1747. func sortClients(rows []ClientWithAttachments, sortKey, order string) {
  1748. if sortKey == "" {
  1749. return
  1750. }
  1751. desc := order == "descend"
  1752. less := func(i, j int) bool {
  1753. a, b := rows[i], rows[j]
  1754. switch sortKey {
  1755. case "enable":
  1756. if a.Enable == b.Enable {
  1757. return false
  1758. }
  1759. return !a.Enable && b.Enable
  1760. case "email":
  1761. return strings.ToLower(a.Email) < strings.ToLower(b.Email)
  1762. case "inboundIds":
  1763. return len(a.InboundIds) < len(b.InboundIds)
  1764. case "traffic":
  1765. ua := int64(0)
  1766. if a.Traffic != nil {
  1767. ua = a.Traffic.Up + a.Traffic.Down
  1768. }
  1769. ub := int64(0)
  1770. if b.Traffic != nil {
  1771. ub = b.Traffic.Up + b.Traffic.Down
  1772. }
  1773. return ua < ub
  1774. case "remaining":
  1775. ra := int64(1<<62 - 1)
  1776. if a.TotalGB > 0 {
  1777. used := int64(0)
  1778. if a.Traffic != nil {
  1779. used = a.Traffic.Up + a.Traffic.Down
  1780. }
  1781. ra = a.TotalGB - used
  1782. }
  1783. rb := int64(1<<62 - 1)
  1784. if b.TotalGB > 0 {
  1785. used := int64(0)
  1786. if b.Traffic != nil {
  1787. used = b.Traffic.Up + b.Traffic.Down
  1788. }
  1789. rb = b.TotalGB - used
  1790. }
  1791. return ra < rb
  1792. case "expiryTime":
  1793. ea := int64(1<<62 - 1)
  1794. if a.ExpiryTime > 0 {
  1795. ea = a.ExpiryTime
  1796. }
  1797. eb := int64(1<<62 - 1)
  1798. if b.ExpiryTime > 0 {
  1799. eb = b.ExpiryTime
  1800. }
  1801. return ea < eb
  1802. case "createdAt":
  1803. if a.CreatedAt == b.CreatedAt {
  1804. return a.Id < b.Id
  1805. }
  1806. return a.CreatedAt < b.CreatedAt
  1807. case "updatedAt":
  1808. if a.UpdatedAt == b.UpdatedAt {
  1809. return a.Id < b.Id
  1810. }
  1811. return a.UpdatedAt < b.UpdatedAt
  1812. case "lastOnline":
  1813. la := int64(0)
  1814. if a.Traffic != nil {
  1815. la = a.Traffic.LastOnline
  1816. }
  1817. lb := int64(0)
  1818. if b.Traffic != nil {
  1819. lb = b.Traffic.LastOnline
  1820. }
  1821. if la == lb {
  1822. return a.Id < b.Id
  1823. }
  1824. return la < lb
  1825. }
  1826. return false
  1827. }
  1828. sort.SliceStable(rows, func(i, j int) bool {
  1829. if desc {
  1830. return less(j, i)
  1831. }
  1832. return less(i, j)
  1833. })
  1834. }
  1835. // BulkAdjustResult is returned by BulkAdjust to report how many clients were
  1836. // successfully updated and which were skipped (typically because the field
  1837. // being adjusted was unlimited for that client) or failed.
  1838. type BulkAdjustResult struct {
  1839. Adjusted int `json:"adjusted"`
  1840. Skipped []BulkAdjustReport `json:"skipped,omitempty"`
  1841. }
  1842. type BulkAdjustReport struct {
  1843. Email string `json:"email"`
  1844. Reason string `json:"reason"`
  1845. }
  1846. type bulkAdjustEntry struct {
  1847. record *model.ClientRecord
  1848. applyExpiry bool
  1849. newExpiry int64
  1850. applyTotal bool
  1851. newTotal int64
  1852. }
  1853. // BulkAdjust shifts ExpiryTime by addDays (days) and TotalGB by addBytes
  1854. // for every email in the list. Clients whose corresponding field is
  1855. // unlimited (0) are skipped — bulk extend should not accidentally
  1856. // limit an unlimited client. addDays and addBytes may be negative.
  1857. //
  1858. // Like BulkDelete, the work is grouped by inbound so each inbound's
  1859. // settings JSON is parsed and written exactly once regardless of how
  1860. // many target emails it contains.
  1861. func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string, addDays int, addBytes int64) (BulkAdjustResult, bool, error) {
  1862. result := BulkAdjustResult{}
  1863. if len(emails) == 0 {
  1864. return result, false, nil
  1865. }
  1866. if addDays == 0 && addBytes == 0 {
  1867. return result, false, common.NewError("no adjustment specified")
  1868. }
  1869. addExpiryMs := int64(addDays) * 24 * 60 * 60 * 1000
  1870. seen := map[string]struct{}{}
  1871. cleanEmails := make([]string, 0, len(emails))
  1872. for _, e := range emails {
  1873. e = strings.TrimSpace(e)
  1874. if e == "" {
  1875. continue
  1876. }
  1877. if _, ok := seen[e]; ok {
  1878. continue
  1879. }
  1880. seen[e] = struct{}{}
  1881. cleanEmails = append(cleanEmails, e)
  1882. }
  1883. if len(cleanEmails) == 0 {
  1884. return result, false, nil
  1885. }
  1886. db := database.GetDB()
  1887. var records []model.ClientRecord
  1888. if err := db.Where("email IN ?", cleanEmails).Find(&records).Error; err != nil {
  1889. return result, false, err
  1890. }
  1891. recordsByEmail := make(map[string]*model.ClientRecord, len(records))
  1892. for i := range records {
  1893. recordsByEmail[records[i].Email] = &records[i]
  1894. }
  1895. skippedReasons := map[string]string{}
  1896. for _, email := range cleanEmails {
  1897. if _, ok := recordsByEmail[email]; !ok {
  1898. skippedReasons[email] = "client not found"
  1899. }
  1900. }
  1901. plan := map[string]*bulkAdjustEntry{}
  1902. for email, rec := range recordsByEmail {
  1903. entry := &bulkAdjustEntry{record: rec}
  1904. if addDays != 0 {
  1905. switch {
  1906. case rec.ExpiryTime == 0:
  1907. if _, exists := skippedReasons[email]; !exists {
  1908. skippedReasons[email] = "unlimited expiry"
  1909. }
  1910. case rec.ExpiryTime > 0:
  1911. next := rec.ExpiryTime + addExpiryMs
  1912. if next <= 0 {
  1913. if _, exists := skippedReasons[email]; !exists {
  1914. skippedReasons[email] = "reduction exceeds remaining time"
  1915. }
  1916. } else {
  1917. entry.applyExpiry = true
  1918. entry.newExpiry = next
  1919. }
  1920. default:
  1921. next := rec.ExpiryTime - addExpiryMs
  1922. if next >= 0 {
  1923. if _, exists := skippedReasons[email]; !exists {
  1924. skippedReasons[email] = "reduction exceeds delay window"
  1925. }
  1926. } else {
  1927. entry.applyExpiry = true
  1928. entry.newExpiry = next
  1929. }
  1930. }
  1931. }
  1932. if addBytes != 0 {
  1933. if rec.TotalGB == 0 {
  1934. if _, exists := skippedReasons[email]; !exists {
  1935. skippedReasons[email] = "unlimited traffic"
  1936. }
  1937. } else {
  1938. next := max(rec.TotalGB+addBytes, 0)
  1939. entry.applyTotal = true
  1940. entry.newTotal = next
  1941. }
  1942. }
  1943. if entry.applyExpiry || entry.applyTotal {
  1944. plan[email] = entry
  1945. }
  1946. }
  1947. if len(plan) == 0 {
  1948. for email, reason := range skippedReasons {
  1949. result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: reason})
  1950. }
  1951. return result, false, nil
  1952. }
  1953. plannedIds := make([]int, 0, len(plan))
  1954. recordIdToEmail := make(map[int]string, len(plan))
  1955. for email, entry := range plan {
  1956. plannedIds = append(plannedIds, entry.record.Id)
  1957. recordIdToEmail[entry.record.Id] = email
  1958. }
  1959. var mappings []model.ClientInbound
  1960. if err := db.Where("client_id IN ?", plannedIds).Find(&mappings).Error; err != nil {
  1961. return result, false, err
  1962. }
  1963. emailsByInbound := map[int][]string{}
  1964. for _, m := range mappings {
  1965. email, ok := recordIdToEmail[m.ClientId]
  1966. if !ok {
  1967. continue
  1968. }
  1969. emailsByInbound[m.InboundId] = append(emailsByInbound[m.InboundId], email)
  1970. }
  1971. needRestart := false
  1972. for inboundId, ibEmails := range emailsByInbound {
  1973. ibRes := s.bulkAdjustInboundClients(inboundSvc, inboundId, ibEmails, plan)
  1974. if ibRes.needRestart {
  1975. needRestart = true
  1976. }
  1977. for email, reason := range ibRes.perEmailSkipped {
  1978. if _, already := skippedReasons[email]; !already {
  1979. skippedReasons[email] = reason
  1980. }
  1981. }
  1982. }
  1983. for email, entry := range plan {
  1984. if _, skipped := skippedReasons[email]; skipped {
  1985. continue
  1986. }
  1987. updates := map[string]any{}
  1988. if entry.applyExpiry {
  1989. updates["expiry_time"] = entry.newExpiry
  1990. }
  1991. if entry.applyTotal {
  1992. updates["total"] = entry.newTotal
  1993. }
  1994. if len(updates) == 0 {
  1995. continue
  1996. }
  1997. if err := db.Model(xray.ClientTraffic{}).Where("email = ?", email).Updates(updates).Error; err != nil {
  1998. if _, already := skippedReasons[email]; !already {
  1999. skippedReasons[email] = err.Error()
  2000. }
  2001. continue
  2002. }
  2003. result.Adjusted++
  2004. }
  2005. for email, reason := range skippedReasons {
  2006. result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: reason})
  2007. }
  2008. return result, needRestart, nil
  2009. }
  2010. type bulkInboundAdjustResult struct {
  2011. perEmailSkipped map[string]string
  2012. needRestart bool
  2013. }
  2014. // bulkAdjustInboundClients applies expiry/total deltas to multiple clients
  2015. // inside a single inbound's settings JSON. The xray runtime is updated
  2016. // only for remote-node inbounds; local nodes do not need a notification
  2017. // because the AddUser payload does not include totalGB/expiryTime —
  2018. // changing those fields is identity-preserving and the panel's traffic
  2019. // enforcement loop picks up the new limits from ClientTraffic directly.
  2020. func (s *ClientService) bulkAdjustInboundClients(
  2021. inboundSvc *InboundService,
  2022. inboundId int,
  2023. emails []string,
  2024. plan map[string]*bulkAdjustEntry,
  2025. ) bulkInboundAdjustResult {
  2026. res := bulkInboundAdjustResult{perEmailSkipped: map[string]string{}}
  2027. defer lockInbound(inboundId).Unlock()
  2028. oldInbound, err := inboundSvc.GetInbound(inboundId)
  2029. if err != nil {
  2030. logger.Error("Load Old Data Error")
  2031. for _, e := range emails {
  2032. res.perEmailSkipped[e] = err.Error()
  2033. }
  2034. return res
  2035. }
  2036. var settings map[string]any
  2037. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  2038. for _, e := range emails {
  2039. res.perEmailSkipped[e] = err.Error()
  2040. }
  2041. return res
  2042. }
  2043. clientKey := "id"
  2044. switch oldInbound.Protocol {
  2045. case model.Trojan:
  2046. clientKey = "password"
  2047. case model.Shadowsocks:
  2048. clientKey = "email"
  2049. case model.Hysteria:
  2050. clientKey = "auth"
  2051. }
  2052. keyToEmail := make(map[string]string, len(emails))
  2053. for _, email := range emails {
  2054. entry := plan[email]
  2055. if entry == nil {
  2056. res.perEmailSkipped[email] = "client not found"
  2057. continue
  2058. }
  2059. key := clientKeyForProtocol(oldInbound.Protocol, entry.record)
  2060. if key == "" {
  2061. res.perEmailSkipped[email] = "missing client key for protocol"
  2062. continue
  2063. }
  2064. keyToEmail[key] = email
  2065. }
  2066. interfaceClients, _ := settings["clients"].([]any)
  2067. foundEmails := map[string]bool{}
  2068. nowMs := time.Now().Unix() * 1000
  2069. for i, client := range interfaceClients {
  2070. c, ok := client.(map[string]any)
  2071. if !ok {
  2072. continue
  2073. }
  2074. cKey, _ := c[clientKey].(string)
  2075. targetEmail, found := keyToEmail[cKey]
  2076. if !found {
  2077. continue
  2078. }
  2079. entry := plan[targetEmail]
  2080. if entry.applyExpiry {
  2081. c["expiryTime"] = entry.newExpiry
  2082. }
  2083. if entry.applyTotal {
  2084. c["totalGB"] = entry.newTotal
  2085. }
  2086. c["updated_at"] = nowMs
  2087. interfaceClients[i] = c
  2088. foundEmails[targetEmail] = true
  2089. }
  2090. for _, email := range keyToEmail {
  2091. if !foundEmails[email] {
  2092. res.perEmailSkipped[email] = "Client Not Found In Inbound"
  2093. }
  2094. }
  2095. if len(foundEmails) == 0 {
  2096. return res
  2097. }
  2098. settings["clients"] = interfaceClients
  2099. newSettings, err := json.MarshalIndent(settings, "", " ")
  2100. if err != nil {
  2101. for email := range foundEmails {
  2102. res.perEmailSkipped[email] = err.Error()
  2103. }
  2104. return res
  2105. }
  2106. oldInbound.Settings = string(newSettings)
  2107. if oldInbound.NodeID != nil {
  2108. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  2109. if rterr != nil {
  2110. for email := range foundEmails {
  2111. res.perEmailSkipped[email] = rterr.Error()
  2112. delete(foundEmails, email)
  2113. }
  2114. } else {
  2115. for email := range foundEmails {
  2116. entry := plan[email]
  2117. updated := *entry.record.ToClient()
  2118. if entry.applyExpiry {
  2119. updated.ExpiryTime = entry.newExpiry
  2120. }
  2121. if entry.applyTotal {
  2122. updated.TotalGB = entry.newTotal
  2123. }
  2124. updated.UpdatedAt = nowMs
  2125. if err1 := rt.UpdateUser(context.Background(), oldInbound, email, updated); err1 != nil {
  2126. res.perEmailSkipped[email] = err1.Error()
  2127. delete(foundEmails, email)
  2128. }
  2129. }
  2130. }
  2131. }
  2132. db := database.GetDB()
  2133. if err := db.Save(oldInbound).Error; err != nil {
  2134. for email := range foundEmails {
  2135. if _, skip := res.perEmailSkipped[email]; !skip {
  2136. res.perEmailSkipped[email] = err.Error()
  2137. }
  2138. }
  2139. return res
  2140. }
  2141. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  2142. if gcErr == nil {
  2143. if syncErr := s.SyncInbound(db, inboundId, finalClients); syncErr != nil {
  2144. logger.Warning("bulkAdjust SyncInbound:", syncErr)
  2145. }
  2146. }
  2147. return res
  2148. }
  2149. // BulkDeleteResult mirrors BulkAdjustResult: total deleted plus per-email
  2150. // skip reasons when an email could not be processed.
  2151. type BulkDeleteResult struct {
  2152. Deleted int `json:"deleted"`
  2153. Skipped []BulkDeleteReport `json:"skipped,omitempty"`
  2154. }
  2155. type BulkDeleteReport struct {
  2156. Email string `json:"email"`
  2157. Reason string `json:"reason"`
  2158. }
  2159. // BulkDelete removes every client in the list in one optimized pass.
  2160. // Instead of running the full single-delete pipeline N times (which would
  2161. // re-read, re-parse, and re-write each inbound's settings JSON for every
  2162. // email), it groups emails by inbound and performs a single
  2163. // read-modify-write per inbound. Per-row DB cleanups are also batched with
  2164. // IN-clause queries at the end. Errors on a particular email are recorded
  2165. // in the Skipped list and processing continues for the rest.
  2166. func (s *ClientService) BulkDelete(inboundSvc *InboundService, emails []string, keepTraffic bool) (BulkDeleteResult, bool, error) {
  2167. result := BulkDeleteResult{}
  2168. seen := map[string]struct{}{}
  2169. cleanEmails := make([]string, 0, len(emails))
  2170. for _, e := range emails {
  2171. e = strings.TrimSpace(e)
  2172. if e == "" {
  2173. continue
  2174. }
  2175. if _, ok := seen[e]; ok {
  2176. continue
  2177. }
  2178. seen[e] = struct{}{}
  2179. cleanEmails = append(cleanEmails, e)
  2180. }
  2181. if len(cleanEmails) == 0 {
  2182. return result, false, nil
  2183. }
  2184. db := database.GetDB()
  2185. var records []model.ClientRecord
  2186. if err := db.Where("email IN ?", cleanEmails).Find(&records).Error; err != nil {
  2187. return result, false, err
  2188. }
  2189. recordsByEmail := make(map[string]*model.ClientRecord, len(records))
  2190. for i := range records {
  2191. recordsByEmail[records[i].Email] = &records[i]
  2192. tombstoneClientEmail(records[i].Email)
  2193. }
  2194. skippedReasons := map[string]string{}
  2195. for _, email := range cleanEmails {
  2196. if _, ok := recordsByEmail[email]; !ok {
  2197. skippedReasons[email] = "client not found"
  2198. }
  2199. }
  2200. clientIds := make([]int, 0, len(recordsByEmail))
  2201. recordIdToEmail := make(map[int]string, len(recordsByEmail))
  2202. for _, r := range recordsByEmail {
  2203. clientIds = append(clientIds, r.Id)
  2204. recordIdToEmail[r.Id] = r.Email
  2205. }
  2206. emailsByInbound := map[int][]string{}
  2207. if len(clientIds) > 0 {
  2208. var mappings []model.ClientInbound
  2209. if err := db.Where("client_id IN ?", clientIds).Find(&mappings).Error; err != nil {
  2210. return result, false, err
  2211. }
  2212. for _, m := range mappings {
  2213. email, ok := recordIdToEmail[m.ClientId]
  2214. if !ok {
  2215. continue
  2216. }
  2217. emailsByInbound[m.InboundId] = append(emailsByInbound[m.InboundId], email)
  2218. }
  2219. }
  2220. needRestart := false
  2221. for inboundId, ibEmails := range emailsByInbound {
  2222. ibResult := s.bulkDelInboundClients(inboundSvc, inboundId, ibEmails, recordsByEmail)
  2223. if ibResult.needRestart {
  2224. needRestart = true
  2225. }
  2226. for email, reason := range ibResult.perEmailSkipped {
  2227. if _, already := skippedReasons[email]; !already {
  2228. skippedReasons[email] = reason
  2229. }
  2230. }
  2231. }
  2232. successEmails := make([]string, 0, len(recordsByEmail))
  2233. successIds := make([]int, 0, len(recordsByEmail))
  2234. for email, rec := range recordsByEmail {
  2235. if _, skipped := skippedReasons[email]; skipped {
  2236. continue
  2237. }
  2238. successEmails = append(successEmails, email)
  2239. successIds = append(successIds, rec.Id)
  2240. }
  2241. if len(successIds) > 0 {
  2242. if err := db.Where("client_id IN ?", successIds).Delete(&model.ClientInbound{}).Error; err != nil {
  2243. return result, needRestart, err
  2244. }
  2245. if !keepTraffic && len(successEmails) > 0 {
  2246. if err := db.Where("email IN ?", successEmails).Delete(&xray.ClientTraffic{}).Error; err != nil {
  2247. return result, needRestart, err
  2248. }
  2249. if err := db.Where("client_email IN ?", successEmails).Delete(&model.InboundClientIps{}).Error; err != nil {
  2250. return result, needRestart, err
  2251. }
  2252. }
  2253. if err := db.Where("id IN ?", successIds).Delete(&model.ClientRecord{}).Error; err != nil {
  2254. return result, needRestart, err
  2255. }
  2256. }
  2257. result.Deleted = len(successEmails)
  2258. for email, reason := range skippedReasons {
  2259. result.Skipped = append(result.Skipped, BulkDeleteReport{Email: email, Reason: reason})
  2260. }
  2261. return result, needRestart, nil
  2262. }
  2263. type bulkInboundDeleteResult struct {
  2264. perEmailSkipped map[string]string
  2265. needRestart bool
  2266. }
  2267. // bulkDelInboundClients removes multiple clients from a single inbound's
  2268. // settings JSON in one read-modify-write cycle, runs the xray runtime
  2269. // RemoveUser/DeleteUser calls, and persists the inbound. The returned map
  2270. // holds per-email failure reasons; emails not present in the map are
  2271. // considered successful for this inbound.
  2272. func (s *ClientService) bulkDelInboundClients(
  2273. inboundSvc *InboundService,
  2274. inboundId int,
  2275. emails []string,
  2276. records map[string]*model.ClientRecord,
  2277. ) bulkInboundDeleteResult {
  2278. res := bulkInboundDeleteResult{perEmailSkipped: map[string]string{}}
  2279. defer lockInbound(inboundId).Unlock()
  2280. oldInbound, err := inboundSvc.GetInbound(inboundId)
  2281. if err != nil {
  2282. logger.Error("Load Old Data Error")
  2283. for _, e := range emails {
  2284. res.perEmailSkipped[e] = err.Error()
  2285. }
  2286. return res
  2287. }
  2288. var settings map[string]any
  2289. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  2290. for _, e := range emails {
  2291. res.perEmailSkipped[e] = err.Error()
  2292. }
  2293. return res
  2294. }
  2295. clientKey := "id"
  2296. switch oldInbound.Protocol {
  2297. case model.Trojan:
  2298. clientKey = "password"
  2299. case model.Shadowsocks:
  2300. clientKey = "email"
  2301. case model.Hysteria:
  2302. clientKey = "auth"
  2303. }
  2304. keyToEmail := make(map[string]string, len(emails))
  2305. for _, email := range emails {
  2306. rec := records[email]
  2307. if rec == nil {
  2308. res.perEmailSkipped[email] = "client not found"
  2309. continue
  2310. }
  2311. key := clientKeyForProtocol(oldInbound.Protocol, rec)
  2312. if key == "" {
  2313. res.perEmailSkipped[email] = "missing client key for protocol"
  2314. continue
  2315. }
  2316. keyToEmail[key] = email
  2317. }
  2318. interfaceClients, _ := settings["clients"].([]any)
  2319. newClients := make([]any, 0, len(interfaceClients))
  2320. foundEmails := map[string]bool{}
  2321. enableByEmail := map[string]bool{}
  2322. for _, client := range interfaceClients {
  2323. c, ok := client.(map[string]any)
  2324. if !ok {
  2325. newClients = append(newClients, client)
  2326. continue
  2327. }
  2328. cKey, _ := c[clientKey].(string)
  2329. if targetEmail, found := keyToEmail[cKey]; found {
  2330. foundEmails[targetEmail] = true
  2331. if em, _ := c["email"].(string); em != "" {
  2332. en, _ := c["enable"].(bool)
  2333. enableByEmail[em] = en
  2334. }
  2335. continue
  2336. }
  2337. newClients = append(newClients, client)
  2338. }
  2339. for _, email := range keyToEmail {
  2340. if !foundEmails[email] {
  2341. res.perEmailSkipped[email] = "Client Not Found In Inbound"
  2342. }
  2343. }
  2344. db := database.GetDB()
  2345. newClients = compactOrphans(db, newClients)
  2346. if newClients == nil {
  2347. newClients = []any{}
  2348. }
  2349. settings["clients"] = newClients
  2350. newSettings, err := json.MarshalIndent(settings, "", " ")
  2351. if err != nil {
  2352. for email := range foundEmails {
  2353. if _, skip := res.perEmailSkipped[email]; !skip {
  2354. res.perEmailSkipped[email] = err.Error()
  2355. }
  2356. }
  2357. return res
  2358. }
  2359. oldInbound.Settings = string(newSettings)
  2360. foundList := make([]string, 0, len(foundEmails))
  2361. for email := range foundEmails {
  2362. foundList = append(foundList, email)
  2363. }
  2364. notDepletedByEmail := map[string]bool{}
  2365. if len(foundList) > 0 {
  2366. type trafficRow struct {
  2367. Email string
  2368. Enable bool
  2369. }
  2370. var rows []trafficRow
  2371. if err := db.Model(xray.ClientTraffic{}).
  2372. Where("email IN ?", foundList).
  2373. Select("email, enable").
  2374. Scan(&rows).Error; err == nil {
  2375. for _, r := range rows {
  2376. notDepletedByEmail[r.Email] = r.Enable
  2377. }
  2378. }
  2379. }
  2380. for email := range foundEmails {
  2381. shared, sharedErr := inboundSvc.emailUsedByOtherInbounds(email, inboundId)
  2382. if sharedErr != nil {
  2383. res.perEmailSkipped[email] = sharedErr.Error()
  2384. delete(foundEmails, email)
  2385. continue
  2386. }
  2387. if shared {
  2388. continue
  2389. }
  2390. if delErr := inboundSvc.DelClientIPs(db, email); delErr != nil {
  2391. logger.Error("Error in delete client IPs")
  2392. res.perEmailSkipped[email] = delErr.Error()
  2393. delete(foundEmails, email)
  2394. continue
  2395. }
  2396. if delErr := inboundSvc.DelClientStat(db, email); delErr != nil {
  2397. logger.Error("Delete stats Data Error")
  2398. res.perEmailSkipped[email] = delErr.Error()
  2399. delete(foundEmails, email)
  2400. continue
  2401. }
  2402. }
  2403. if oldInbound.NodeID == nil {
  2404. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  2405. if rterr != nil {
  2406. res.needRestart = true
  2407. } else {
  2408. for email := range foundEmails {
  2409. if !enableByEmail[email] || !notDepletedByEmail[email] {
  2410. continue
  2411. }
  2412. err1 := rt.RemoveUser(context.Background(), oldInbound, email)
  2413. if err1 == nil {
  2414. logger.Debug("Client deleted on", rt.Name(), ":", email)
  2415. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  2416. logger.Debug("User is already deleted. Nothing to do more...")
  2417. } else {
  2418. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  2419. res.needRestart = true
  2420. }
  2421. }
  2422. }
  2423. } else {
  2424. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  2425. if rterr != nil {
  2426. for email := range foundEmails {
  2427. res.perEmailSkipped[email] = rterr.Error()
  2428. delete(foundEmails, email)
  2429. }
  2430. } else {
  2431. for email := range foundEmails {
  2432. if err1 := rt.DeleteUser(context.Background(), oldInbound, email); err1 != nil {
  2433. res.perEmailSkipped[email] = err1.Error()
  2434. delete(foundEmails, email)
  2435. }
  2436. }
  2437. }
  2438. }
  2439. if err := db.Save(oldInbound).Error; err != nil {
  2440. for email := range foundEmails {
  2441. if _, skip := res.perEmailSkipped[email]; !skip {
  2442. res.perEmailSkipped[email] = err.Error()
  2443. }
  2444. }
  2445. return res
  2446. }
  2447. finalClients, err := inboundSvc.GetClients(oldInbound)
  2448. if err != nil {
  2449. return res
  2450. }
  2451. if err := s.SyncInbound(db, inboundId, finalClients); err != nil {
  2452. return res
  2453. }
  2454. return res
  2455. }
  2456. // BulkCreateResult mirrors BulkAdjustResult for the create flow.
  2457. type BulkCreateResult struct {
  2458. Created int `json:"created"`
  2459. Skipped []BulkCreateReport `json:"skipped,omitempty"`
  2460. }
  2461. type BulkCreateReport struct {
  2462. Email string `json:"email"`
  2463. Reason string `json:"reason"`
  2464. }
  2465. // BulkCreate iterates payloads sequentially. Each item is the same shape
  2466. // the single-create endpoint accepts, so callers can submit a heterogeneous
  2467. // list (different inboundIds, plans, etc.) in one round-trip.
  2468. func (s *ClientService) BulkCreate(inboundSvc *InboundService, payloads []ClientCreatePayload) (BulkCreateResult, bool, error) {
  2469. result := BulkCreateResult{}
  2470. needRestart := false
  2471. for i := range payloads {
  2472. p := payloads[i]
  2473. email := strings.TrimSpace(p.Client.Email)
  2474. nr, err := s.Create(inboundSvc, &p)
  2475. if err != nil {
  2476. if email == "" {
  2477. email = "(missing email)"
  2478. }
  2479. result.Skipped = append(result.Skipped, BulkCreateReport{Email: email, Reason: err.Error()})
  2480. continue
  2481. }
  2482. if nr {
  2483. needRestart = true
  2484. }
  2485. result.Created++
  2486. }
  2487. return result, needRestart, nil
  2488. }
  2489. func (s *ClientService) DelDepleted(inboundSvc *InboundService) (int, bool, error) {
  2490. db := database.GetDB()
  2491. now := time.Now().UnixMilli()
  2492. depletedClause := "reset = 0 and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))"
  2493. var rows []xray.ClientTraffic
  2494. if err := db.Where(depletedClause, now).Find(&rows).Error; err != nil {
  2495. return 0, false, err
  2496. }
  2497. if len(rows) == 0 {
  2498. return 0, false, nil
  2499. }
  2500. emails := make(map[string]struct{}, len(rows))
  2501. for _, r := range rows {
  2502. if r.Email != "" {
  2503. emails[r.Email] = struct{}{}
  2504. }
  2505. }
  2506. needRestart := false
  2507. deleted := 0
  2508. for email := range emails {
  2509. var rec model.ClientRecord
  2510. if err := db.Where("email = ?", email).First(&rec).Error; err != nil {
  2511. if errors.Is(err, gorm.ErrRecordNotFound) {
  2512. continue
  2513. }
  2514. return deleted, needRestart, err
  2515. }
  2516. nr, err := s.Delete(inboundSvc, rec.Id, false)
  2517. if err != nil {
  2518. return deleted, needRestart, err
  2519. }
  2520. if nr {
  2521. needRestart = true
  2522. }
  2523. deleted++
  2524. }
  2525. return deleted, needRestart, nil
  2526. }
  2527. func (s *ClientService) ResetAllClientTraffics(inboundSvc *InboundService, id int) error {
  2528. return submitTrafficWrite(func() error {
  2529. return s.resetAllClientTrafficsLocked(id)
  2530. })
  2531. }
  2532. func (s *ClientService) resetAllClientTrafficsLocked(id int) error {
  2533. db := database.GetDB()
  2534. now := time.Now().Unix() * 1000
  2535. if err := db.Transaction(func(tx *gorm.DB) error {
  2536. whereText := "inbound_id "
  2537. if id == -1 {
  2538. whereText += " > ?"
  2539. } else {
  2540. whereText += " = ?"
  2541. }
  2542. result := tx.Model(xray.ClientTraffic{}).
  2543. Where(whereText, id).
  2544. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  2545. if result.Error != nil {
  2546. return result.Error
  2547. }
  2548. inboundWhereText := "id "
  2549. if id == -1 {
  2550. inboundWhereText += " > ?"
  2551. } else {
  2552. inboundWhereText += " = ?"
  2553. }
  2554. result = tx.Model(model.Inbound{}).
  2555. Where(inboundWhereText, id).
  2556. Update("last_traffic_reset_time", now)
  2557. return result.Error
  2558. }); err != nil {
  2559. return err
  2560. }
  2561. return nil
  2562. }
  2563. func (s *ClientService) ResetAllTraffics() (bool, error) {
  2564. res := database.GetDB().Model(&xray.ClientTraffic{}).
  2565. Where("1 = 1").
  2566. Updates(map[string]any{"up": 0, "down": 0})
  2567. if res.Error != nil {
  2568. return false, res.Error
  2569. }
  2570. return res.RowsAffected > 0, nil
  2571. }
  2572. func (s *ClientService) Detach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  2573. existing, err := s.GetByID(id)
  2574. if err != nil {
  2575. return false, err
  2576. }
  2577. currentIds, err := s.GetInboundIdsForRecord(id)
  2578. if err != nil {
  2579. return false, err
  2580. }
  2581. have := make(map[int]struct{}, len(currentIds))
  2582. for _, x := range currentIds {
  2583. have[x] = struct{}{}
  2584. }
  2585. needRestart := false
  2586. for _, ibId := range inboundIds {
  2587. if _, attached := have[ibId]; !attached {
  2588. continue
  2589. }
  2590. inbound, getErr := inboundSvc.GetInbound(ibId)
  2591. if getErr != nil {
  2592. return needRestart, getErr
  2593. }
  2594. key := clientKeyForProtocol(inbound.Protocol, existing)
  2595. if key == "" {
  2596. continue
  2597. }
  2598. nr, delErr := s.DelInboundClient(inboundSvc, ibId, key)
  2599. if delErr != nil {
  2600. return needRestart, delErr
  2601. }
  2602. if nr {
  2603. needRestart = true
  2604. }
  2605. }
  2606. return needRestart, nil
  2607. }
  2608. func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, clients []model.Client) (string, error) {
  2609. emailSubIDs, err := inboundSvc.getAllEmailSubIDs()
  2610. if err != nil {
  2611. return "", err
  2612. }
  2613. seen := make(map[string]string, len(clients))
  2614. for _, client := range clients {
  2615. if client.Email == "" {
  2616. continue
  2617. }
  2618. key := strings.ToLower(client.Email)
  2619. if prev, ok := seen[key]; ok {
  2620. if prev != client.SubID || client.SubID == "" {
  2621. return client.Email, nil
  2622. }
  2623. continue
  2624. }
  2625. seen[key] = client.SubID
  2626. if existingSub, ok := emailSubIDs[key]; ok {
  2627. if client.SubID == "" || existingSub == "" || existingSub != client.SubID {
  2628. return client.Email, nil
  2629. }
  2630. }
  2631. }
  2632. return "", nil
  2633. }
  2634. func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (bool, error) {
  2635. defer lockInbound(data.Id).Unlock()
  2636. clients, err := inboundSvc.GetClients(data)
  2637. if err != nil {
  2638. return false, err
  2639. }
  2640. var settings map[string]any
  2641. err = json.Unmarshal([]byte(data.Settings), &settings)
  2642. if err != nil {
  2643. return false, err
  2644. }
  2645. interfaceClients := settings["clients"].([]any)
  2646. nowTs := time.Now().Unix() * 1000
  2647. for i := range interfaceClients {
  2648. if cm, ok := interfaceClients[i].(map[string]any); ok {
  2649. if _, ok2 := cm["created_at"]; !ok2 {
  2650. cm["created_at"] = nowTs
  2651. }
  2652. cm["updated_at"] = nowTs
  2653. interfaceClients[i] = cm
  2654. }
  2655. }
  2656. existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients)
  2657. if err != nil {
  2658. return false, err
  2659. }
  2660. if existEmail != "" {
  2661. return false, common.NewError("Duplicate email:", existEmail)
  2662. }
  2663. oldInbound, err := inboundSvc.GetInbound(data.Id)
  2664. if err != nil {
  2665. return false, err
  2666. }
  2667. for _, client := range clients {
  2668. if strings.TrimSpace(client.Email) == "" {
  2669. return false, common.NewError("client email is required")
  2670. }
  2671. switch oldInbound.Protocol {
  2672. case "trojan":
  2673. if client.Password == "" {
  2674. return false, common.NewError("empty client ID")
  2675. }
  2676. case "shadowsocks":
  2677. if client.Email == "" {
  2678. return false, common.NewError("empty client ID")
  2679. }
  2680. case "hysteria":
  2681. if client.Auth == "" {
  2682. return false, common.NewError("empty client ID")
  2683. }
  2684. default:
  2685. if client.ID == "" {
  2686. return false, common.NewError("empty client ID")
  2687. }
  2688. }
  2689. }
  2690. var oldSettings map[string]any
  2691. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  2692. if err != nil {
  2693. return false, err
  2694. }
  2695. if oldInbound.Protocol == model.Shadowsocks {
  2696. applyShadowsocksClientMethod(interfaceClients, oldSettings)
  2697. }
  2698. oldClients := oldSettings["clients"].([]any)
  2699. oldClients = compactOrphans(database.GetDB(), oldClients)
  2700. oldClients = append(oldClients, interfaceClients...)
  2701. oldSettings["clients"] = oldClients
  2702. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  2703. if err != nil {
  2704. return false, err
  2705. }
  2706. oldInbound.Settings = string(newSettings)
  2707. db := database.GetDB()
  2708. tx := db.Begin()
  2709. defer func() {
  2710. if err != nil {
  2711. tx.Rollback()
  2712. } else {
  2713. tx.Commit()
  2714. }
  2715. }()
  2716. needRestart := false
  2717. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  2718. if rterr != nil {
  2719. if oldInbound.NodeID != nil {
  2720. err = rterr
  2721. return false, err
  2722. }
  2723. needRestart = true
  2724. } else if oldInbound.NodeID == nil {
  2725. for _, client := range clients {
  2726. if len(client.Email) == 0 {
  2727. needRestart = true
  2728. continue
  2729. }
  2730. inboundSvc.AddClientStat(tx, data.Id, &client)
  2731. if !client.Enable {
  2732. continue
  2733. }
  2734. cipher := ""
  2735. if oldInbound.Protocol == "shadowsocks" {
  2736. cipher = oldSettings["method"].(string)
  2737. }
  2738. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  2739. "email": client.Email,
  2740. "id": client.ID,
  2741. "auth": client.Auth,
  2742. "security": client.Security,
  2743. "flow": client.Flow,
  2744. "password": client.Password,
  2745. "cipher": cipher,
  2746. })
  2747. if err1 == nil {
  2748. logger.Debug("Client added on", rt.Name(), ":", client.Email)
  2749. } else {
  2750. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  2751. needRestart = true
  2752. }
  2753. }
  2754. } else {
  2755. for _, client := range clients {
  2756. if len(client.Email) > 0 {
  2757. inboundSvc.AddClientStat(tx, data.Id, &client)
  2758. }
  2759. if err1 := rt.AddClient(context.Background(), oldInbound, client); err1 != nil {
  2760. err = err1
  2761. return false, err
  2762. }
  2763. }
  2764. }
  2765. if err = tx.Save(oldInbound).Error; err != nil {
  2766. return false, err
  2767. }
  2768. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  2769. if gcErr != nil {
  2770. err = gcErr
  2771. return false, err
  2772. }
  2773. if err = s.SyncInbound(tx, oldInbound.Id, finalClients); err != nil {
  2774. return false, err
  2775. }
  2776. return needRestart, nil
  2777. }
  2778. func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *model.Inbound, clientId string) (bool, error) {
  2779. defer lockInbound(data.Id).Unlock()
  2780. clients, err := inboundSvc.GetClients(data)
  2781. if err != nil {
  2782. return false, err
  2783. }
  2784. var settings map[string]any
  2785. err = json.Unmarshal([]byte(data.Settings), &settings)
  2786. if err != nil {
  2787. return false, err
  2788. }
  2789. interfaceClients := settings["clients"].([]any)
  2790. oldInbound, err := inboundSvc.GetInbound(data.Id)
  2791. if err != nil {
  2792. return false, err
  2793. }
  2794. oldClients, err := inboundSvc.GetClients(oldInbound)
  2795. if err != nil {
  2796. return false, err
  2797. }
  2798. oldEmail := ""
  2799. newClientId := ""
  2800. clientIndex := -1
  2801. for index, oldClient := range oldClients {
  2802. oldClientId := ""
  2803. switch oldInbound.Protocol {
  2804. case "trojan":
  2805. oldClientId = oldClient.Password
  2806. newClientId = clients[0].Password
  2807. case "shadowsocks":
  2808. oldClientId = oldClient.Email
  2809. newClientId = clients[0].Email
  2810. case "hysteria":
  2811. oldClientId = oldClient.Auth
  2812. newClientId = clients[0].Auth
  2813. default:
  2814. oldClientId = oldClient.ID
  2815. newClientId = clients[0].ID
  2816. }
  2817. if clientId == oldClientId {
  2818. oldEmail = oldClient.Email
  2819. clientIndex = index
  2820. break
  2821. }
  2822. }
  2823. if clientIndex == -1 {
  2824. var rec model.ClientRecord
  2825. var lookupErr error
  2826. switch oldInbound.Protocol {
  2827. case "trojan":
  2828. lookupErr = database.GetDB().Where("password = ?", clientId).First(&rec).Error
  2829. case "shadowsocks":
  2830. lookupErr = database.GetDB().Where("email = ?", clientId).First(&rec).Error
  2831. case "hysteria":
  2832. lookupErr = database.GetDB().Where("auth = ?", clientId).First(&rec).Error
  2833. default:
  2834. lookupErr = database.GetDB().Where("uuid = ?", clientId).First(&rec).Error
  2835. }
  2836. if lookupErr == nil && rec.Email != "" {
  2837. for index, oldClient := range oldClients {
  2838. if oldClient.Email == rec.Email {
  2839. oldEmail = oldClient.Email
  2840. clientIndex = index
  2841. break
  2842. }
  2843. }
  2844. }
  2845. }
  2846. if newClientId == "" || clientIndex == -1 {
  2847. return false, common.NewError("empty client ID")
  2848. }
  2849. if strings.TrimSpace(clients[0].Email) == "" {
  2850. return false, common.NewError("client email is required")
  2851. }
  2852. if clients[0].Email != oldEmail {
  2853. existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients)
  2854. if err != nil {
  2855. return false, err
  2856. }
  2857. if existEmail != "" {
  2858. return false, common.NewError("Duplicate email:", existEmail)
  2859. }
  2860. }
  2861. var oldSettings map[string]any
  2862. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  2863. if err != nil {
  2864. return false, err
  2865. }
  2866. settingsClients := oldSettings["clients"].([]any)
  2867. var preservedCreated any
  2868. if clientIndex >= 0 && clientIndex < len(settingsClients) {
  2869. if oldMap, ok := settingsClients[clientIndex].(map[string]any); ok {
  2870. if v, ok2 := oldMap["created_at"]; ok2 {
  2871. preservedCreated = v
  2872. }
  2873. }
  2874. }
  2875. if len(interfaceClients) > 0 {
  2876. if newMap, ok := interfaceClients[0].(map[string]any); ok {
  2877. if preservedCreated == nil {
  2878. preservedCreated = time.Now().Unix() * 1000
  2879. }
  2880. newMap["created_at"] = preservedCreated
  2881. newMap["updated_at"] = time.Now().Unix() * 1000
  2882. interfaceClients[0] = newMap
  2883. }
  2884. }
  2885. if oldInbound.Protocol == model.Shadowsocks {
  2886. applyShadowsocksClientMethod(interfaceClients, oldSettings)
  2887. }
  2888. settingsClients[clientIndex] = interfaceClients[0]
  2889. oldSettings["clients"] = settingsClients
  2890. if oldInbound.Protocol == model.VLESS {
  2891. hasVisionFlow := false
  2892. for _, c := range settingsClients {
  2893. cm, ok := c.(map[string]any)
  2894. if !ok {
  2895. continue
  2896. }
  2897. if flow, _ := cm["flow"].(string); flow == "xtls-rprx-vision" {
  2898. hasVisionFlow = true
  2899. break
  2900. }
  2901. }
  2902. if !hasVisionFlow {
  2903. delete(oldSettings, "testseed")
  2904. }
  2905. }
  2906. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  2907. if err != nil {
  2908. return false, err
  2909. }
  2910. oldInbound.Settings = string(newSettings)
  2911. db := database.GetDB()
  2912. tx := db.Begin()
  2913. defer func() {
  2914. if err != nil {
  2915. tx.Rollback()
  2916. } else {
  2917. tx.Commit()
  2918. }
  2919. }()
  2920. if len(clients[0].Email) > 0 {
  2921. if len(oldEmail) > 0 {
  2922. emailUnchanged := strings.EqualFold(oldEmail, clients[0].Email)
  2923. targetExists := int64(0)
  2924. if !emailUnchanged {
  2925. if err = tx.Model(xray.ClientTraffic{}).Where("email = ?", clients[0].Email).Count(&targetExists).Error; err != nil {
  2926. return false, err
  2927. }
  2928. }
  2929. if emailUnchanged || targetExists == 0 {
  2930. err = inboundSvc.UpdateClientStat(tx, oldEmail, &clients[0])
  2931. if err != nil {
  2932. return false, err
  2933. }
  2934. err = inboundSvc.UpdateClientIPs(tx, oldEmail, clients[0].Email)
  2935. if err != nil {
  2936. return false, err
  2937. }
  2938. } else {
  2939. stillUsed, sErr := inboundSvc.emailUsedByOtherInbounds(oldEmail, data.Id)
  2940. if sErr != nil {
  2941. return false, sErr
  2942. }
  2943. if !stillUsed {
  2944. if err = inboundSvc.DelClientStat(tx, oldEmail); err != nil {
  2945. return false, err
  2946. }
  2947. if err = inboundSvc.DelClientIPs(tx, oldEmail); err != nil {
  2948. return false, err
  2949. }
  2950. }
  2951. if err = inboundSvc.UpdateClientStat(tx, clients[0].Email, &clients[0]); err != nil {
  2952. return false, err
  2953. }
  2954. }
  2955. } else {
  2956. inboundSvc.AddClientStat(tx, data.Id, &clients[0])
  2957. }
  2958. } else {
  2959. stillUsed, err := inboundSvc.emailUsedByOtherInbounds(oldEmail, data.Id)
  2960. if err != nil {
  2961. return false, err
  2962. }
  2963. if !stillUsed {
  2964. err = inboundSvc.DelClientStat(tx, oldEmail)
  2965. if err != nil {
  2966. return false, err
  2967. }
  2968. err = inboundSvc.DelClientIPs(tx, oldEmail)
  2969. if err != nil {
  2970. return false, err
  2971. }
  2972. }
  2973. }
  2974. needRestart := false
  2975. if len(oldEmail) > 0 {
  2976. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  2977. if rterr != nil {
  2978. if oldInbound.NodeID != nil {
  2979. err = rterr
  2980. return false, err
  2981. }
  2982. needRestart = true
  2983. } else if oldInbound.NodeID == nil {
  2984. if oldClients[clientIndex].Enable {
  2985. err1 := rt.RemoveUser(context.Background(), oldInbound, oldEmail)
  2986. if err1 == nil {
  2987. logger.Debug("Old client deleted on", rt.Name(), ":", oldEmail)
  2988. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", oldEmail)) {
  2989. logger.Debug("User is already deleted. Nothing to do more...")
  2990. } else {
  2991. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  2992. needRestart = true
  2993. }
  2994. }
  2995. if clients[0].Enable {
  2996. cipher := ""
  2997. if oldInbound.Protocol == "shadowsocks" {
  2998. cipher = oldSettings["method"].(string)
  2999. }
  3000. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  3001. "email": clients[0].Email,
  3002. "id": clients[0].ID,
  3003. "security": clients[0].Security,
  3004. "flow": clients[0].Flow,
  3005. "auth": clients[0].Auth,
  3006. "password": clients[0].Password,
  3007. "cipher": cipher,
  3008. })
  3009. if err1 == nil {
  3010. logger.Debug("Client edited on", rt.Name(), ":", clients[0].Email)
  3011. } else {
  3012. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  3013. needRestart = true
  3014. }
  3015. }
  3016. } else {
  3017. if err1 := rt.UpdateUser(context.Background(), oldInbound, oldEmail, clients[0]); err1 != nil {
  3018. err = err1
  3019. return false, err
  3020. }
  3021. }
  3022. } else {
  3023. logger.Debug("Client old email not found")
  3024. needRestart = true
  3025. }
  3026. if err = tx.Save(oldInbound).Error; err != nil {
  3027. return false, err
  3028. }
  3029. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  3030. if gcErr != nil {
  3031. err = gcErr
  3032. return false, err
  3033. }
  3034. if err = s.SyncInbound(tx, oldInbound.Id, finalClients); err != nil {
  3035. return false, err
  3036. }
  3037. return needRestart, nil
  3038. }
  3039. func (s *ClientService) DelInboundClient(inboundSvc *InboundService, inboundId int, clientId string) (bool, error) {
  3040. defer lockInbound(inboundId).Unlock()
  3041. oldInbound, err := inboundSvc.GetInbound(inboundId)
  3042. if err != nil {
  3043. logger.Error("Load Old Data Error")
  3044. return false, err
  3045. }
  3046. var settings map[string]any
  3047. err = json.Unmarshal([]byte(oldInbound.Settings), &settings)
  3048. if err != nil {
  3049. return false, err
  3050. }
  3051. email := ""
  3052. client_key := "id"
  3053. switch oldInbound.Protocol {
  3054. case "trojan":
  3055. client_key = "password"
  3056. case "shadowsocks":
  3057. client_key = "email"
  3058. case "hysteria":
  3059. client_key = "auth"
  3060. }
  3061. interfaceClients := settings["clients"].([]any)
  3062. var newClients []any
  3063. needApiDel := false
  3064. clientFound := false
  3065. for _, client := range interfaceClients {
  3066. c := client.(map[string]any)
  3067. c_id := c[client_key].(string)
  3068. if c_id == clientId {
  3069. clientFound = true
  3070. email, _ = c["email"].(string)
  3071. needApiDel, _ = c["enable"].(bool)
  3072. } else {
  3073. newClients = append(newClients, client)
  3074. }
  3075. }
  3076. if !clientFound {
  3077. return false, common.NewError("Client Not Found In Inbound For ID:", clientId)
  3078. }
  3079. db := database.GetDB()
  3080. newClients = compactOrphans(db, newClients)
  3081. if newClients == nil {
  3082. newClients = []any{}
  3083. }
  3084. settings["clients"] = newClients
  3085. newSettings, err := json.MarshalIndent(settings, "", " ")
  3086. if err != nil {
  3087. return false, err
  3088. }
  3089. oldInbound.Settings = string(newSettings)
  3090. emailShared, err := inboundSvc.emailUsedByOtherInbounds(email, inboundId)
  3091. if err != nil {
  3092. return false, err
  3093. }
  3094. if !emailShared {
  3095. err = inboundSvc.DelClientIPs(db, email)
  3096. if err != nil {
  3097. logger.Error("Error in delete client IPs")
  3098. return false, err
  3099. }
  3100. }
  3101. needRestart := false
  3102. if len(email) > 0 {
  3103. var enables []bool
  3104. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Limit(1).Pluck("enable", &enables).Error
  3105. if err != nil {
  3106. logger.Error("Get stats error")
  3107. return false, err
  3108. }
  3109. notDepleted := len(enables) > 0 && enables[0]
  3110. if !emailShared {
  3111. err = inboundSvc.DelClientStat(db, email)
  3112. if err != nil {
  3113. logger.Error("Delete stats Data Error")
  3114. return false, err
  3115. }
  3116. }
  3117. if needApiDel && notDepleted && oldInbound.NodeID == nil {
  3118. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  3119. if rterr != nil {
  3120. needRestart = true
  3121. } else {
  3122. err1 := rt.RemoveUser(context.Background(), oldInbound, email)
  3123. if err1 == nil {
  3124. logger.Debug("Client deleted on", rt.Name(), ":", email)
  3125. needRestart = false
  3126. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  3127. logger.Debug("User is already deleted. Nothing to do more...")
  3128. } else {
  3129. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  3130. needRestart = true
  3131. }
  3132. }
  3133. }
  3134. }
  3135. if oldInbound.NodeID != nil && len(email) > 0 {
  3136. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  3137. if rterr != nil {
  3138. return false, rterr
  3139. }
  3140. if err1 := rt.DeleteUser(context.Background(), oldInbound, email); err1 != nil {
  3141. return false, err1
  3142. }
  3143. }
  3144. if err := db.Save(oldInbound).Error; err != nil {
  3145. return false, err
  3146. }
  3147. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  3148. if gcErr != nil {
  3149. return false, gcErr
  3150. }
  3151. if err := s.SyncInbound(db, inboundId, finalClients); err != nil {
  3152. return false, err
  3153. }
  3154. return needRestart, nil
  3155. }
  3156. func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inboundId int, email string) (bool, error) {
  3157. defer lockInbound(inboundId).Unlock()
  3158. oldInbound, err := inboundSvc.GetInbound(inboundId)
  3159. if err != nil {
  3160. logger.Error("Load Old Data Error")
  3161. return false, err
  3162. }
  3163. var settings map[string]any
  3164. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  3165. return false, err
  3166. }
  3167. interfaceClients, ok := settings["clients"].([]any)
  3168. if !ok {
  3169. return false, common.NewError("invalid clients format in inbound settings")
  3170. }
  3171. var newClients []any
  3172. needApiDel := false
  3173. found := false
  3174. for _, client := range interfaceClients {
  3175. c, ok := client.(map[string]any)
  3176. if !ok {
  3177. continue
  3178. }
  3179. if cEmail, ok := c["email"].(string); ok && cEmail == email {
  3180. found = true
  3181. needApiDel, _ = c["enable"].(bool)
  3182. } else {
  3183. newClients = append(newClients, client)
  3184. }
  3185. }
  3186. if !found {
  3187. return false, common.NewError(fmt.Sprintf("client with email %s not found", email))
  3188. }
  3189. db := database.GetDB()
  3190. newClients = compactOrphans(db, newClients)
  3191. if newClients == nil {
  3192. newClients = []any{}
  3193. }
  3194. settings["clients"] = newClients
  3195. newSettings, err := json.MarshalIndent(settings, "", " ")
  3196. if err != nil {
  3197. return false, err
  3198. }
  3199. oldInbound.Settings = string(newSettings)
  3200. emailShared, err := inboundSvc.emailUsedByOtherInbounds(email, inboundId)
  3201. if err != nil {
  3202. return false, err
  3203. }
  3204. if !emailShared {
  3205. if err := inboundSvc.DelClientIPs(db, email); err != nil {
  3206. logger.Error("Error in delete client IPs")
  3207. return false, err
  3208. }
  3209. }
  3210. needRestart := false
  3211. if len(email) > 0 && !emailShared {
  3212. traffic, err := inboundSvc.GetClientTrafficByEmail(email)
  3213. if err != nil {
  3214. return false, err
  3215. }
  3216. if traffic != nil {
  3217. if err := inboundSvc.DelClientStat(db, email); err != nil {
  3218. logger.Error("Delete stats Data Error")
  3219. return false, err
  3220. }
  3221. }
  3222. if needApiDel {
  3223. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  3224. if rterr != nil {
  3225. if oldInbound.NodeID != nil {
  3226. return false, rterr
  3227. }
  3228. needRestart = true
  3229. } else if oldInbound.NodeID == nil {
  3230. if err1 := rt.RemoveUser(context.Background(), oldInbound, email); err1 == nil {
  3231. logger.Debug("Client deleted on", rt.Name(), ":", email)
  3232. needRestart = false
  3233. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  3234. logger.Debug("User is already deleted. Nothing to do more...")
  3235. } else {
  3236. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  3237. needRestart = true
  3238. }
  3239. } else {
  3240. if err1 := rt.DeleteUser(context.Background(), oldInbound, email); err1 != nil {
  3241. return false, err1
  3242. }
  3243. }
  3244. }
  3245. }
  3246. if err := db.Save(oldInbound).Error; err != nil {
  3247. return false, err
  3248. }
  3249. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  3250. if gcErr != nil {
  3251. return false, gcErr
  3252. }
  3253. if err := s.SyncInbound(db, inboundId, finalClients); err != nil {
  3254. return false, err
  3255. }
  3256. return needRestart, nil
  3257. }
  3258. func (s *ClientService) SetClientTelegramUserID(inboundSvc *InboundService, trafficId int, tgId int64) (bool, error) {
  3259. traffic, inbound, err := inboundSvc.GetClientInboundByTrafficID(trafficId)
  3260. if err != nil {
  3261. return false, err
  3262. }
  3263. if inbound == nil {
  3264. return false, common.NewError("Inbound Not Found For Traffic ID:", trafficId)
  3265. }
  3266. clientEmail := traffic.Email
  3267. oldClients, err := inboundSvc.GetClients(inbound)
  3268. if err != nil {
  3269. return false, err
  3270. }
  3271. clientId := ""
  3272. for _, oldClient := range oldClients {
  3273. if oldClient.Email == clientEmail {
  3274. switch inbound.Protocol {
  3275. case "trojan":
  3276. clientId = oldClient.Password
  3277. case "shadowsocks":
  3278. clientId = oldClient.Email
  3279. default:
  3280. clientId = oldClient.ID
  3281. }
  3282. break
  3283. }
  3284. }
  3285. if len(clientId) == 0 {
  3286. return false, common.NewError("Client Not Found For Email:", clientEmail)
  3287. }
  3288. var settings map[string]any
  3289. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  3290. if err != nil {
  3291. return false, err
  3292. }
  3293. clients := settings["clients"].([]any)
  3294. var newClients []any
  3295. for client_index := range clients {
  3296. c := clients[client_index].(map[string]any)
  3297. if c["email"] == clientEmail {
  3298. c["tgId"] = tgId
  3299. c["updated_at"] = time.Now().Unix() * 1000
  3300. newClients = append(newClients, any(c))
  3301. }
  3302. }
  3303. settings["clients"] = newClients
  3304. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  3305. if err != nil {
  3306. return false, err
  3307. }
  3308. inbound.Settings = string(modifiedSettings)
  3309. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  3310. return needRestart, err
  3311. }
  3312. func (s *ClientService) checkIsEnabledByEmail(inboundSvc *InboundService, clientEmail string) (bool, error) {
  3313. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  3314. if err != nil {
  3315. return false, err
  3316. }
  3317. if inbound == nil {
  3318. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  3319. }
  3320. clients, err := inboundSvc.GetClients(inbound)
  3321. if err != nil {
  3322. return false, err
  3323. }
  3324. isEnable := false
  3325. for _, client := range clients {
  3326. if client.Email == clientEmail {
  3327. isEnable = client.Enable
  3328. break
  3329. }
  3330. }
  3331. return isEnable, err
  3332. }
  3333. func (s *ClientService) ToggleClientEnableByEmail(inboundSvc *InboundService, clientEmail string) (bool, bool, error) {
  3334. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  3335. if err != nil {
  3336. return false, false, err
  3337. }
  3338. if inbound == nil {
  3339. return false, false, common.NewError("Inbound Not Found For Email:", clientEmail)
  3340. }
  3341. oldClients, err := inboundSvc.GetClients(inbound)
  3342. if err != nil {
  3343. return false, false, err
  3344. }
  3345. clientId := ""
  3346. clientOldEnabled := false
  3347. for _, oldClient := range oldClients {
  3348. if oldClient.Email == clientEmail {
  3349. switch inbound.Protocol {
  3350. case "trojan":
  3351. clientId = oldClient.Password
  3352. case "shadowsocks":
  3353. clientId = oldClient.Email
  3354. default:
  3355. clientId = oldClient.ID
  3356. }
  3357. clientOldEnabled = oldClient.Enable
  3358. break
  3359. }
  3360. }
  3361. if len(clientId) == 0 {
  3362. return false, false, common.NewError("Client Not Found For Email:", clientEmail)
  3363. }
  3364. var settings map[string]any
  3365. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  3366. if err != nil {
  3367. return false, false, err
  3368. }
  3369. clients := settings["clients"].([]any)
  3370. var newClients []any
  3371. for client_index := range clients {
  3372. c := clients[client_index].(map[string]any)
  3373. if c["email"] == clientEmail {
  3374. c["enable"] = !clientOldEnabled
  3375. c["updated_at"] = time.Now().Unix() * 1000
  3376. newClients = append(newClients, any(c))
  3377. }
  3378. }
  3379. settings["clients"] = newClients
  3380. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  3381. if err != nil {
  3382. return false, false, err
  3383. }
  3384. inbound.Settings = string(modifiedSettings)
  3385. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  3386. if err != nil {
  3387. return false, needRestart, err
  3388. }
  3389. return !clientOldEnabled, needRestart, nil
  3390. }
  3391. func (s *ClientService) SetClientEnableByEmail(inboundSvc *InboundService, clientEmail string, enable bool) (bool, bool, error) {
  3392. current, err := s.checkIsEnabledByEmail(inboundSvc, clientEmail)
  3393. if err != nil {
  3394. return false, false, err
  3395. }
  3396. if current == enable {
  3397. return false, false, nil
  3398. }
  3399. newEnabled, needRestart, err := s.ToggleClientEnableByEmail(inboundSvc, clientEmail)
  3400. if err != nil {
  3401. return false, needRestart, err
  3402. }
  3403. return newEnabled == enable, needRestart, nil
  3404. }
  3405. func (s *ClientService) ResetClientIpLimitByEmail(inboundSvc *InboundService, clientEmail string, count int) (bool, error) {
  3406. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  3407. if err != nil {
  3408. return false, err
  3409. }
  3410. if inbound == nil {
  3411. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  3412. }
  3413. oldClients, err := inboundSvc.GetClients(inbound)
  3414. if err != nil {
  3415. return false, err
  3416. }
  3417. clientId := ""
  3418. for _, oldClient := range oldClients {
  3419. if oldClient.Email == clientEmail {
  3420. switch inbound.Protocol {
  3421. case "trojan":
  3422. clientId = oldClient.Password
  3423. case "shadowsocks":
  3424. clientId = oldClient.Email
  3425. default:
  3426. clientId = oldClient.ID
  3427. }
  3428. break
  3429. }
  3430. }
  3431. if len(clientId) == 0 {
  3432. return false, common.NewError("Client Not Found For Email:", clientEmail)
  3433. }
  3434. var settings map[string]any
  3435. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  3436. if err != nil {
  3437. return false, err
  3438. }
  3439. clients := settings["clients"].([]any)
  3440. var newClients []any
  3441. for client_index := range clients {
  3442. c := clients[client_index].(map[string]any)
  3443. if c["email"] == clientEmail {
  3444. c["limitIp"] = count
  3445. c["updated_at"] = time.Now().Unix() * 1000
  3446. newClients = append(newClients, any(c))
  3447. }
  3448. }
  3449. settings["clients"] = newClients
  3450. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  3451. if err != nil {
  3452. return false, err
  3453. }
  3454. inbound.Settings = string(modifiedSettings)
  3455. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  3456. return needRestart, err
  3457. }
  3458. func (s *ClientService) ResetClientExpiryTimeByEmail(inboundSvc *InboundService, clientEmail string, expiry_time int64) (bool, error) {
  3459. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  3460. if err != nil {
  3461. return false, err
  3462. }
  3463. if inbound == nil {
  3464. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  3465. }
  3466. oldClients, err := inboundSvc.GetClients(inbound)
  3467. if err != nil {
  3468. return false, err
  3469. }
  3470. clientId := ""
  3471. for _, oldClient := range oldClients {
  3472. if oldClient.Email == clientEmail {
  3473. switch inbound.Protocol {
  3474. case "trojan":
  3475. clientId = oldClient.Password
  3476. case "shadowsocks":
  3477. clientId = oldClient.Email
  3478. default:
  3479. clientId = oldClient.ID
  3480. }
  3481. break
  3482. }
  3483. }
  3484. if len(clientId) == 0 {
  3485. return false, common.NewError("Client Not Found For Email:", clientEmail)
  3486. }
  3487. var settings map[string]any
  3488. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  3489. if err != nil {
  3490. return false, err
  3491. }
  3492. clients := settings["clients"].([]any)
  3493. var newClients []any
  3494. for client_index := range clients {
  3495. c := clients[client_index].(map[string]any)
  3496. if c["email"] == clientEmail {
  3497. c["expiryTime"] = expiry_time
  3498. c["updated_at"] = time.Now().Unix() * 1000
  3499. newClients = append(newClients, any(c))
  3500. }
  3501. }
  3502. settings["clients"] = newClients
  3503. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  3504. if err != nil {
  3505. return false, err
  3506. }
  3507. inbound.Settings = string(modifiedSettings)
  3508. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  3509. return needRestart, err
  3510. }
  3511. func (s *ClientService) ResetClientTrafficLimitByEmail(inboundSvc *InboundService, clientEmail string, totalGB int) (bool, error) {
  3512. if totalGB < 0 {
  3513. return false, common.NewError("totalGB must be >= 0")
  3514. }
  3515. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  3516. if err != nil {
  3517. return false, err
  3518. }
  3519. if inbound == nil {
  3520. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  3521. }
  3522. oldClients, err := inboundSvc.GetClients(inbound)
  3523. if err != nil {
  3524. return false, err
  3525. }
  3526. clientId := ""
  3527. for _, oldClient := range oldClients {
  3528. if oldClient.Email == clientEmail {
  3529. switch inbound.Protocol {
  3530. case "trojan":
  3531. clientId = oldClient.Password
  3532. case "shadowsocks":
  3533. clientId = oldClient.Email
  3534. default:
  3535. clientId = oldClient.ID
  3536. }
  3537. break
  3538. }
  3539. }
  3540. if len(clientId) == 0 {
  3541. return false, common.NewError("Client Not Found For Email:", clientEmail)
  3542. }
  3543. var settings map[string]any
  3544. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  3545. if err != nil {
  3546. return false, err
  3547. }
  3548. clients := settings["clients"].([]any)
  3549. var newClients []any
  3550. for client_index := range clients {
  3551. c := clients[client_index].(map[string]any)
  3552. if c["email"] == clientEmail {
  3553. c["totalGB"] = totalGB * 1024 * 1024 * 1024
  3554. c["updated_at"] = time.Now().Unix() * 1000
  3555. newClients = append(newClients, any(c))
  3556. }
  3557. }
  3558. settings["clients"] = newClients
  3559. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  3560. if err != nil {
  3561. return false, err
  3562. }
  3563. inbound.Settings = string(modifiedSettings)
  3564. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  3565. return needRestart, err
  3566. }