client.go 122 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696
  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. existing := make(map[string]struct{}, len(emails))
  116. const orphanChunk = 400
  117. for start := 0; start < len(emails); start += orphanChunk {
  118. end := min(start+orphanChunk, len(emails))
  119. var found []string
  120. if err := db.Model(&model.ClientRecord{}).Where("email IN ?", emails[start:end]).Pluck("email", &found).Error; err != nil {
  121. logger.Warning("compactOrphans pluck:", err)
  122. return clients
  123. }
  124. for _, e := range found {
  125. existing[e] = struct{}{}
  126. }
  127. }
  128. if len(existing) == len(emails) {
  129. return clients
  130. }
  131. out := make([]any, 0, len(existing))
  132. for _, c := range clients {
  133. cm, ok := c.(map[string]any)
  134. if !ok {
  135. out = append(out, c)
  136. continue
  137. }
  138. e, _ := cm["email"].(string)
  139. if e == "" {
  140. out = append(out, c)
  141. continue
  142. }
  143. if _, ok := existing[e]; ok {
  144. out = append(out, c)
  145. }
  146. }
  147. return out
  148. }
  149. func tombstoneClientEmail(email string) {
  150. if email == "" {
  151. return
  152. }
  153. recentlyDeletedMu.Lock()
  154. defer recentlyDeletedMu.Unlock()
  155. recentlyDeleted[email] = time.Now()
  156. cutoff := time.Now().Add(-deleteTombstoneTTL)
  157. for e, ts := range recentlyDeleted {
  158. if ts.Before(cutoff) {
  159. delete(recentlyDeleted, e)
  160. }
  161. }
  162. }
  163. func tombstoneClientEmails(emails []string) {
  164. if len(emails) == 0 {
  165. return
  166. }
  167. now := time.Now()
  168. cutoff := now.Add(-deleteTombstoneTTL)
  169. recentlyDeletedMu.Lock()
  170. defer recentlyDeletedMu.Unlock()
  171. for _, email := range emails {
  172. if email != "" {
  173. recentlyDeleted[email] = now
  174. }
  175. }
  176. for e, ts := range recentlyDeleted {
  177. if ts.Before(cutoff) {
  178. delete(recentlyDeleted, e)
  179. }
  180. }
  181. }
  182. func isClientEmailTombstoned(email string) bool {
  183. if email == "" {
  184. return false
  185. }
  186. recentlyDeletedMu.Lock()
  187. defer recentlyDeletedMu.Unlock()
  188. ts, ok := recentlyDeleted[email]
  189. if !ok {
  190. return false
  191. }
  192. if time.Since(ts) > deleteTombstoneTTL {
  193. delete(recentlyDeleted, email)
  194. return false
  195. }
  196. return true
  197. }
  198. func (s *ClientService) SyncInbound(tx *gorm.DB, inboundId int, clients []model.Client) error {
  199. if tx == nil {
  200. tx = database.GetDB()
  201. }
  202. if err := tx.Where("inbound_id = ?", inboundId).Delete(&model.ClientInbound{}).Error; err != nil {
  203. return err
  204. }
  205. emails := make([]string, 0, len(clients))
  206. seen := make(map[string]struct{}, len(clients))
  207. for i := range clients {
  208. email := strings.TrimSpace(clients[i].Email)
  209. if email == "" {
  210. continue
  211. }
  212. if _, ok := seen[email]; ok {
  213. continue
  214. }
  215. seen[email] = struct{}{}
  216. emails = append(emails, email)
  217. }
  218. existing := make(map[string]*model.ClientRecord, len(emails))
  219. const selectChunk = 400
  220. for start := 0; start < len(emails); start += selectChunk {
  221. end := min(start+selectChunk, len(emails))
  222. var rows []model.ClientRecord
  223. if err := tx.Where("email IN ?", emails[start:end]).Find(&rows).Error; err != nil {
  224. return err
  225. }
  226. for i := range rows {
  227. r := rows[i]
  228. existing[r.Email] = &r
  229. }
  230. }
  231. idByEmail := make(map[string]int, len(emails))
  232. pending := make(map[string]*model.ClientRecord, len(emails))
  233. toCreate := make([]*model.ClientRecord, 0, len(emails))
  234. for i := range clients {
  235. email := strings.TrimSpace(clients[i].Email)
  236. if email == "" {
  237. continue
  238. }
  239. incoming := clients[i].ToRecord()
  240. row, ok := existing[email]
  241. if !ok {
  242. if _, dup := pending[email]; !dup {
  243. pending[email] = incoming
  244. toCreate = append(toCreate, incoming)
  245. }
  246. continue
  247. }
  248. before := *row
  249. if incoming.UUID != "" {
  250. row.UUID = incoming.UUID
  251. }
  252. if incoming.Password != "" {
  253. row.Password = incoming.Password
  254. }
  255. if incoming.Auth != "" {
  256. row.Auth = incoming.Auth
  257. }
  258. row.Flow = incoming.Flow
  259. if incoming.Security != "" {
  260. row.Security = incoming.Security
  261. }
  262. if incoming.Reverse != "" {
  263. row.Reverse = incoming.Reverse
  264. }
  265. row.SubID = incoming.SubID
  266. row.LimitIP = incoming.LimitIP
  267. row.TotalGB = incoming.TotalGB
  268. row.ExpiryTime = incoming.ExpiryTime
  269. row.Enable = incoming.Enable
  270. row.TgID = incoming.TgID
  271. if incoming.Group != "" {
  272. row.Group = incoming.Group
  273. }
  274. row.Comment = incoming.Comment
  275. row.Reset = incoming.Reset
  276. if incoming.CreatedAt > 0 && (row.CreatedAt == 0 || incoming.CreatedAt < row.CreatedAt) {
  277. row.CreatedAt = incoming.CreatedAt
  278. }
  279. preservedUpdatedAt := max(incoming.UpdatedAt, row.UpdatedAt)
  280. row.UpdatedAt = preservedUpdatedAt
  281. idByEmail[email] = row.Id
  282. if *row == before {
  283. continue
  284. }
  285. if err := tx.Save(row).Error; err != nil {
  286. return err
  287. }
  288. if err := tx.Model(&model.ClientRecord{}).
  289. Where("id = ?", row.Id).
  290. UpdateColumn("updated_at", preservedUpdatedAt).Error; err != nil {
  291. return err
  292. }
  293. }
  294. if len(toCreate) > 0 {
  295. if err := tx.CreateInBatches(toCreate, 200).Error; err != nil {
  296. return err
  297. }
  298. for _, rec := range toCreate {
  299. idByEmail[rec.Email] = rec.Id
  300. }
  301. }
  302. links := make([]model.ClientInbound, 0, len(clients))
  303. linked := make(map[int]struct{}, len(clients))
  304. for i := range clients {
  305. email := strings.TrimSpace(clients[i].Email)
  306. if email == "" {
  307. continue
  308. }
  309. id, ok := idByEmail[email]
  310. if !ok {
  311. continue
  312. }
  313. if _, dup := linked[id]; dup {
  314. continue
  315. }
  316. linked[id] = struct{}{}
  317. links = append(links, model.ClientInbound{
  318. ClientId: id,
  319. InboundId: inboundId,
  320. FlowOverride: clients[i].Flow,
  321. })
  322. }
  323. if len(links) > 0 {
  324. if err := tx.CreateInBatches(links, 200).Error; err != nil {
  325. return err
  326. }
  327. }
  328. return nil
  329. }
  330. func (s *ClientService) DetachInbound(tx *gorm.DB, inboundId int) error {
  331. if tx == nil {
  332. tx = database.GetDB()
  333. }
  334. return tx.Where("inbound_id = ?", inboundId).Delete(&model.ClientInbound{}).Error
  335. }
  336. func (s *ClientService) ListForInbound(tx *gorm.DB, inboundId int) ([]model.Client, error) {
  337. if tx == nil {
  338. tx = database.GetDB()
  339. }
  340. type joinedRow struct {
  341. model.ClientRecord
  342. FlowOverride string
  343. }
  344. var rows []joinedRow
  345. err := tx.Table("clients").
  346. Select("clients.*, client_inbounds.flow_override AS flow_override").
  347. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  348. Where("client_inbounds.inbound_id = ?", inboundId).
  349. Order("clients.id ASC").
  350. Find(&rows).Error
  351. if err != nil {
  352. return nil, err
  353. }
  354. out := make([]model.Client, 0, len(rows))
  355. for i := range rows {
  356. c := rows[i].ToClient()
  357. c.Flow = rows[i].FlowOverride
  358. out = append(out, *c)
  359. }
  360. return out, nil
  361. }
  362. func (s *ClientService) GetRecordByEmail(tx *gorm.DB, email string) (*model.ClientRecord, error) {
  363. if tx == nil {
  364. tx = database.GetDB()
  365. }
  366. row := &model.ClientRecord{}
  367. err := tx.Where("email = ?", email).First(row).Error
  368. if err != nil {
  369. return nil, err
  370. }
  371. return row, nil
  372. }
  373. // EffectiveFlow returns the client's flow from the first flow-capable inbound
  374. // it is attached to (lowest inbound_id with a non-empty flow_override). The
  375. // canonical clients.Flow column is unreliable for multi-inbound clients: a
  376. // non-flow inbound (Hysteria, WS, gRPC, …) carries an empty flow and, when its
  377. // SyncInbound runs last, overwrites the column to "" even though a VLESS Reality
  378. // inbound stored a real flow. The per-inbound flow_override is always correct,
  379. // so derive the display flow from it (order-independent). See issue #4792.
  380. func (s *ClientService) EffectiveFlow(tx *gorm.DB, recordId int) (string, error) {
  381. if tx == nil {
  382. tx = database.GetDB()
  383. }
  384. var flows []string
  385. err := tx.Model(&model.ClientInbound{}).
  386. Where("client_id = ? AND flow_override <> ?", recordId, "").
  387. Order("inbound_id ASC").
  388. Limit(1).
  389. Pluck("flow_override", &flows).Error
  390. if err != nil {
  391. return "", err
  392. }
  393. if len(flows) == 0 {
  394. return "", nil
  395. }
  396. return flows[0], nil
  397. }
  398. func (s *ClientService) GetInboundIdsForEmail(tx *gorm.DB, email string) ([]int, error) {
  399. if tx == nil {
  400. tx = database.GetDB()
  401. }
  402. var ids []int
  403. err := tx.Table("client_inbounds").
  404. Select("client_inbounds.inbound_id").
  405. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  406. Where("clients.email = ?", email).
  407. Scan(&ids).Error
  408. if err != nil {
  409. return nil, err
  410. }
  411. return ids, nil
  412. }
  413. func (s *ClientService) GetByID(id int) (*model.ClientRecord, error) {
  414. row := &model.ClientRecord{}
  415. if err := database.GetDB().Where("id = ?", id).First(row).Error; err != nil {
  416. return nil, err
  417. }
  418. return row, nil
  419. }
  420. func (s *ClientService) GetInboundIdsForRecord(id int) ([]int, error) {
  421. var ids []int
  422. err := database.GetDB().Table("client_inbounds").
  423. Where("client_id = ?", id).
  424. Order("inbound_id ASC").
  425. Pluck("inbound_id", &ids).Error
  426. if err != nil {
  427. return nil, err
  428. }
  429. return ids, nil
  430. }
  431. func (s *ClientService) List() ([]ClientWithAttachments, error) {
  432. db := database.GetDB()
  433. var rows []model.ClientRecord
  434. if err := db.Order("id ASC").Find(&rows).Error; err != nil {
  435. return nil, err
  436. }
  437. if len(rows) == 0 {
  438. return []ClientWithAttachments{}, nil
  439. }
  440. clientIds := make([]int, 0, len(rows))
  441. emails := make([]string, 0, len(rows))
  442. for i := range rows {
  443. clientIds = append(clientIds, rows[i].Id)
  444. if rows[i].Email != "" {
  445. emails = append(emails, rows[i].Email)
  446. }
  447. }
  448. attachments := make(map[int][]int, len(rows))
  449. for _, batch := range chunkInts(clientIds, sqlInChunk) {
  450. var links []model.ClientInbound
  451. if err := db.Where("client_id IN ?", batch).Find(&links).Error; err != nil {
  452. return nil, err
  453. }
  454. for _, l := range links {
  455. attachments[l.ClientId] = append(attachments[l.ClientId], l.InboundId)
  456. }
  457. }
  458. trafficByEmail := make(map[string]*xray.ClientTraffic, len(emails))
  459. if len(emails) > 0 {
  460. var stats []xray.ClientTraffic
  461. for _, batch := range chunkStrings(emails, sqlInChunk) {
  462. var batchStats []xray.ClientTraffic
  463. if err := db.Where("email IN ?", batch).Find(&batchStats).Error; err != nil {
  464. return nil, err
  465. }
  466. stats = append(stats, batchStats...)
  467. }
  468. for i := range stats {
  469. trafficByEmail[stats[i].Email] = &stats[i]
  470. }
  471. }
  472. out := make([]ClientWithAttachments, 0, len(rows))
  473. for i := range rows {
  474. out = append(out, ClientWithAttachments{
  475. ClientRecord: rows[i],
  476. InboundIds: attachments[rows[i].Id],
  477. Traffic: trafficByEmail[rows[i].Email],
  478. })
  479. }
  480. return out, nil
  481. }
  482. type ClientCreatePayload struct {
  483. Client model.Client `json:"client"`
  484. InboundIds []int `json:"inboundIds"`
  485. }
  486. func hasForbiddenClientChar(s string) bool {
  487. for _, r := range s {
  488. if r == '/' || r == '\\' || r == ' ' || r < 0x20 || r == 0x7f {
  489. return true
  490. }
  491. }
  492. return false
  493. }
  494. func validateClientEmail(email string) error {
  495. if hasForbiddenClientChar(email) {
  496. return common.NewError("client email contains an invalid character:", email)
  497. }
  498. return nil
  499. }
  500. func validateClientSubID(subID string) error {
  501. if hasForbiddenClientChar(subID) {
  502. return common.NewError("client subId contains an invalid character:", subID)
  503. }
  504. return nil
  505. }
  506. func (s *ClientService) HasPendingNode(inboundSvc *InboundService, email string) bool {
  507. if strings.TrimSpace(email) == "" {
  508. return false
  509. }
  510. ids, err := s.GetInboundIdsForEmail(nil, email)
  511. if err != nil {
  512. return false
  513. }
  514. return inboundSvc.AnyNodePending(ids)
  515. }
  516. func (s *ClientService) Create(inboundSvc *InboundService, payload *ClientCreatePayload) (bool, error) {
  517. if payload == nil {
  518. return false, common.NewError("empty payload")
  519. }
  520. client := payload.Client
  521. if strings.TrimSpace(client.Email) == "" {
  522. return false, common.NewError("client email is required")
  523. }
  524. if err := validateClientEmail(client.Email); err != nil {
  525. return false, err
  526. }
  527. if err := validateClientSubID(client.SubID); err != nil {
  528. return false, err
  529. }
  530. if len(payload.InboundIds) == 0 {
  531. return false, common.NewError("at least one inbound is required")
  532. }
  533. if client.SubID == "" {
  534. client.SubID = uuid.NewString()
  535. }
  536. if !client.Enable {
  537. client.Enable = true
  538. }
  539. now := time.Now().UnixMilli()
  540. if client.CreatedAt == 0 {
  541. client.CreatedAt = now
  542. }
  543. client.UpdatedAt = now
  544. existing := &model.ClientRecord{}
  545. err := database.GetDB().Where("email = ?", client.Email).First(existing).Error
  546. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  547. return false, err
  548. }
  549. emailTaken := !errors.Is(err, gorm.ErrRecordNotFound)
  550. if emailTaken {
  551. if existing.SubID == "" || existing.SubID != client.SubID {
  552. return false, common.NewError("email already in use:", client.Email)
  553. }
  554. }
  555. if client.SubID != "" {
  556. var subTaken int64
  557. if err := database.GetDB().Model(&model.ClientRecord{}).
  558. Where("sub_id = ? AND email <> ?", client.SubID, client.Email).
  559. Count(&subTaken).Error; err != nil {
  560. return false, err
  561. }
  562. if subTaken > 0 {
  563. return false, common.NewError("subId already in use:", client.SubID)
  564. }
  565. }
  566. needRestart := false
  567. for _, ibId := range payload.InboundIds {
  568. inbound, getErr := inboundSvc.GetInbound(ibId)
  569. if getErr != nil {
  570. return needRestart, getErr
  571. }
  572. if err := s.fillProtocolDefaults(&client, inbound); err != nil {
  573. return needRestart, err
  574. }
  575. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(client, inbound)}})
  576. if mErr != nil {
  577. return needRestart, mErr
  578. }
  579. nr, addErr := s.AddInboundClient(inboundSvc, &model.Inbound{
  580. Id: ibId,
  581. Settings: string(settingsPayload),
  582. })
  583. if addErr != nil {
  584. return needRestart, addErr
  585. }
  586. if nr {
  587. needRestart = true
  588. }
  589. }
  590. return needRestart, nil
  591. }
  592. func (s *ClientService) fillProtocolDefaults(c *model.Client, ib *model.Inbound) error {
  593. switch ib.Protocol {
  594. case model.VMESS, model.VLESS:
  595. if c.ID == "" {
  596. c.ID = uuid.NewString()
  597. }
  598. case model.Trojan:
  599. if c.Password == "" {
  600. c.Password = strings.ReplaceAll(uuid.NewString(), "-", "")
  601. }
  602. case model.Shadowsocks:
  603. method := shadowsocksMethodFromSettings(ib.Settings)
  604. if c.Password == "" || !validShadowsocksClientKey(method, c.Password) {
  605. c.Password = randomShadowsocksClientKey(method)
  606. }
  607. case model.Hysteria:
  608. if c.Auth == "" {
  609. c.Auth = strings.ReplaceAll(uuid.NewString(), "-", "")
  610. }
  611. }
  612. return nil
  613. }
  614. func clientWithInboundFlow(c model.Client, ib *model.Inbound) model.Client {
  615. if !inboundCanEnableTlsFlow(string(ib.Protocol), ib.StreamSettings) {
  616. c.Flow = ""
  617. }
  618. return c
  619. }
  620. func shadowsocksMethodFromSettings(settings string) string {
  621. if settings == "" {
  622. return ""
  623. }
  624. var m map[string]any
  625. if err := json.Unmarshal([]byte(settings), &m); err != nil {
  626. return ""
  627. }
  628. method, _ := m["method"].(string)
  629. return method
  630. }
  631. func randomShadowsocksClientKey(method string) string {
  632. if n := shadowsocksKeyBytes(method); n > 0 {
  633. return random.Base64Bytes(n)
  634. }
  635. return strings.ReplaceAll(uuid.NewString(), "-", "")
  636. }
  637. func validShadowsocksClientKey(method, key string) bool {
  638. n := shadowsocksKeyBytes(method)
  639. if n == 0 {
  640. return key != ""
  641. }
  642. decoded, err := base64.StdEncoding.DecodeString(key)
  643. if err != nil {
  644. return false
  645. }
  646. return len(decoded) == n
  647. }
  648. func shadowsocksKeyBytes(method string) int {
  649. switch method {
  650. case "2022-blake3-aes-128-gcm":
  651. return 16
  652. case "2022-blake3-aes-256-gcm", "2022-blake3-chacha20-poly1305":
  653. return 32
  654. }
  655. return 0
  656. }
  657. func applyShadowsocksClientMethod(clients []any, settings map[string]any) {
  658. method, _ := settings["method"].(string)
  659. is2022 := strings.HasPrefix(method, "2022-blake3-")
  660. for i := range clients {
  661. cm, ok := clients[i].(map[string]any)
  662. if !ok {
  663. continue
  664. }
  665. if is2022 {
  666. if _, hasKey := cm["method"]; hasKey {
  667. delete(cm, "method")
  668. clients[i] = cm
  669. }
  670. continue
  671. }
  672. if method == "" {
  673. continue
  674. }
  675. if existing, _ := cm["method"].(string); existing != "" {
  676. continue
  677. }
  678. cm["method"] = method
  679. clients[i] = cm
  680. }
  681. }
  682. func (s *ClientService) Update(inboundSvc *InboundService, id int, updated model.Client, inboundFilter ...int) (bool, error) {
  683. existing, err := s.GetByID(id)
  684. if err != nil {
  685. return false, err
  686. }
  687. inboundIds, err := s.GetInboundIdsForRecord(id)
  688. if err != nil {
  689. return false, err
  690. }
  691. if len(inboundFilter) > 0 {
  692. allow := make(map[int]struct{}, len(inboundFilter))
  693. for _, fid := range inboundFilter {
  694. allow[fid] = struct{}{}
  695. }
  696. filtered := inboundIds[:0:0]
  697. for _, ibId := range inboundIds {
  698. if _, ok := allow[ibId]; ok {
  699. filtered = append(filtered, ibId)
  700. }
  701. }
  702. inboundIds = filtered
  703. }
  704. if strings.TrimSpace(updated.Email) == "" {
  705. return false, common.NewError("client email is required")
  706. }
  707. if err := validateClientEmail(updated.Email); err != nil {
  708. return false, err
  709. }
  710. if err := validateClientSubID(updated.SubID); err != nil {
  711. return false, err
  712. }
  713. if updated.SubID == "" {
  714. updated.SubID = existing.SubID
  715. }
  716. if updated.SubID == "" {
  717. updated.SubID = uuid.NewString()
  718. }
  719. updated.UpdatedAt = time.Now().UnixMilli()
  720. if updated.CreatedAt == 0 {
  721. updated.CreatedAt = existing.CreatedAt
  722. }
  723. // Preserve existing credentials when the caller omits them, so a partial
  724. // update (e.g. only changing traffic/expiry) doesn't silently rotate the
  725. // client's UUID/password/auth via fillProtocolDefaults. Supplying a new
  726. // value still rotates it intentionally.
  727. if updated.ID == "" {
  728. updated.ID = existing.UUID
  729. }
  730. if updated.Password == "" {
  731. updated.Password = existing.Password
  732. }
  733. if updated.Auth == "" {
  734. updated.Auth = existing.Auth
  735. }
  736. if updated.Email != existing.Email {
  737. var collisionCount int64
  738. if err := database.GetDB().Model(&model.ClientRecord{}).
  739. Where("email = ? AND id <> ?", updated.Email, id).
  740. Count(&collisionCount).Error; err != nil {
  741. return false, err
  742. }
  743. if collisionCount > 0 {
  744. return false, common.NewError("Duplicate email:", updated.Email)
  745. }
  746. if err := database.GetDB().Model(&model.ClientRecord{}).
  747. Where("id = ?", id).
  748. Update("email", updated.Email).Error; err != nil {
  749. return false, err
  750. }
  751. }
  752. if updated.SubID != "" {
  753. var subCollision int64
  754. if err := database.GetDB().Model(&model.ClientRecord{}).
  755. Where("sub_id = ? AND id <> ?", updated.SubID, id).
  756. Count(&subCollision).Error; err != nil {
  757. return false, err
  758. }
  759. if subCollision > 0 {
  760. return false, common.NewError("Duplicate subId:", updated.SubID)
  761. }
  762. }
  763. needRestart := false
  764. for _, ibId := range inboundIds {
  765. inbound, getErr := inboundSvc.GetInbound(ibId)
  766. if getErr != nil {
  767. if errors.Is(getErr, gorm.ErrRecordNotFound) {
  768. if err := database.GetDB().
  769. Where("client_id = ? AND inbound_id = ?", id, ibId).
  770. Delete(&model.ClientInbound{}).Error; err != nil {
  771. return needRestart, err
  772. }
  773. continue
  774. }
  775. return needRestart, getErr
  776. }
  777. oldKey := clientKeyForProtocol(inbound.Protocol, existing)
  778. if oldKey == "" {
  779. continue
  780. }
  781. if err := s.fillProtocolDefaults(&updated, inbound); err != nil {
  782. return needRestart, err
  783. }
  784. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(updated, inbound)}})
  785. if mErr != nil {
  786. return needRestart, mErr
  787. }
  788. nr, upErr := s.UpdateInboundClient(inboundSvc, &model.Inbound{
  789. Id: ibId,
  790. Settings: string(settingsPayload),
  791. }, oldKey)
  792. if upErr != nil {
  793. return needRestart, upErr
  794. }
  795. if nr {
  796. needRestart = true
  797. }
  798. }
  799. reverseStr := ""
  800. if updated.Reverse != nil && strings.TrimSpace(updated.Reverse.Tag) != "" {
  801. if b, mErr := json.Marshal(updated.Reverse); mErr == nil {
  802. reverseStr = string(b)
  803. }
  804. }
  805. if err := database.GetDB().Model(&model.ClientRecord{}).
  806. Where("id = ?", id).
  807. Update("reverse", reverseStr).Error; err != nil {
  808. return needRestart, err
  809. }
  810. if err := database.GetDB().Model(&model.ClientRecord{}).
  811. Where("id = ?", id).
  812. UpdateColumn("updated_at", time.Now().UnixMilli()).Error; err != nil {
  813. return needRestart, err
  814. }
  815. return needRestart, nil
  816. }
  817. func (s *ClientService) Delete(inboundSvc *InboundService, id int, keepTraffic bool) (bool, error) {
  818. existing, err := s.GetByID(id)
  819. if err != nil {
  820. return false, err
  821. }
  822. tombstoneClientEmail(existing.Email)
  823. inboundIds, err := s.GetInboundIdsForRecord(id)
  824. if err != nil {
  825. return false, err
  826. }
  827. needRestart := false
  828. for _, ibId := range inboundIds {
  829. inbound, getErr := inboundSvc.GetInbound(ibId)
  830. if getErr != nil {
  831. if errors.Is(getErr, gorm.ErrRecordNotFound) {
  832. continue
  833. }
  834. return needRestart, getErr
  835. }
  836. key := clientKeyForProtocol(inbound.Protocol, existing)
  837. if key == "" {
  838. continue
  839. }
  840. nr, delErr := s.DelInboundClient(inboundSvc, ibId, key, false)
  841. if delErr != nil {
  842. return needRestart, delErr
  843. }
  844. if nr {
  845. needRestart = true
  846. }
  847. }
  848. db := database.GetDB()
  849. if err := db.Where("client_id = ?", id).Delete(&model.ClientInbound{}).Error; err != nil {
  850. return needRestart, err
  851. }
  852. if !keepTraffic && existing.Email != "" {
  853. if err := db.Where("email = ?", existing.Email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  854. return needRestart, err
  855. }
  856. if err := db.Where("client_email = ?", existing.Email).Delete(&model.InboundClientIps{}).Error; err != nil {
  857. return needRestart, err
  858. }
  859. }
  860. if err := db.Delete(&model.ClientRecord{}, id).Error; err != nil {
  861. return needRestart, err
  862. }
  863. return needRestart, nil
  864. }
  865. func (s *ClientService) Attach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  866. existing, err := s.GetByID(id)
  867. if err != nil {
  868. return false, err
  869. }
  870. currentIds, err := s.GetInboundIdsForRecord(id)
  871. if err != nil {
  872. return false, err
  873. }
  874. have := make(map[int]struct{}, len(currentIds))
  875. for _, x := range currentIds {
  876. have[x] = struct{}{}
  877. }
  878. clientWire := existing.ToClient()
  879. flow, ffErr := s.EffectiveFlow(nil, id)
  880. if ffErr != nil {
  881. return false, ffErr
  882. }
  883. clientWire.Flow = flow
  884. clientWire.UpdatedAt = time.Now().UnixMilli()
  885. needRestart := false
  886. for _, ibId := range inboundIds {
  887. if _, attached := have[ibId]; attached {
  888. continue
  889. }
  890. inbound, getErr := inboundSvc.GetInbound(ibId)
  891. if getErr != nil {
  892. return needRestart, getErr
  893. }
  894. copyClient := *clientWire
  895. if err := s.fillProtocolDefaults(&copyClient, inbound); err != nil {
  896. return needRestart, err
  897. }
  898. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(copyClient, inbound)}})
  899. if mErr != nil {
  900. return needRestart, mErr
  901. }
  902. nr, addErr := s.AddInboundClient(inboundSvc, &model.Inbound{
  903. Id: ibId,
  904. Settings: string(settingsPayload),
  905. })
  906. if addErr != nil {
  907. return needRestart, addErr
  908. }
  909. if nr {
  910. needRestart = true
  911. }
  912. }
  913. return needRestart, nil
  914. }
  915. func (s *ClientService) CreateOne(inboundSvc *InboundService, inboundId int, client model.Client) (bool, error) {
  916. return s.Create(inboundSvc, &ClientCreatePayload{
  917. Client: client,
  918. InboundIds: []int{inboundId},
  919. })
  920. }
  921. func (s *ClientService) DetachByEmail(inboundSvc *InboundService, inboundId int, email string) (bool, error) {
  922. if email == "" {
  923. return false, common.NewError("client email is required")
  924. }
  925. rec, err := s.GetRecordByEmail(nil, email)
  926. if err != nil {
  927. return false, err
  928. }
  929. return s.Detach(inboundSvc, rec.Id, []int{inboundId})
  930. }
  931. func (s *ClientService) AttachByEmail(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  932. if email == "" {
  933. return false, common.NewError("client email is required")
  934. }
  935. rec, err := s.GetRecordByEmail(nil, email)
  936. if err != nil {
  937. return false, err
  938. }
  939. return s.Attach(inboundSvc, rec.Id, inboundIds)
  940. }
  941. // BulkAttachResult reports the outcome of a bulk attach across target inbounds.
  942. type BulkAttachResult struct {
  943. Attached []string `json:"attached"`
  944. Skipped []string `json:"skipped"`
  945. Errors []string `json:"errors"`
  946. }
  947. // BulkAttach attaches the given existing clients (by email) to each target inbound,
  948. // reusing their identity (email/UUID/password/subId) and a shared traffic row. It adds
  949. // all clients to a target in a single AddInboundClient call, and reports clients already
  950. // present on a target as skipped.
  951. func (s *ClientService) BulkAttach(inboundSvc *InboundService, emails []string, inboundIds []int) (*BulkAttachResult, bool, error) {
  952. result := &BulkAttachResult{}
  953. if len(emails) == 0 || len(inboundIds) == 0 {
  954. return result, false, nil
  955. }
  956. recordErr := func(format string, args ...any) {
  957. msg := fmt.Sprintf(format, args...)
  958. result.Errors = append(result.Errors, msg)
  959. logger.Warningf("[BulkAttach] %s", msg)
  960. }
  961. records := make([]*model.ClientRecord, 0, len(emails))
  962. seenEmail := make(map[string]struct{}, len(emails))
  963. for _, email := range emails {
  964. if email == "" {
  965. continue
  966. }
  967. key := strings.ToLower(email)
  968. if _, ok := seenEmail[key]; ok {
  969. continue
  970. }
  971. seenEmail[key] = struct{}{}
  972. rec, err := s.GetRecordByEmail(nil, email)
  973. if err != nil {
  974. recordErr("%s: %v", email, err)
  975. continue
  976. }
  977. records = append(records, rec)
  978. }
  979. emailSubIDs, sidErr := inboundSvc.getAllEmailSubIDs()
  980. if sidErr != nil {
  981. emailSubIDs = nil
  982. logger.Warningf("[BulkAttach] getAllEmailSubIDs: %v", sidErr)
  983. }
  984. needRestart := false
  985. for _, ibId := range inboundIds {
  986. inbound, err := inboundSvc.GetInbound(ibId)
  987. if err != nil {
  988. recordErr("inbound %d: %v", ibId, err)
  989. continue
  990. }
  991. existingClients, err := inboundSvc.GetClients(inbound)
  992. if err != nil {
  993. recordErr("inbound %d: %v", ibId, err)
  994. continue
  995. }
  996. have := make(map[string]struct{}, len(existingClients))
  997. for _, c := range existingClients {
  998. have[strings.ToLower(c.Email)] = struct{}{}
  999. }
  1000. clientsToAdd := make([]model.Client, 0, len(records))
  1001. for _, rec := range records {
  1002. if _, attached := have[strings.ToLower(rec.Email)]; attached {
  1003. result.Skipped = append(result.Skipped, rec.Email)
  1004. continue
  1005. }
  1006. client := *rec.ToClient()
  1007. client.UpdatedAt = time.Now().UnixMilli()
  1008. if err := s.fillProtocolDefaults(&client, inbound); err != nil {
  1009. recordErr("%s -> inbound %d: %v", rec.Email, ibId, err)
  1010. continue
  1011. }
  1012. clientsToAdd = append(clientsToAdd, clientWithInboundFlow(client, inbound))
  1013. }
  1014. if len(clientsToAdd) == 0 {
  1015. continue
  1016. }
  1017. payload, err := json.Marshal(map[string][]model.Client{"clients": clientsToAdd})
  1018. if err != nil {
  1019. recordErr("inbound %d: %v", ibId, err)
  1020. continue
  1021. }
  1022. nr, err := s.addInboundClient(inboundSvc, &model.Inbound{Id: ibId, Settings: string(payload)}, emailSubIDs)
  1023. if err != nil {
  1024. recordErr("inbound %d: %v", ibId, err)
  1025. continue
  1026. }
  1027. if nr {
  1028. needRestart = true
  1029. }
  1030. for _, c := range clientsToAdd {
  1031. result.Attached = append(result.Attached, c.Email)
  1032. }
  1033. }
  1034. return result, needRestart, nil
  1035. }
  1036. // BulkDetachResult reports the outcome of a bulk detach across target inbounds.
  1037. type BulkDetachResult struct {
  1038. Detached []string `json:"detached"`
  1039. Skipped []string `json:"skipped"`
  1040. Errors []string `json:"errors"`
  1041. }
  1042. // BulkDetach detaches the given existing clients (by email) from each target inbound.
  1043. // (email, inbound) pairs where the client is not currently attached are silently skipped
  1044. // at the inbound level; emails that aren't attached to any of the requested inbounds
  1045. // are reported under skipped. ClientRecord rows are kept even when they become orphaned
  1046. // (matches single-client detach semantics); callers should use bulkDelete for full removal.
  1047. func (s *ClientService) BulkDetach(inboundSvc *InboundService, emails []string, inboundIds []int) (*BulkDetachResult, bool, error) {
  1048. result := &BulkDetachResult{}
  1049. if len(emails) == 0 || len(inboundIds) == 0 {
  1050. return result, false, nil
  1051. }
  1052. recordErr := func(format string, args ...any) {
  1053. msg := fmt.Sprintf(format, args...)
  1054. result.Errors = append(result.Errors, msg)
  1055. logger.Warningf("[BulkDetach] %s", msg)
  1056. }
  1057. requested := make(map[int]struct{}, len(inboundIds))
  1058. for _, id := range inboundIds {
  1059. requested[id] = struct{}{}
  1060. }
  1061. recsByInbound := make(map[int][]*model.ClientRecord)
  1062. emailOrder := make([]string, 0, len(emails))
  1063. emailRepr := make(map[string]string, len(emails))
  1064. emailFailed := make(map[string]bool, len(emails))
  1065. seenEmail := make(map[string]struct{}, len(emails))
  1066. for _, email := range emails {
  1067. if email == "" {
  1068. continue
  1069. }
  1070. key := strings.ToLower(email)
  1071. if _, ok := seenEmail[key]; ok {
  1072. continue
  1073. }
  1074. seenEmail[key] = struct{}{}
  1075. rec, err := s.GetRecordByEmail(nil, email)
  1076. if err != nil {
  1077. recordErr("%s: %v", email, err)
  1078. continue
  1079. }
  1080. currentIds, err := s.GetInboundIdsForRecord(rec.Id)
  1081. if err != nil {
  1082. recordErr("%s: %v", email, err)
  1083. continue
  1084. }
  1085. matched := false
  1086. for _, id := range currentIds {
  1087. if _, ok := requested[id]; ok {
  1088. recsByInbound[id] = append(recsByInbound[id], rec)
  1089. matched = true
  1090. }
  1091. }
  1092. if !matched {
  1093. result.Skipped = append(result.Skipped, rec.Email)
  1094. continue
  1095. }
  1096. emailOrder = append(emailOrder, key)
  1097. emailRepr[key] = rec.Email
  1098. }
  1099. needRestart := false
  1100. for _, ibId := range inboundIds {
  1101. recs, ok := recsByInbound[ibId]
  1102. if !ok {
  1103. continue
  1104. }
  1105. delete(recsByInbound, ibId)
  1106. nr, err := s.delInboundClients(inboundSvc, ibId, recs, true)
  1107. if err != nil {
  1108. recordErr("inbound %d: %v", ibId, err)
  1109. for _, rec := range recs {
  1110. emailFailed[strings.ToLower(rec.Email)] = true
  1111. }
  1112. continue
  1113. }
  1114. if nr {
  1115. needRestart = true
  1116. }
  1117. }
  1118. for _, key := range emailOrder {
  1119. if emailFailed[key] {
  1120. continue
  1121. }
  1122. result.Detached = append(result.Detached, emailRepr[key])
  1123. }
  1124. return result, needRestart, nil
  1125. }
  1126. // delInboundClients removes several clients from a single inbound in one pass:
  1127. // one settings rewrite, one runtime sweep, one Save and one SyncInbound for the
  1128. // whole batch, instead of repeating the full per-client cycle. It mirrors the
  1129. // semantics of DelInboundClient for each removed client. needRestart is the OR
  1130. // across all removals.
  1131. func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId int, recs []*model.ClientRecord, keepTraffic bool) (bool, error) {
  1132. if len(recs) == 0 {
  1133. return false, nil
  1134. }
  1135. defer lockInbound(inboundId).Unlock()
  1136. oldInbound, err := inboundSvc.GetInbound(inboundId)
  1137. if err != nil {
  1138. logger.Error("Load Old Data Error")
  1139. return false, err
  1140. }
  1141. var settings map[string]any
  1142. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  1143. return false, err
  1144. }
  1145. clientKey := "id"
  1146. switch oldInbound.Protocol {
  1147. case "trojan":
  1148. clientKey = "password"
  1149. case "shadowsocks":
  1150. clientKey = "email"
  1151. case "hysteria":
  1152. clientKey = "auth"
  1153. }
  1154. wanted := make(map[string]struct{}, len(recs))
  1155. for _, rec := range recs {
  1156. if k := clientKeyForProtocol(oldInbound.Protocol, rec); k != "" {
  1157. wanted[k] = struct{}{}
  1158. }
  1159. }
  1160. interfaceClients, ok := settings["clients"].([]any)
  1161. if !ok {
  1162. return false, common.NewError("invalid clients format in inbound settings")
  1163. }
  1164. type removedClient struct {
  1165. email string
  1166. needApiDel bool
  1167. }
  1168. removed := make([]removedClient, 0, len(wanted))
  1169. newClients := make([]any, 0, len(interfaceClients))
  1170. for _, client := range interfaceClients {
  1171. c, ok := client.(map[string]any)
  1172. if !ok {
  1173. newClients = append(newClients, client)
  1174. continue
  1175. }
  1176. cid, _ := c[clientKey].(string)
  1177. if _, hit := wanted[cid]; hit && cid != "" {
  1178. email, _ := c["email"].(string)
  1179. enable, _ := c["enable"].(bool)
  1180. removed = append(removed, removedClient{email: email, needApiDel: enable})
  1181. continue
  1182. }
  1183. newClients = append(newClients, client)
  1184. }
  1185. if len(removed) == 0 {
  1186. return false, nil
  1187. }
  1188. db := database.GetDB()
  1189. newClients = compactOrphans(db, newClients)
  1190. if newClients == nil {
  1191. newClients = []any{}
  1192. }
  1193. settings["clients"] = newClients
  1194. newSettings, err := json.MarshalIndent(settings, "", " ")
  1195. if err != nil {
  1196. return false, err
  1197. }
  1198. oldInbound.Settings = string(newSettings)
  1199. var sharedSet map[string]bool
  1200. if !keepTraffic {
  1201. removedEmails := make([]string, 0, len(removed))
  1202. for _, r := range removed {
  1203. if r.email != "" {
  1204. removedEmails = append(removedEmails, r.email)
  1205. }
  1206. }
  1207. var sharedErr error
  1208. sharedSet, sharedErr = inboundSvc.emailsUsedByOtherInbounds(removedEmails, inboundId)
  1209. if sharedErr != nil {
  1210. return false, sharedErr
  1211. }
  1212. }
  1213. needRestart := false
  1214. markDirty := false
  1215. for _, r := range removed {
  1216. email := r.email
  1217. emailShared := sharedSet[strings.ToLower(strings.TrimSpace(email))]
  1218. if !emailShared && !keepTraffic {
  1219. if err := inboundSvc.DelClientIPs(db, email); err != nil {
  1220. logger.Error("Error in delete client IPs")
  1221. return needRestart, err
  1222. }
  1223. }
  1224. if len(email) > 0 {
  1225. var enables []bool
  1226. if err := db.Model(xray.ClientTraffic{}).Where("email = ?", email).Limit(1).Pluck("enable", &enables).Error; err != nil {
  1227. logger.Error("Get stats error")
  1228. return needRestart, err
  1229. }
  1230. notDepleted := len(enables) > 0 && enables[0]
  1231. if !emailShared && !keepTraffic {
  1232. if err := inboundSvc.DelClientStat(db, email); err != nil {
  1233. logger.Error("Delete stats Data Error")
  1234. return needRestart, err
  1235. }
  1236. }
  1237. if r.needApiDel && notDepleted && oldInbound.NodeID == nil {
  1238. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  1239. if rterr != nil {
  1240. needRestart = true
  1241. } else if err1 := rt.RemoveUser(context.Background(), oldInbound, email); err1 != nil {
  1242. if !strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  1243. needRestart = true
  1244. }
  1245. }
  1246. }
  1247. }
  1248. if oldInbound.NodeID != nil && len(email) > 0 {
  1249. rt, push, dirty, perr := inboundSvc.nodePushPlan(oldInbound)
  1250. if perr != nil {
  1251. return needRestart, perr
  1252. }
  1253. if dirty {
  1254. markDirty = true
  1255. }
  1256. if push {
  1257. if err1 := rt.DeleteUser(context.Background(), oldInbound, email); err1 != nil {
  1258. logger.Warning("Error in deleting client on", rt.Name(), ":", err1)
  1259. markDirty = true
  1260. }
  1261. }
  1262. }
  1263. }
  1264. if err := db.Save(oldInbound).Error; err != nil {
  1265. return needRestart, err
  1266. }
  1267. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  1268. if gcErr != nil {
  1269. return needRestart, gcErr
  1270. }
  1271. if err := s.SyncInbound(db, inboundId, finalClients); err != nil {
  1272. return needRestart, err
  1273. }
  1274. if markDirty && oldInbound.NodeID != nil {
  1275. if dErr := (&NodeService{}).MarkNodeDirty(*oldInbound.NodeID); dErr != nil {
  1276. logger.Warning("mark node dirty failed:", dErr)
  1277. }
  1278. }
  1279. return needRestart, nil
  1280. }
  1281. func (s *ClientService) DetachByEmailMany(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  1282. if email == "" {
  1283. return false, common.NewError("client email is required")
  1284. }
  1285. rec, err := s.GetRecordByEmail(nil, email)
  1286. if err != nil {
  1287. return false, err
  1288. }
  1289. return s.Detach(inboundSvc, rec.Id, inboundIds)
  1290. }
  1291. func (s *ClientService) DeleteByEmail(inboundSvc *InboundService, email string, keepTraffic bool) (bool, error) {
  1292. if email == "" {
  1293. return false, common.NewError("client email is required")
  1294. }
  1295. rec, err := s.GetRecordByEmail(nil, email)
  1296. if err == nil {
  1297. return s.Delete(inboundSvc, rec.Id, keepTraffic)
  1298. }
  1299. if !errors.Is(err, gorm.ErrRecordNotFound) {
  1300. return false, err
  1301. }
  1302. inboundIds, idsErr := s.findInboundIdsByClientEmail(email)
  1303. if idsErr != nil {
  1304. return false, idsErr
  1305. }
  1306. if len(inboundIds) == 0 {
  1307. return false, common.NewError(fmt.Sprintf("client %q not found in any inbound or client record", email))
  1308. }
  1309. needRestart := false
  1310. for _, ibId := range inboundIds {
  1311. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, email, false)
  1312. if delErr != nil {
  1313. return needRestart, delErr
  1314. }
  1315. if nr {
  1316. needRestart = true
  1317. }
  1318. }
  1319. if !keepTraffic {
  1320. db := database.GetDB()
  1321. if err := db.Where("email = ?", email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  1322. return needRestart, err
  1323. }
  1324. if err := db.Where("client_email = ?", email).Delete(&model.InboundClientIps{}).Error; err != nil {
  1325. return needRestart, err
  1326. }
  1327. }
  1328. return needRestart, nil
  1329. }
  1330. // findInboundIdsByClientEmail returns every inbound whose settings.clients[]
  1331. // JSON contains an entry with the given email. Driver-portable (no JSON
  1332. // operators) by parsing in Go — fine for the rare fallback path.
  1333. func (s *ClientService) findInboundIdsByClientEmail(email string) ([]int, error) {
  1334. var inbounds []model.Inbound
  1335. if err := database.GetDB().
  1336. Select("id, settings").
  1337. Where("settings LIKE ?", "%"+email+"%").
  1338. Find(&inbounds).Error; err != nil {
  1339. return nil, err
  1340. }
  1341. out := make([]int, 0, len(inbounds))
  1342. for _, ib := range inbounds {
  1343. var settings map[string]any
  1344. if err := json.Unmarshal([]byte(ib.Settings), &settings); err != nil {
  1345. continue
  1346. }
  1347. clients, ok := settings["clients"].([]any)
  1348. if !ok {
  1349. continue
  1350. }
  1351. for _, c := range clients {
  1352. cm, ok := c.(map[string]any)
  1353. if !ok {
  1354. continue
  1355. }
  1356. if cEmail, _ := cm["email"].(string); cEmail == email {
  1357. out = append(out, ib.Id)
  1358. break
  1359. }
  1360. }
  1361. }
  1362. return out, nil
  1363. }
  1364. func (s *ClientService) UpdateByEmail(inboundSvc *InboundService, email string, updated model.Client, inboundFilter ...int) (bool, error) {
  1365. if email == "" {
  1366. return false, common.NewError("client email is required")
  1367. }
  1368. rec, err := s.GetRecordByEmail(nil, email)
  1369. if err != nil {
  1370. return false, err
  1371. }
  1372. return s.Update(inboundSvc, rec.Id, updated, inboundFilter...)
  1373. }
  1374. func (s *ClientService) ResetTrafficByEmail(inboundSvc *InboundService, email string) (bool, error) {
  1375. if email == "" {
  1376. return false, common.NewError("client email is required")
  1377. }
  1378. rec, err := s.GetRecordByEmail(nil, email)
  1379. if err != nil {
  1380. return false, err
  1381. }
  1382. inboundIds, err := s.GetInboundIdsForRecord(rec.Id)
  1383. if err != nil {
  1384. return false, err
  1385. }
  1386. needRestart := false
  1387. if !rec.Enable {
  1388. updated := rec.ToClient()
  1389. updated.Enable = true
  1390. nr, uErr := s.Update(inboundSvc, rec.Id, *updated)
  1391. if uErr != nil {
  1392. logger.Warning("Failed to auto-enable client during traffic reset:", uErr)
  1393. }
  1394. if nr {
  1395. needRestart = true
  1396. }
  1397. }
  1398. if len(inboundIds) == 0 {
  1399. if rErr := inboundSvc.ResetClientTrafficByEmail(email); rErr != nil {
  1400. return false, rErr
  1401. }
  1402. return needRestart, nil
  1403. }
  1404. for _, ibId := range inboundIds {
  1405. nr, rErr := inboundSvc.ResetClientTraffic(ibId, email)
  1406. if rErr != nil {
  1407. return needRestart, rErr
  1408. }
  1409. if nr {
  1410. needRestart = true
  1411. }
  1412. }
  1413. return needRestart, nil
  1414. }
  1415. // ClientSlim is the row-shape used by the clients page. It drops fields the
  1416. // table never reads (UUID, password, auth, flow, security, reverse, tgId)
  1417. // so the list payload stays compact even when the panel manages thousands
  1418. // of clients. Modals that need the full record still call /get/:email.
  1419. type ClientSlim struct {
  1420. Email string `json:"email"`
  1421. SubID string `json:"subId"`
  1422. Enable bool `json:"enable"`
  1423. TotalGB int64 `json:"totalGB"`
  1424. ExpiryTime int64 `json:"expiryTime"`
  1425. LimitIP int `json:"limitIp"`
  1426. Reset int `json:"reset"`
  1427. Group string `json:"group,omitempty"`
  1428. Comment string `json:"comment,omitempty"`
  1429. InboundIds []int `json:"inboundIds"`
  1430. Traffic *xray.ClientTraffic `json:"traffic,omitempty"`
  1431. CreatedAt int64 `json:"createdAt"`
  1432. UpdatedAt int64 `json:"updatedAt"`
  1433. }
  1434. // ClientPageParams are the query params accepted by /panel/api/clients/list/paged.
  1435. // All fields are optional — the empty value means "no filter" / defaults.
  1436. //
  1437. // Filter / Protocol / Inbound accept either a single value or a comma-separated
  1438. // list; matching is OR within a field and AND across fields. The numeric range
  1439. // fields treat 0 as "unset" on the lower bound and 0 (or negative) as
  1440. // "unbounded" on the upper bound.
  1441. type ClientPageParams struct {
  1442. Page int `form:"page"`
  1443. PageSize int `form:"pageSize"`
  1444. Search string `form:"search"`
  1445. Filter string `form:"filter"`
  1446. Protocol string `form:"protocol"`
  1447. Inbound string `form:"inbound"`
  1448. Sort string `form:"sort"`
  1449. Order string `form:"order"`
  1450. ExpiryFrom int64 `form:"expiryFrom"`
  1451. ExpiryTo int64 `form:"expiryTo"`
  1452. UsageFrom int64 `form:"usageFrom"`
  1453. UsageTo int64 `form:"usageTo"`
  1454. AutoRenew string `form:"autoRenew"`
  1455. HasTgID string `form:"hasTgId"`
  1456. HasComment string `form:"hasComment"`
  1457. Group string `form:"group"`
  1458. }
  1459. // ClientPageResponse is the shape returned by ListPaged. `Total` is the
  1460. // row count in the DB; `Filtered` is the count after Search/Filter/Protocol
  1461. // were applied, before pagination. The page contains at most PageSize items.
  1462. // Summary is computed across the full DB row set so dashboard counters
  1463. // on the clients page stay stable as the user paginates/filters.
  1464. type ClientPageResponse struct {
  1465. Items []ClientSlim `json:"items"`
  1466. Total int `json:"total"`
  1467. Filtered int `json:"filtered"`
  1468. Page int `json:"page"`
  1469. PageSize int `json:"pageSize"`
  1470. Summary ClientsSummary `json:"summary"`
  1471. Groups []string `json:"groups"`
  1472. }
  1473. // ClientsSummary collects per-bucket counts plus the matching email lists so
  1474. // the clients page can render the dashboard stat cards and their hover
  1475. // popovers without shipping the full client array.
  1476. type ClientsSummary struct {
  1477. Total int `json:"total"`
  1478. Active int `json:"active"`
  1479. Online []string `json:"online"`
  1480. Depleted []string `json:"depleted"`
  1481. Expiring []string `json:"expiring"`
  1482. Deactive []string `json:"deactive"`
  1483. }
  1484. const (
  1485. clientPageDefaultSize = 25
  1486. clientPageMaxSize = 200
  1487. )
  1488. // ListPaged loads every client (with traffic + attachments) into memory,
  1489. // applies the requested filter / search / protocol predicates, sorts, and
  1490. // returns the requested page along with total and filtered counts. The DB
  1491. // query itself is unchanged from List(); the win is that the response
  1492. // only carries 25-ish slim rows over the wire instead of all 2000 full
  1493. // records, which on real panels was the dominant cost.
  1494. func (s *ClientService) ListPaged(inboundSvc *InboundService, settingSvc *SettingService, params ClientPageParams) (*ClientPageResponse, error) {
  1495. all, err := s.List()
  1496. if err != nil {
  1497. return nil, err
  1498. }
  1499. total := len(all)
  1500. pageSize := params.PageSize
  1501. if pageSize <= 0 {
  1502. pageSize = clientPageDefaultSize
  1503. }
  1504. if pageSize > clientPageMaxSize {
  1505. pageSize = clientPageMaxSize
  1506. }
  1507. page := params.Page
  1508. if page <= 0 {
  1509. page = 1
  1510. }
  1511. protocols := parseCSVStrings(params.Protocol)
  1512. inboundIDs := parseCSVInts(params.Inbound)
  1513. buckets := parseCSVStrings(params.Filter)
  1514. var protocolByInbound map[int]string
  1515. if len(protocols) > 0 {
  1516. inbounds, err := inboundSvc.GetAllInbounds()
  1517. if err == nil {
  1518. protocolByInbound = make(map[int]string, len(inbounds))
  1519. for _, ib := range inbounds {
  1520. protocolByInbound[ib.Id] = string(ib.Protocol)
  1521. }
  1522. }
  1523. }
  1524. onlines := inboundSvc.GetOnlineClients()
  1525. onlineSet := make(map[string]struct{}, len(onlines))
  1526. for _, e := range onlines {
  1527. onlineSet[e] = struct{}{}
  1528. }
  1529. var expireDiffMs, trafficDiffBytes int64
  1530. if settingSvc != nil {
  1531. if v, err := settingSvc.GetExpireDiff(); err == nil {
  1532. expireDiffMs = int64(v) * 86400000
  1533. }
  1534. if v, err := settingSvc.GetTrafficDiff(); err == nil {
  1535. trafficDiffBytes = int64(v) * 1073741824
  1536. }
  1537. }
  1538. nowMs := time.Now().UnixMilli()
  1539. summary := buildClientsSummary(all, onlineSet, nowMs, expireDiffMs, trafficDiffBytes)
  1540. needle := strings.ToLower(strings.TrimSpace(params.Search))
  1541. filtered := make([]ClientWithAttachments, 0, len(all))
  1542. for _, c := range all {
  1543. if needle != "" && !clientMatchesSearch(c, needle) {
  1544. continue
  1545. }
  1546. if len(protocols) > 0 && !clientMatchesAnyProtocol(c, protocols, protocolByInbound) {
  1547. continue
  1548. }
  1549. if len(inboundIDs) > 0 && !clientMatchesAnyInbound(c, inboundIDs) {
  1550. continue
  1551. }
  1552. if len(buckets) > 0 && !clientMatchesAnyBucket(c, buckets, onlineSet, nowMs, expireDiffMs, trafficDiffBytes) {
  1553. continue
  1554. }
  1555. if !clientMatchesExpiryRange(c, params.ExpiryFrom, params.ExpiryTo) {
  1556. continue
  1557. }
  1558. if !clientMatchesUsageRange(c, params.UsageFrom, params.UsageTo) {
  1559. continue
  1560. }
  1561. if !clientMatchesAutoRenew(c, params.AutoRenew) {
  1562. continue
  1563. }
  1564. if !clientMatchesHasTgID(c, params.HasTgID) {
  1565. continue
  1566. }
  1567. if !clientMatchesHasComment(c, params.HasComment) {
  1568. continue
  1569. }
  1570. if !clientMatchesAnyGroup(c, params.Group) {
  1571. continue
  1572. }
  1573. filtered = append(filtered, c)
  1574. }
  1575. sortClients(filtered, params.Sort, params.Order)
  1576. filteredCount := len(filtered)
  1577. start := (page - 1) * pageSize
  1578. end := start + pageSize
  1579. if start > filteredCount {
  1580. start = filteredCount
  1581. }
  1582. if end > filteredCount {
  1583. end = filteredCount
  1584. }
  1585. pageRows := filtered[start:end]
  1586. items := make([]ClientSlim, 0, len(pageRows))
  1587. for _, c := range pageRows {
  1588. items = append(items, toClientSlim(c))
  1589. }
  1590. groupRows, gErr := s.ListGroups()
  1591. if gErr != nil {
  1592. return nil, gErr
  1593. }
  1594. groups := make([]string, 0, len(groupRows))
  1595. for _, g := range groupRows {
  1596. groups = append(groups, g.Name)
  1597. }
  1598. return &ClientPageResponse{
  1599. Items: items,
  1600. Total: total,
  1601. Filtered: filteredCount,
  1602. Page: page,
  1603. PageSize: pageSize,
  1604. Summary: summary,
  1605. Groups: groups,
  1606. }, nil
  1607. }
  1608. type GroupSummary struct {
  1609. Name string `json:"name"`
  1610. ClientCount int `json:"clientCount"`
  1611. TrafficUsed int64 `json:"trafficUsed"`
  1612. }
  1613. func (s *ClientService) ListGroups() ([]GroupSummary, error) {
  1614. db := database.GetDB()
  1615. // email is unique in both clients and client_traffics, so the LEFT JOIN
  1616. // never double-counts a client's traffic.
  1617. var derived []GroupSummary
  1618. if err := db.Table("clients AS c").
  1619. Select("c.group_name AS name, COUNT(*) AS client_count, COALESCE(SUM(ct.up + ct.down), 0) AS traffic_used").
  1620. Joins("LEFT JOIN client_traffics ct ON ct.email = c.email").
  1621. Where("c.group_name <> ''").
  1622. Group("c.group_name").
  1623. Scan(&derived).Error; err != nil {
  1624. return nil, err
  1625. }
  1626. var stored []model.ClientGroup
  1627. if err := db.Find(&stored).Error; err != nil {
  1628. return nil, err
  1629. }
  1630. type groupAgg struct {
  1631. count int
  1632. traffic int64
  1633. }
  1634. merged := make(map[string]groupAgg, len(derived)+len(stored))
  1635. for _, g := range stored {
  1636. merged[g.Name] = groupAgg{}
  1637. }
  1638. for _, g := range derived {
  1639. merged[g.Name] = groupAgg{count: g.ClientCount, traffic: g.TrafficUsed}
  1640. }
  1641. out := make([]GroupSummary, 0, len(merged))
  1642. for name, agg := range merged {
  1643. out = append(out, GroupSummary{Name: name, ClientCount: agg.count, TrafficUsed: agg.traffic})
  1644. }
  1645. sort.Slice(out, func(i, j int) bool {
  1646. return strings.ToLower(out[i].Name) < strings.ToLower(out[j].Name)
  1647. })
  1648. return out, nil
  1649. }
  1650. func (s *ClientService) EmailsByGroup(name string) ([]string, error) {
  1651. name = strings.TrimSpace(name)
  1652. if name == "" {
  1653. return []string{}, nil
  1654. }
  1655. db := database.GetDB()
  1656. var emails []string
  1657. if err := db.Model(&model.ClientRecord{}).
  1658. Where("group_name = ?", name).
  1659. Order("email ASC").
  1660. Pluck("email", &emails).Error; err != nil {
  1661. return nil, err
  1662. }
  1663. if emails == nil {
  1664. emails = []string{}
  1665. }
  1666. return emails, nil
  1667. }
  1668. func (s *ClientService) BulkResetTraffic(inboundSvc *InboundService, emails []string) (int, error) {
  1669. if len(emails) == 0 {
  1670. return 0, nil
  1671. }
  1672. seen := map[string]struct{}{}
  1673. cleanEmails := make([]string, 0, len(emails))
  1674. for _, e := range emails {
  1675. e = strings.TrimSpace(e)
  1676. if e == "" {
  1677. continue
  1678. }
  1679. if _, ok := seen[e]; ok {
  1680. continue
  1681. }
  1682. seen[e] = struct{}{}
  1683. cleanEmails = append(cleanEmails, e)
  1684. }
  1685. if len(cleanEmails) == 0 {
  1686. return 0, nil
  1687. }
  1688. for _, e := range cleanEmails {
  1689. rec, err := s.GetRecordByEmail(nil, e)
  1690. if err == nil && !rec.Enable {
  1691. updated := rec.ToClient()
  1692. updated.Enable = true
  1693. s.Update(inboundSvc, rec.Id, *updated)
  1694. }
  1695. }
  1696. affected := 0
  1697. err := submitTrafficWrite(func() error {
  1698. db := database.GetDB()
  1699. return db.Transaction(func(tx *gorm.DB) error {
  1700. for _, batch := range chunkStrings(cleanEmails, sqlInChunk) {
  1701. res := tx.Model(xray.ClientTraffic{}).
  1702. Where("email IN ?", batch).
  1703. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  1704. if res.Error != nil {
  1705. return res.Error
  1706. }
  1707. affected += int(res.RowsAffected)
  1708. }
  1709. return nil
  1710. })
  1711. })
  1712. if err != nil {
  1713. return 0, err
  1714. }
  1715. return affected, nil
  1716. }
  1717. func (s *ClientService) CreateGroup(name string) error {
  1718. name = strings.TrimSpace(name)
  1719. if name == "" {
  1720. return common.NewError("group name is required")
  1721. }
  1722. db := database.GetDB()
  1723. var count int64
  1724. if err := db.Model(&model.ClientGroup{}).Where("name = ?", name).Count(&count).Error; err != nil {
  1725. return err
  1726. }
  1727. if count > 0 {
  1728. return common.NewError("group already exists")
  1729. }
  1730. return db.Create(&model.ClientGroup{Name: name}).Error
  1731. }
  1732. func (s *ClientService) RenameGroup(oldName, newName string) (int, error) {
  1733. oldName = strings.TrimSpace(oldName)
  1734. newName = strings.TrimSpace(newName)
  1735. if oldName == "" {
  1736. return 0, common.NewError("old group name is required")
  1737. }
  1738. if newName == "" {
  1739. return 0, common.NewError("new group name is required")
  1740. }
  1741. if oldName == newName {
  1742. return 0, nil
  1743. }
  1744. return s.replaceGroupValue(oldName, newName)
  1745. }
  1746. func (s *ClientService) DeleteGroup(name string) (int, error) {
  1747. name = strings.TrimSpace(name)
  1748. if name == "" {
  1749. return 0, common.NewError("group name is required")
  1750. }
  1751. return s.replaceGroupValue(name, "")
  1752. }
  1753. func (s *ClientService) RemoveFromGroup(emails []string) (int, error) {
  1754. return s.AddToGroup(emails, "")
  1755. }
  1756. func (s *ClientService) AddToGroup(emails []string, group string) (int, error) {
  1757. group = strings.TrimSpace(group)
  1758. if len(emails) == 0 {
  1759. return 0, nil
  1760. }
  1761. db := database.GetDB()
  1762. if group != "" {
  1763. var exists int64
  1764. if err := db.Model(&model.ClientGroup{}).Where("name = ?", group).Count(&exists).Error; err != nil {
  1765. return 0, err
  1766. }
  1767. if exists == 0 {
  1768. var derived int64
  1769. if err := db.Model(&model.ClientRecord{}).Where("group_name = ?", group).Count(&derived).Error; err != nil {
  1770. return 0, err
  1771. }
  1772. if derived == 0 {
  1773. if err := db.Create(&model.ClientGroup{Name: group}).Error; err != nil {
  1774. return 0, err
  1775. }
  1776. }
  1777. }
  1778. }
  1779. var records []model.ClientRecord
  1780. for _, batch := range chunkStrings(emails, sqlInChunk) {
  1781. var rows []model.ClientRecord
  1782. if err := db.Where("email IN ?", batch).Find(&rows).Error; err != nil {
  1783. return 0, err
  1784. }
  1785. records = append(records, rows...)
  1786. }
  1787. if len(records) == 0 {
  1788. return 0, nil
  1789. }
  1790. affectedEmails := make([]string, 0, len(records))
  1791. for _, r := range records {
  1792. affectedEmails = append(affectedEmails, r.Email)
  1793. }
  1794. tx := db.Begin()
  1795. for _, batch := range chunkStrings(affectedEmails, sqlInChunk) {
  1796. if err := tx.Model(&model.ClientRecord{}).
  1797. Where("email IN ?", batch).
  1798. UpdateColumn("group_name", group).Error; err != nil {
  1799. tx.Rollback()
  1800. return 0, err
  1801. }
  1802. }
  1803. var inboundIDs []int
  1804. inboundIDSeen := make(map[int]struct{})
  1805. for _, batch := range chunkStrings(affectedEmails, sqlInChunk) {
  1806. var ids []int
  1807. if err := tx.Table("client_inbounds").
  1808. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  1809. Where("clients.email IN ?", batch).
  1810. Distinct("client_inbounds.inbound_id").
  1811. Pluck("inbound_id", &ids).Error; err != nil {
  1812. tx.Rollback()
  1813. return 0, err
  1814. }
  1815. for _, id := range ids {
  1816. if _, ok := inboundIDSeen[id]; !ok {
  1817. inboundIDSeen[id] = struct{}{}
  1818. inboundIDs = append(inboundIDs, id)
  1819. }
  1820. }
  1821. }
  1822. emailSet := make(map[string]struct{}, len(affectedEmails))
  1823. for _, e := range affectedEmails {
  1824. emailSet[e] = struct{}{}
  1825. }
  1826. for _, ibID := range inboundIDs {
  1827. var ib model.Inbound
  1828. if err := tx.First(&ib, ibID).Error; err != nil {
  1829. tx.Rollback()
  1830. return 0, err
  1831. }
  1832. var settings map[string]any
  1833. if err := json.Unmarshal([]byte(ib.Settings), &settings); err != nil {
  1834. continue
  1835. }
  1836. clients, ok := settings["clients"].([]any)
  1837. if !ok {
  1838. continue
  1839. }
  1840. modified := false
  1841. for i := range clients {
  1842. cm, ok := clients[i].(map[string]any)
  1843. if !ok {
  1844. continue
  1845. }
  1846. email, _ := cm["email"].(string)
  1847. if _, hit := emailSet[email]; !hit {
  1848. continue
  1849. }
  1850. if group == "" {
  1851. delete(cm, "group")
  1852. } else {
  1853. cm["group"] = group
  1854. }
  1855. clients[i] = cm
  1856. modified = true
  1857. }
  1858. if modified {
  1859. settings["clients"] = clients
  1860. newSettings, err := json.Marshal(settings)
  1861. if err != nil {
  1862. continue
  1863. }
  1864. ib.Settings = string(newSettings)
  1865. if err := tx.Save(&ib).Error; err != nil {
  1866. tx.Rollback()
  1867. return 0, err
  1868. }
  1869. }
  1870. }
  1871. if err := tx.Commit().Error; err != nil {
  1872. return 0, err
  1873. }
  1874. return len(records), nil
  1875. }
  1876. func (s *ClientService) replaceGroupValue(oldName, newName string) (int, error) {
  1877. db := database.GetDB()
  1878. if newName == "" {
  1879. if err := db.Where("name = ?", oldName).Delete(&model.ClientGroup{}).Error; err != nil {
  1880. return 0, err
  1881. }
  1882. } else {
  1883. if err := db.Model(&model.ClientGroup{}).Where("name = ?", oldName).Update("name", newName).Error; err != nil {
  1884. return 0, err
  1885. }
  1886. }
  1887. var records []model.ClientRecord
  1888. if err := db.Where("group_name = ?", oldName).Find(&records).Error; err != nil {
  1889. return 0, err
  1890. }
  1891. if len(records) == 0 {
  1892. return 0, nil
  1893. }
  1894. affectedEmails := make([]string, 0, len(records))
  1895. for _, r := range records {
  1896. affectedEmails = append(affectedEmails, r.Email)
  1897. }
  1898. tx := db.Begin()
  1899. if err := tx.Model(&model.ClientRecord{}).
  1900. Where("group_name = ?", oldName).
  1901. UpdateColumn("group_name", newName).Error; err != nil {
  1902. tx.Rollback()
  1903. return 0, err
  1904. }
  1905. var inboundIDs []int
  1906. inboundIDSeen := make(map[int]struct{})
  1907. for _, batch := range chunkStrings(affectedEmails, sqlInChunk) {
  1908. var ids []int
  1909. if err := tx.Table("client_inbounds").
  1910. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  1911. Where("clients.email IN ?", batch).
  1912. Distinct("client_inbounds.inbound_id").
  1913. Pluck("inbound_id", &ids).Error; err != nil {
  1914. tx.Rollback()
  1915. return 0, err
  1916. }
  1917. for _, id := range ids {
  1918. if _, ok := inboundIDSeen[id]; !ok {
  1919. inboundIDSeen[id] = struct{}{}
  1920. inboundIDs = append(inboundIDs, id)
  1921. }
  1922. }
  1923. }
  1924. for _, ibID := range inboundIDs {
  1925. var ib model.Inbound
  1926. if err := tx.First(&ib, ibID).Error; err != nil {
  1927. tx.Rollback()
  1928. return 0, err
  1929. }
  1930. var settings map[string]any
  1931. if err := json.Unmarshal([]byte(ib.Settings), &settings); err != nil {
  1932. continue
  1933. }
  1934. clients, ok := settings["clients"].([]any)
  1935. if !ok {
  1936. continue
  1937. }
  1938. modified := false
  1939. for i := range clients {
  1940. cm, ok := clients[i].(map[string]any)
  1941. if !ok {
  1942. continue
  1943. }
  1944. if g, ok := cm["group"].(string); ok && g == oldName {
  1945. if newName == "" {
  1946. delete(cm, "group")
  1947. } else {
  1948. cm["group"] = newName
  1949. }
  1950. clients[i] = cm
  1951. modified = true
  1952. }
  1953. }
  1954. if modified {
  1955. settings["clients"] = clients
  1956. newSettings, err := json.Marshal(settings)
  1957. if err != nil {
  1958. continue
  1959. }
  1960. ib.Settings = string(newSettings)
  1961. if err := tx.Save(&ib).Error; err != nil {
  1962. tx.Rollback()
  1963. return 0, err
  1964. }
  1965. }
  1966. }
  1967. if err := tx.Commit().Error; err != nil {
  1968. return 0, err
  1969. }
  1970. return len(records), nil
  1971. }
  1972. func buildClientsSummary(all []ClientWithAttachments, onlineSet map[string]struct{}, nowMs, expireDiffMs, trafficDiffBytes int64) ClientsSummary {
  1973. s := ClientsSummary{
  1974. Total: len(all),
  1975. Online: []string{},
  1976. Depleted: []string{},
  1977. Expiring: []string{},
  1978. Deactive: []string{},
  1979. }
  1980. for _, c := range all {
  1981. used := int64(0)
  1982. if c.Traffic != nil {
  1983. used = c.Traffic.Up + c.Traffic.Down
  1984. }
  1985. exhausted := c.TotalGB > 0 && used >= c.TotalGB
  1986. expired := c.ExpiryTime > 0 && c.ExpiryTime <= nowMs
  1987. if c.Enable {
  1988. if _, ok := onlineSet[c.Email]; ok {
  1989. s.Online = append(s.Online, c.Email)
  1990. }
  1991. }
  1992. if exhausted || expired {
  1993. s.Depleted = append(s.Depleted, c.Email)
  1994. continue
  1995. }
  1996. if !c.Enable {
  1997. s.Deactive = append(s.Deactive, c.Email)
  1998. continue
  1999. }
  2000. nearExpiry := c.ExpiryTime > 0 && c.ExpiryTime-nowMs < expireDiffMs
  2001. nearLimit := c.TotalGB > 0 && c.TotalGB-used < trafficDiffBytes
  2002. if nearExpiry || nearLimit {
  2003. s.Expiring = append(s.Expiring, c.Email)
  2004. } else {
  2005. s.Active++
  2006. }
  2007. }
  2008. return s
  2009. }
  2010. func toClientSlim(c ClientWithAttachments) ClientSlim {
  2011. return ClientSlim{
  2012. Email: c.Email,
  2013. SubID: c.SubID,
  2014. Enable: c.Enable,
  2015. TotalGB: c.TotalGB,
  2016. ExpiryTime: c.ExpiryTime,
  2017. LimitIP: c.LimitIP,
  2018. Reset: c.Reset,
  2019. Group: c.Group,
  2020. Comment: c.Comment,
  2021. InboundIds: c.InboundIds,
  2022. Traffic: c.Traffic,
  2023. CreatedAt: c.CreatedAt,
  2024. UpdatedAt: c.UpdatedAt,
  2025. }
  2026. }
  2027. func clientMatchesSearch(c ClientWithAttachments, needle string) bool {
  2028. if needle == "" {
  2029. return true
  2030. }
  2031. candidates := [...]string{c.Email, c.SubID, c.Comment, c.UUID, c.Password, c.Auth}
  2032. for _, v := range candidates {
  2033. if v != "" && strings.Contains(strings.ToLower(v), needle) {
  2034. return true
  2035. }
  2036. }
  2037. return false
  2038. }
  2039. // parseCSVStrings splits a comma-separated list, trims/lower-cases each item,
  2040. // and drops blanks. Returns nil when the input has no usable entries — the
  2041. // caller can then skip the predicate entirely.
  2042. func parseCSVStrings(raw string) []string {
  2043. if raw == "" {
  2044. return nil
  2045. }
  2046. parts := strings.Split(raw, ",")
  2047. out := make([]string, 0, len(parts))
  2048. for _, p := range parts {
  2049. s := strings.ToLower(strings.TrimSpace(p))
  2050. if s != "" {
  2051. out = append(out, s)
  2052. }
  2053. }
  2054. if len(out) == 0 {
  2055. return nil
  2056. }
  2057. return out
  2058. }
  2059. // parseCSVInts is parseCSVStrings for positive integer IDs; non-numeric or
  2060. // non-positive entries are silently dropped.
  2061. func parseCSVInts(raw string) []int {
  2062. if raw == "" {
  2063. return nil
  2064. }
  2065. parts := strings.Split(raw, ",")
  2066. out := make([]int, 0, len(parts))
  2067. for _, p := range parts {
  2068. s := strings.TrimSpace(p)
  2069. if s == "" {
  2070. continue
  2071. }
  2072. if n, err := strconv.Atoi(s); err == nil && n > 0 {
  2073. out = append(out, n)
  2074. }
  2075. }
  2076. if len(out) == 0 {
  2077. return nil
  2078. }
  2079. return out
  2080. }
  2081. func clientMatchesAnyProtocol(c ClientWithAttachments, protocols []string, byInbound map[int]string) bool {
  2082. for _, id := range c.InboundIds {
  2083. p := byInbound[id]
  2084. if p == "" {
  2085. continue
  2086. }
  2087. if slices.Contains(protocols, strings.ToLower(p)) {
  2088. return true
  2089. }
  2090. }
  2091. return false
  2092. }
  2093. func clientMatchesAnyInbound(c ClientWithAttachments, inboundIds []int) bool {
  2094. for _, id := range c.InboundIds {
  2095. if slices.Contains(inboundIds, id) {
  2096. return true
  2097. }
  2098. }
  2099. return false
  2100. }
  2101. func clientMatchesAnyBucket(c ClientWithAttachments, buckets []string, onlineSet map[string]struct{}, nowMs, expireDiffMs, trafficDiffBytes int64) bool {
  2102. for _, b := range buckets {
  2103. if clientMatchesBucket(c, b, onlineSet, nowMs, expireDiffMs, trafficDiffBytes) {
  2104. return true
  2105. }
  2106. }
  2107. return false
  2108. }
  2109. func clientMatchesExpiryRange(c ClientWithAttachments, fromMs, toMs int64) bool {
  2110. if fromMs <= 0 && toMs <= 0 {
  2111. return true
  2112. }
  2113. // expiryTime of 0 means "never expires"; treat it as outside any bounded
  2114. // range so users filtering by date see only clients with concrete expiries.
  2115. if c.ExpiryTime == 0 {
  2116. return false
  2117. }
  2118. // Negative expiry is the "delayed start" sentinel; same treatment as never.
  2119. if c.ExpiryTime < 0 {
  2120. return false
  2121. }
  2122. if fromMs > 0 && c.ExpiryTime < fromMs {
  2123. return false
  2124. }
  2125. if toMs > 0 && c.ExpiryTime > toMs {
  2126. return false
  2127. }
  2128. return true
  2129. }
  2130. func clientMatchesUsageRange(c ClientWithAttachments, fromBytes, toBytes int64) bool {
  2131. if fromBytes <= 0 && toBytes <= 0 {
  2132. return true
  2133. }
  2134. used := int64(0)
  2135. if c.Traffic != nil {
  2136. used = c.Traffic.Up + c.Traffic.Down
  2137. }
  2138. if fromBytes > 0 && used < fromBytes {
  2139. return false
  2140. }
  2141. if toBytes > 0 && used > toBytes {
  2142. return false
  2143. }
  2144. return true
  2145. }
  2146. func clientMatchesAutoRenew(c ClientWithAttachments, mode string) bool {
  2147. switch strings.ToLower(strings.TrimSpace(mode)) {
  2148. case "on":
  2149. return c.Reset > 0
  2150. case "off":
  2151. return c.Reset <= 0
  2152. }
  2153. return true
  2154. }
  2155. func clientMatchesHasTgID(c ClientWithAttachments, mode string) bool {
  2156. switch strings.ToLower(strings.TrimSpace(mode)) {
  2157. case "yes":
  2158. return c.TgID != 0
  2159. case "no":
  2160. return c.TgID == 0
  2161. }
  2162. return true
  2163. }
  2164. func clientMatchesHasComment(c ClientWithAttachments, mode string) bool {
  2165. switch strings.ToLower(strings.TrimSpace(mode)) {
  2166. case "yes":
  2167. return strings.TrimSpace(c.Comment) != ""
  2168. case "no":
  2169. return strings.TrimSpace(c.Comment) == ""
  2170. }
  2171. return true
  2172. }
  2173. func clientMatchesAnyGroup(c ClientWithAttachments, csv string) bool {
  2174. groups := parseCSVStrings(csv)
  2175. if len(groups) == 0 {
  2176. return true
  2177. }
  2178. current := strings.TrimSpace(c.Group)
  2179. for _, g := range groups {
  2180. if g == "" {
  2181. if current == "" {
  2182. return true
  2183. }
  2184. continue
  2185. }
  2186. if strings.EqualFold(g, current) {
  2187. return true
  2188. }
  2189. }
  2190. return false
  2191. }
  2192. func clientMatchesBucket(c ClientWithAttachments, bucket string, onlineSet map[string]struct{}, nowMs, expireDiffMs, trafficDiffBytes int64) bool {
  2193. if bucket == "" {
  2194. return true
  2195. }
  2196. used := int64(0)
  2197. if c.Traffic != nil {
  2198. used = c.Traffic.Up + c.Traffic.Down
  2199. }
  2200. exhausted := c.TotalGB > 0 && used >= c.TotalGB
  2201. expired := c.ExpiryTime > 0 && c.ExpiryTime <= nowMs
  2202. switch bucket {
  2203. case "online":
  2204. if onlineSet == nil {
  2205. return false
  2206. }
  2207. _, ok := onlineSet[c.Email]
  2208. return ok && c.Enable
  2209. case "depleted":
  2210. return exhausted || expired
  2211. case "deactive":
  2212. return !c.Enable
  2213. case "active":
  2214. return c.Enable && !exhausted && !expired
  2215. case "expiring":
  2216. if !c.Enable || exhausted || expired {
  2217. return false
  2218. }
  2219. nearExpiry := c.ExpiryTime > 0 && c.ExpiryTime-nowMs < expireDiffMs
  2220. nearLimit := c.TotalGB > 0 && c.TotalGB-used < trafficDiffBytes
  2221. return nearExpiry || nearLimit
  2222. }
  2223. return true
  2224. }
  2225. func sortClients(rows []ClientWithAttachments, sortKey, order string) {
  2226. if sortKey == "" {
  2227. return
  2228. }
  2229. desc := order == "descend"
  2230. less := func(i, j int) bool {
  2231. a, b := rows[i], rows[j]
  2232. switch sortKey {
  2233. case "enable":
  2234. if a.Enable == b.Enable {
  2235. return false
  2236. }
  2237. return !a.Enable && b.Enable
  2238. case "email":
  2239. return strings.ToLower(a.Email) < strings.ToLower(b.Email)
  2240. case "inboundIds":
  2241. return len(a.InboundIds) < len(b.InboundIds)
  2242. case "traffic":
  2243. ua := int64(0)
  2244. if a.Traffic != nil {
  2245. ua = a.Traffic.Up + a.Traffic.Down
  2246. }
  2247. ub := int64(0)
  2248. if b.Traffic != nil {
  2249. ub = b.Traffic.Up + b.Traffic.Down
  2250. }
  2251. return ua < ub
  2252. case "remaining":
  2253. ra := int64(1<<62 - 1)
  2254. if a.TotalGB > 0 {
  2255. used := int64(0)
  2256. if a.Traffic != nil {
  2257. used = a.Traffic.Up + a.Traffic.Down
  2258. }
  2259. ra = a.TotalGB - used
  2260. }
  2261. rb := int64(1<<62 - 1)
  2262. if b.TotalGB > 0 {
  2263. used := int64(0)
  2264. if b.Traffic != nil {
  2265. used = b.Traffic.Up + b.Traffic.Down
  2266. }
  2267. rb = b.TotalGB - used
  2268. }
  2269. return ra < rb
  2270. case "expiryTime":
  2271. ea := int64(1<<62 - 1)
  2272. if a.ExpiryTime > 0 {
  2273. ea = a.ExpiryTime
  2274. }
  2275. eb := int64(1<<62 - 1)
  2276. if b.ExpiryTime > 0 {
  2277. eb = b.ExpiryTime
  2278. }
  2279. return ea < eb
  2280. case "createdAt":
  2281. if a.CreatedAt == b.CreatedAt {
  2282. return a.Id < b.Id
  2283. }
  2284. return a.CreatedAt < b.CreatedAt
  2285. case "updatedAt":
  2286. if a.UpdatedAt == b.UpdatedAt {
  2287. return a.Id < b.Id
  2288. }
  2289. return a.UpdatedAt < b.UpdatedAt
  2290. case "lastOnline":
  2291. la := int64(0)
  2292. if a.Traffic != nil {
  2293. la = a.Traffic.LastOnline
  2294. }
  2295. lb := int64(0)
  2296. if b.Traffic != nil {
  2297. lb = b.Traffic.LastOnline
  2298. }
  2299. if la == lb {
  2300. return a.Id < b.Id
  2301. }
  2302. return la < lb
  2303. }
  2304. return false
  2305. }
  2306. sort.SliceStable(rows, func(i, j int) bool {
  2307. if desc {
  2308. return less(j, i)
  2309. }
  2310. return less(i, j)
  2311. })
  2312. }
  2313. // BulkAdjustResult is returned by BulkAdjust to report how many clients were
  2314. // successfully updated and which were skipped (typically because the field
  2315. // being adjusted was unlimited for that client) or failed.
  2316. type BulkAdjustResult struct {
  2317. Adjusted int `json:"adjusted"`
  2318. Skipped []BulkAdjustReport `json:"skipped,omitempty"`
  2319. }
  2320. type BulkAdjustReport struct {
  2321. Email string `json:"email"`
  2322. Reason string `json:"reason"`
  2323. }
  2324. type bulkAdjustEntry struct {
  2325. record *model.ClientRecord
  2326. applyExpiry bool
  2327. newExpiry int64
  2328. applyTotal bool
  2329. newTotal int64
  2330. }
  2331. // BulkAdjust shifts ExpiryTime by addDays (days) and TotalGB by addBytes
  2332. // for every email in the list. Clients whose corresponding field is
  2333. // unlimited (0) are skipped — bulk extend should not accidentally
  2334. // limit an unlimited client. addDays and addBytes may be negative.
  2335. //
  2336. // Like BulkDelete, the work is grouped by inbound so each inbound's
  2337. // settings JSON is parsed and written exactly once regardless of how
  2338. // many target emails it contains.
  2339. func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string, addDays int, addBytes int64) (BulkAdjustResult, bool, error) {
  2340. result := BulkAdjustResult{}
  2341. if len(emails) == 0 {
  2342. return result, false, nil
  2343. }
  2344. if addDays == 0 && addBytes == 0 {
  2345. return result, false, common.NewError("no adjustment specified")
  2346. }
  2347. addExpiryMs := int64(addDays) * 24 * 60 * 60 * 1000
  2348. seen := map[string]struct{}{}
  2349. cleanEmails := make([]string, 0, len(emails))
  2350. for _, e := range emails {
  2351. e = strings.TrimSpace(e)
  2352. if e == "" {
  2353. continue
  2354. }
  2355. if _, ok := seen[e]; ok {
  2356. continue
  2357. }
  2358. seen[e] = struct{}{}
  2359. cleanEmails = append(cleanEmails, e)
  2360. }
  2361. if len(cleanEmails) == 0 {
  2362. return result, false, nil
  2363. }
  2364. db := database.GetDB()
  2365. var records []model.ClientRecord
  2366. for _, batch := range chunkStrings(cleanEmails, sqlInChunk) {
  2367. var rows []model.ClientRecord
  2368. if err := db.Where("email IN ?", batch).Find(&rows).Error; err != nil {
  2369. return result, false, err
  2370. }
  2371. records = append(records, rows...)
  2372. }
  2373. recordsByEmail := make(map[string]*model.ClientRecord, len(records))
  2374. for i := range records {
  2375. recordsByEmail[records[i].Email] = &records[i]
  2376. }
  2377. skippedReasons := map[string]string{}
  2378. for _, email := range cleanEmails {
  2379. if _, ok := recordsByEmail[email]; !ok {
  2380. skippedReasons[email] = "client not found"
  2381. }
  2382. }
  2383. plan := map[string]*bulkAdjustEntry{}
  2384. for email, rec := range recordsByEmail {
  2385. entry := &bulkAdjustEntry{record: rec}
  2386. if addDays != 0 {
  2387. switch {
  2388. case rec.ExpiryTime == 0:
  2389. if _, exists := skippedReasons[email]; !exists {
  2390. skippedReasons[email] = "unlimited expiry"
  2391. }
  2392. case rec.ExpiryTime > 0:
  2393. next := rec.ExpiryTime + addExpiryMs
  2394. if next <= 0 {
  2395. if _, exists := skippedReasons[email]; !exists {
  2396. skippedReasons[email] = "reduction exceeds remaining time"
  2397. }
  2398. } else {
  2399. entry.applyExpiry = true
  2400. entry.newExpiry = next
  2401. }
  2402. default:
  2403. next := rec.ExpiryTime - addExpiryMs
  2404. if next >= 0 {
  2405. if _, exists := skippedReasons[email]; !exists {
  2406. skippedReasons[email] = "reduction exceeds delay window"
  2407. }
  2408. } else {
  2409. entry.applyExpiry = true
  2410. entry.newExpiry = next
  2411. }
  2412. }
  2413. }
  2414. if addBytes != 0 {
  2415. if rec.TotalGB == 0 {
  2416. if _, exists := skippedReasons[email]; !exists {
  2417. skippedReasons[email] = "unlimited traffic"
  2418. }
  2419. } else {
  2420. next := max(rec.TotalGB+addBytes, 0)
  2421. entry.applyTotal = true
  2422. entry.newTotal = next
  2423. }
  2424. }
  2425. if entry.applyExpiry || entry.applyTotal {
  2426. plan[email] = entry
  2427. }
  2428. }
  2429. if len(plan) == 0 {
  2430. for email, reason := range skippedReasons {
  2431. result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: reason})
  2432. }
  2433. return result, false, nil
  2434. }
  2435. plannedIds := make([]int, 0, len(plan))
  2436. recordIdToEmail := make(map[int]string, len(plan))
  2437. for email, entry := range plan {
  2438. plannedIds = append(plannedIds, entry.record.Id)
  2439. recordIdToEmail[entry.record.Id] = email
  2440. }
  2441. var mappings []model.ClientInbound
  2442. for _, batch := range chunkInts(plannedIds, sqlInChunk) {
  2443. var rows []model.ClientInbound
  2444. if err := db.Where("client_id IN ?", batch).Find(&rows).Error; err != nil {
  2445. return result, false, err
  2446. }
  2447. mappings = append(mappings, rows...)
  2448. }
  2449. emailsByInbound := map[int][]string{}
  2450. for _, m := range mappings {
  2451. email, ok := recordIdToEmail[m.ClientId]
  2452. if !ok {
  2453. continue
  2454. }
  2455. emailsByInbound[m.InboundId] = append(emailsByInbound[m.InboundId], email)
  2456. }
  2457. needRestart := false
  2458. for inboundId, ibEmails := range emailsByInbound {
  2459. ibRes := s.bulkAdjustInboundClients(inboundSvc, inboundId, ibEmails, plan)
  2460. if ibRes.needRestart {
  2461. needRestart = true
  2462. }
  2463. for email, reason := range ibRes.perEmailSkipped {
  2464. if _, already := skippedReasons[email]; !already {
  2465. skippedReasons[email] = reason
  2466. }
  2467. }
  2468. }
  2469. for email, entry := range plan {
  2470. if _, skipped := skippedReasons[email]; skipped {
  2471. continue
  2472. }
  2473. updates := map[string]any{}
  2474. if entry.applyExpiry {
  2475. updates["expiry_time"] = entry.newExpiry
  2476. }
  2477. if entry.applyTotal {
  2478. updates["total"] = entry.newTotal
  2479. }
  2480. if len(updates) == 0 {
  2481. continue
  2482. }
  2483. if err := db.Model(xray.ClientTraffic{}).Where("email = ?", email).Updates(updates).Error; err != nil {
  2484. if _, already := skippedReasons[email]; !already {
  2485. skippedReasons[email] = err.Error()
  2486. }
  2487. continue
  2488. }
  2489. result.Adjusted++
  2490. }
  2491. for email, reason := range skippedReasons {
  2492. result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: reason})
  2493. }
  2494. return result, needRestart, nil
  2495. }
  2496. type bulkInboundAdjustResult struct {
  2497. perEmailSkipped map[string]string
  2498. needRestart bool
  2499. }
  2500. // bulkAdjustInboundClients applies expiry/total deltas to multiple clients
  2501. // inside a single inbound's settings JSON. The xray runtime is updated
  2502. // only for remote-node inbounds; local nodes do not need a notification
  2503. // because the AddUser payload does not include totalGB/expiryTime —
  2504. // changing those fields is identity-preserving and the panel's traffic
  2505. // enforcement loop picks up the new limits from ClientTraffic directly.
  2506. func (s *ClientService) bulkAdjustInboundClients(
  2507. inboundSvc *InboundService,
  2508. inboundId int,
  2509. emails []string,
  2510. plan map[string]*bulkAdjustEntry,
  2511. ) bulkInboundAdjustResult {
  2512. res := bulkInboundAdjustResult{perEmailSkipped: map[string]string{}}
  2513. defer lockInbound(inboundId).Unlock()
  2514. oldInbound, err := inboundSvc.GetInbound(inboundId)
  2515. if err != nil {
  2516. logger.Error("Load Old Data Error")
  2517. for _, e := range emails {
  2518. res.perEmailSkipped[e] = err.Error()
  2519. }
  2520. return res
  2521. }
  2522. var settings map[string]any
  2523. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  2524. for _, e := range emails {
  2525. res.perEmailSkipped[e] = err.Error()
  2526. }
  2527. return res
  2528. }
  2529. clientKey := "id"
  2530. switch oldInbound.Protocol {
  2531. case model.Trojan:
  2532. clientKey = "password"
  2533. case model.Shadowsocks:
  2534. clientKey = "email"
  2535. case model.Hysteria:
  2536. clientKey = "auth"
  2537. }
  2538. keyToEmail := make(map[string]string, len(emails))
  2539. for _, email := range emails {
  2540. entry := plan[email]
  2541. if entry == nil {
  2542. res.perEmailSkipped[email] = "client not found"
  2543. continue
  2544. }
  2545. key := clientKeyForProtocol(oldInbound.Protocol, entry.record)
  2546. if key == "" {
  2547. res.perEmailSkipped[email] = "missing client key for protocol"
  2548. continue
  2549. }
  2550. keyToEmail[key] = email
  2551. }
  2552. interfaceClients, _ := settings["clients"].([]any)
  2553. foundEmails := map[string]bool{}
  2554. nowMs := time.Now().Unix() * 1000
  2555. for i, client := range interfaceClients {
  2556. c, ok := client.(map[string]any)
  2557. if !ok {
  2558. continue
  2559. }
  2560. cKey, _ := c[clientKey].(string)
  2561. targetEmail, found := keyToEmail[cKey]
  2562. if !found {
  2563. continue
  2564. }
  2565. entry := plan[targetEmail]
  2566. if entry.applyExpiry {
  2567. c["expiryTime"] = entry.newExpiry
  2568. }
  2569. if entry.applyTotal {
  2570. c["totalGB"] = entry.newTotal
  2571. }
  2572. c["updated_at"] = nowMs
  2573. interfaceClients[i] = c
  2574. foundEmails[targetEmail] = true
  2575. }
  2576. for _, email := range keyToEmail {
  2577. if !foundEmails[email] {
  2578. res.perEmailSkipped[email] = "Client Not Found In Inbound"
  2579. }
  2580. }
  2581. if len(foundEmails) == 0 {
  2582. return res
  2583. }
  2584. settings["clients"] = interfaceClients
  2585. newSettings, err := json.MarshalIndent(settings, "", " ")
  2586. if err != nil {
  2587. for email := range foundEmails {
  2588. res.perEmailSkipped[email] = err.Error()
  2589. }
  2590. return res
  2591. }
  2592. oldInbound.Settings = string(newSettings)
  2593. markDirty := false
  2594. if oldInbound.NodeID != nil {
  2595. rt, push, dirty, perr := inboundSvc.nodePushPlan(oldInbound)
  2596. if perr != nil {
  2597. for email := range foundEmails {
  2598. res.perEmailSkipped[email] = perr.Error()
  2599. delete(foundEmails, email)
  2600. }
  2601. } else {
  2602. if dirty {
  2603. markDirty = true
  2604. }
  2605. if push {
  2606. for email := range foundEmails {
  2607. entry := plan[email]
  2608. updated := *entry.record.ToClient()
  2609. if entry.applyExpiry {
  2610. updated.ExpiryTime = entry.newExpiry
  2611. }
  2612. if entry.applyTotal {
  2613. updated.TotalGB = entry.newTotal
  2614. }
  2615. updated.UpdatedAt = nowMs
  2616. if err1 := rt.UpdateUser(context.Background(), oldInbound, email, updated); err1 != nil {
  2617. logger.Warning("Error in updating client on", rt.Name(), ":", err1)
  2618. markDirty = true
  2619. }
  2620. }
  2621. }
  2622. }
  2623. }
  2624. db := database.GetDB()
  2625. txErr := db.Transaction(func(tx *gorm.DB) error {
  2626. if err := tx.Save(oldInbound).Error; err != nil {
  2627. return err
  2628. }
  2629. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  2630. if gcErr != nil {
  2631. return gcErr
  2632. }
  2633. return s.SyncInbound(tx, inboundId, finalClients)
  2634. })
  2635. if txErr != nil {
  2636. for email := range foundEmails {
  2637. if _, skip := res.perEmailSkipped[email]; !skip {
  2638. res.perEmailSkipped[email] = txErr.Error()
  2639. }
  2640. }
  2641. } else if markDirty && oldInbound.NodeID != nil {
  2642. if dErr := (&NodeService{}).MarkNodeDirty(*oldInbound.NodeID); dErr != nil {
  2643. logger.Warning("mark node dirty failed:", dErr)
  2644. }
  2645. }
  2646. return res
  2647. }
  2648. // BulkDeleteResult mirrors BulkAdjustResult: total deleted plus per-email
  2649. // skip reasons when an email could not be processed.
  2650. type BulkDeleteResult struct {
  2651. Deleted int `json:"deleted"`
  2652. Skipped []BulkDeleteReport `json:"skipped,omitempty"`
  2653. }
  2654. type BulkDeleteReport struct {
  2655. Email string `json:"email"`
  2656. Reason string `json:"reason"`
  2657. }
  2658. const sqlInChunk = 400
  2659. // BulkDelete removes every client in the list in one optimized pass.
  2660. // Instead of running the full single-delete pipeline N times (which would
  2661. // re-read, re-parse, and re-write each inbound's settings JSON for every
  2662. // email), it groups emails by inbound and performs a single
  2663. // read-modify-write per inbound. Per-row DB cleanups are also batched with
  2664. // IN-clause queries at the end. Errors on a particular email are recorded
  2665. // in the Skipped list and processing continues for the rest.
  2666. func (s *ClientService) BulkDelete(inboundSvc *InboundService, emails []string, keepTraffic bool) (BulkDeleteResult, bool, error) {
  2667. result := BulkDeleteResult{}
  2668. seen := map[string]struct{}{}
  2669. cleanEmails := make([]string, 0, len(emails))
  2670. for _, e := range emails {
  2671. e = strings.TrimSpace(e)
  2672. if e == "" {
  2673. continue
  2674. }
  2675. if _, ok := seen[e]; ok {
  2676. continue
  2677. }
  2678. seen[e] = struct{}{}
  2679. cleanEmails = append(cleanEmails, e)
  2680. }
  2681. if len(cleanEmails) == 0 {
  2682. return result, false, nil
  2683. }
  2684. db := database.GetDB()
  2685. var records []model.ClientRecord
  2686. for _, batch := range chunkStrings(cleanEmails, sqlInChunk) {
  2687. var rows []model.ClientRecord
  2688. if err := db.Where("email IN ?", batch).Find(&rows).Error; err != nil {
  2689. return result, false, err
  2690. }
  2691. records = append(records, rows...)
  2692. }
  2693. recordsByEmail := make(map[string]*model.ClientRecord, len(records))
  2694. tombstoneEmails := make([]string, 0, len(records))
  2695. for i := range records {
  2696. recordsByEmail[records[i].Email] = &records[i]
  2697. tombstoneEmails = append(tombstoneEmails, records[i].Email)
  2698. }
  2699. tombstoneClientEmails(tombstoneEmails)
  2700. skippedReasons := map[string]string{}
  2701. for _, email := range cleanEmails {
  2702. if _, ok := recordsByEmail[email]; !ok {
  2703. skippedReasons[email] = "client not found"
  2704. }
  2705. }
  2706. clientIds := make([]int, 0, len(recordsByEmail))
  2707. recordIdToEmail := make(map[int]string, len(recordsByEmail))
  2708. for _, r := range recordsByEmail {
  2709. clientIds = append(clientIds, r.Id)
  2710. recordIdToEmail[r.Id] = r.Email
  2711. }
  2712. emailsByInbound := map[int][]string{}
  2713. if len(clientIds) > 0 {
  2714. var mappings []model.ClientInbound
  2715. for _, batch := range chunkInts(clientIds, sqlInChunk) {
  2716. var rows []model.ClientInbound
  2717. if err := db.Where("client_id IN ?", batch).Find(&rows).Error; err != nil {
  2718. return result, false, err
  2719. }
  2720. mappings = append(mappings, rows...)
  2721. }
  2722. for _, m := range mappings {
  2723. email, ok := recordIdToEmail[m.ClientId]
  2724. if !ok {
  2725. continue
  2726. }
  2727. emailsByInbound[m.InboundId] = append(emailsByInbound[m.InboundId], email)
  2728. }
  2729. }
  2730. needRestart := false
  2731. for inboundId, ibEmails := range emailsByInbound {
  2732. ibResult := s.bulkDelInboundClients(inboundSvc, inboundId, ibEmails, recordsByEmail, false)
  2733. if ibResult.needRestart {
  2734. needRestart = true
  2735. }
  2736. for email, reason := range ibResult.perEmailSkipped {
  2737. if _, already := skippedReasons[email]; !already {
  2738. skippedReasons[email] = reason
  2739. }
  2740. }
  2741. }
  2742. successEmails := make([]string, 0, len(recordsByEmail))
  2743. successIds := make([]int, 0, len(recordsByEmail))
  2744. for email, rec := range recordsByEmail {
  2745. if _, skipped := skippedReasons[email]; skipped {
  2746. continue
  2747. }
  2748. successEmails = append(successEmails, email)
  2749. successIds = append(successIds, rec.Id)
  2750. }
  2751. if len(successIds) > 0 {
  2752. for _, batch := range chunkInts(successIds, sqlInChunk) {
  2753. if err := db.Where("client_id IN ?", batch).Delete(&model.ClientInbound{}).Error; err != nil {
  2754. return result, needRestart, err
  2755. }
  2756. }
  2757. if !keepTraffic && len(successEmails) > 0 {
  2758. for _, batch := range chunkStrings(successEmails, sqlInChunk) {
  2759. if err := db.Where("email IN ?", batch).Delete(&xray.ClientTraffic{}).Error; err != nil {
  2760. return result, needRestart, err
  2761. }
  2762. if err := db.Where("client_email IN ?", batch).Delete(&model.InboundClientIps{}).Error; err != nil {
  2763. return result, needRestart, err
  2764. }
  2765. }
  2766. }
  2767. for _, batch := range chunkInts(successIds, sqlInChunk) {
  2768. if err := db.Where("id IN ?", batch).Delete(&model.ClientRecord{}).Error; err != nil {
  2769. return result, needRestart, err
  2770. }
  2771. }
  2772. }
  2773. result.Deleted = len(successEmails)
  2774. for email, reason := range skippedReasons {
  2775. result.Skipped = append(result.Skipped, BulkDeleteReport{Email: email, Reason: reason})
  2776. }
  2777. return result, needRestart, nil
  2778. }
  2779. type bulkInboundDeleteResult struct {
  2780. perEmailSkipped map[string]string
  2781. needRestart bool
  2782. }
  2783. // bulkDelInboundClients removes multiple clients from a single inbound's
  2784. // settings JSON in one read-modify-write cycle, runs the xray runtime
  2785. // RemoveUser/DeleteUser calls, and persists the inbound. The returned map
  2786. // holds per-email failure reasons; emails not present in the map are
  2787. // considered successful for this inbound.
  2788. func (s *ClientService) bulkDelInboundClients(
  2789. inboundSvc *InboundService,
  2790. inboundId int,
  2791. emails []string,
  2792. records map[string]*model.ClientRecord,
  2793. keepTraffic bool,
  2794. ) bulkInboundDeleteResult {
  2795. res := bulkInboundDeleteResult{perEmailSkipped: map[string]string{}}
  2796. defer lockInbound(inboundId).Unlock()
  2797. oldInbound, err := inboundSvc.GetInbound(inboundId)
  2798. if err != nil {
  2799. logger.Error("Load Old Data Error")
  2800. for _, e := range emails {
  2801. res.perEmailSkipped[e] = err.Error()
  2802. }
  2803. return res
  2804. }
  2805. var settings map[string]any
  2806. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  2807. for _, e := range emails {
  2808. res.perEmailSkipped[e] = err.Error()
  2809. }
  2810. return res
  2811. }
  2812. clientKey := "id"
  2813. switch oldInbound.Protocol {
  2814. case model.Trojan:
  2815. clientKey = "password"
  2816. case model.Shadowsocks:
  2817. clientKey = "email"
  2818. case model.Hysteria:
  2819. clientKey = "auth"
  2820. }
  2821. keyToEmail := make(map[string]string, len(emails))
  2822. for _, email := range emails {
  2823. rec := records[email]
  2824. if rec == nil {
  2825. res.perEmailSkipped[email] = "client not found"
  2826. continue
  2827. }
  2828. key := clientKeyForProtocol(oldInbound.Protocol, rec)
  2829. if key == "" {
  2830. res.perEmailSkipped[email] = "missing client key for protocol"
  2831. continue
  2832. }
  2833. keyToEmail[key] = email
  2834. }
  2835. interfaceClients, _ := settings["clients"].([]any)
  2836. newClients := make([]any, 0, len(interfaceClients))
  2837. foundEmails := map[string]bool{}
  2838. enableByEmail := map[string]bool{}
  2839. for _, client := range interfaceClients {
  2840. c, ok := client.(map[string]any)
  2841. if !ok {
  2842. newClients = append(newClients, client)
  2843. continue
  2844. }
  2845. cKey, _ := c[clientKey].(string)
  2846. if targetEmail, found := keyToEmail[cKey]; found {
  2847. foundEmails[targetEmail] = true
  2848. if em, _ := c["email"].(string); em != "" {
  2849. en, _ := c["enable"].(bool)
  2850. enableByEmail[em] = en
  2851. }
  2852. continue
  2853. }
  2854. newClients = append(newClients, client)
  2855. }
  2856. for _, email := range keyToEmail {
  2857. if !foundEmails[email] {
  2858. res.perEmailSkipped[email] = "Client Not Found In Inbound"
  2859. }
  2860. }
  2861. db := database.GetDB()
  2862. newClients = compactOrphans(db, newClients)
  2863. if newClients == nil {
  2864. newClients = []any{}
  2865. }
  2866. settings["clients"] = newClients
  2867. newSettings, err := json.MarshalIndent(settings, "", " ")
  2868. if err != nil {
  2869. for email := range foundEmails {
  2870. if _, skip := res.perEmailSkipped[email]; !skip {
  2871. res.perEmailSkipped[email] = err.Error()
  2872. }
  2873. }
  2874. return res
  2875. }
  2876. oldInbound.Settings = string(newSettings)
  2877. foundList := make([]string, 0, len(foundEmails))
  2878. for email := range foundEmails {
  2879. foundList = append(foundList, email)
  2880. }
  2881. notDepletedByEmail := map[string]bool{}
  2882. if len(foundList) > 0 {
  2883. type trafficRow struct {
  2884. Email string
  2885. Enable bool
  2886. }
  2887. for _, batch := range chunkStrings(foundList, sqlInChunk) {
  2888. var rows []trafficRow
  2889. if err := db.Model(xray.ClientTraffic{}).
  2890. Where("email IN ?", batch).
  2891. Select("email, enable").
  2892. Scan(&rows).Error; err == nil {
  2893. for _, r := range rows {
  2894. notDepletedByEmail[r.Email] = r.Enable
  2895. }
  2896. }
  2897. }
  2898. }
  2899. var sharedSet map[string]bool
  2900. if !keepTraffic {
  2901. var sharedErr error
  2902. sharedSet, sharedErr = inboundSvc.emailsUsedByOtherInbounds(foundList, inboundId)
  2903. if sharedErr != nil {
  2904. for email := range foundEmails {
  2905. res.perEmailSkipped[email] = sharedErr.Error()
  2906. delete(foundEmails, email)
  2907. }
  2908. return res
  2909. }
  2910. }
  2911. if !keepTraffic {
  2912. purge := make([]string, 0, len(foundEmails))
  2913. for email := range foundEmails {
  2914. if !sharedSet[strings.ToLower(strings.TrimSpace(email))] {
  2915. purge = append(purge, email)
  2916. }
  2917. }
  2918. if len(purge) > 0 {
  2919. if delErr := inboundSvc.delClientIPsByEmails(db, purge); delErr != nil {
  2920. logger.Error("Error in delete client IPs")
  2921. for _, email := range purge {
  2922. res.perEmailSkipped[email] = delErr.Error()
  2923. delete(foundEmails, email)
  2924. }
  2925. } else if delErr := inboundSvc.delClientStatsByEmails(db, purge); delErr != nil {
  2926. logger.Error("Delete stats Data Error")
  2927. for _, email := range purge {
  2928. res.perEmailSkipped[email] = delErr.Error()
  2929. delete(foundEmails, email)
  2930. }
  2931. }
  2932. }
  2933. }
  2934. markDirty := false
  2935. if oldInbound.NodeID == nil {
  2936. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  2937. if rterr != nil {
  2938. res.needRestart = true
  2939. } else {
  2940. for email := range foundEmails {
  2941. if !enableByEmail[email] || !notDepletedByEmail[email] {
  2942. continue
  2943. }
  2944. err1 := rt.RemoveUser(context.Background(), oldInbound, email)
  2945. if err1 == nil {
  2946. logger.Debug("Client deleted on", rt.Name(), ":", email)
  2947. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  2948. logger.Debug("User is already deleted. Nothing to do more...")
  2949. } else {
  2950. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  2951. res.needRestart = true
  2952. }
  2953. }
  2954. }
  2955. } else {
  2956. rt, push, dirty, perr := inboundSvc.nodePushPlan(oldInbound)
  2957. if perr != nil {
  2958. for email := range foundEmails {
  2959. res.perEmailSkipped[email] = perr.Error()
  2960. delete(foundEmails, email)
  2961. }
  2962. } else {
  2963. if dirty {
  2964. markDirty = true
  2965. }
  2966. if push {
  2967. for email := range foundEmails {
  2968. if err1 := rt.DeleteUser(context.Background(), oldInbound, email); err1 != nil {
  2969. logger.Warning("Error in deleting client on", rt.Name(), ":", err1)
  2970. markDirty = true
  2971. }
  2972. }
  2973. }
  2974. }
  2975. }
  2976. txErr := db.Transaction(func(tx *gorm.DB) error {
  2977. if err := tx.Save(oldInbound).Error; err != nil {
  2978. return err
  2979. }
  2980. finalClients, err := inboundSvc.GetClients(oldInbound)
  2981. if err != nil {
  2982. return err
  2983. }
  2984. return s.SyncInbound(tx, inboundId, finalClients)
  2985. })
  2986. if txErr != nil {
  2987. for email := range foundEmails {
  2988. if _, skip := res.perEmailSkipped[email]; !skip {
  2989. res.perEmailSkipped[email] = txErr.Error()
  2990. }
  2991. }
  2992. } else if markDirty && oldInbound.NodeID != nil {
  2993. if dErr := (&NodeService{}).MarkNodeDirty(*oldInbound.NodeID); dErr != nil {
  2994. logger.Warning("mark node dirty failed:", dErr)
  2995. }
  2996. }
  2997. return res
  2998. }
  2999. // BulkCreateResult mirrors BulkAdjustResult for the create flow.
  3000. type BulkCreateResult struct {
  3001. Created int `json:"created"`
  3002. Skipped []BulkCreateReport `json:"skipped,omitempty"`
  3003. }
  3004. type BulkCreateReport struct {
  3005. Email string `json:"email"`
  3006. Reason string `json:"reason"`
  3007. }
  3008. func (s *ClientService) BulkCreate(inboundSvc *InboundService, payloads []ClientCreatePayload) (BulkCreateResult, bool, error) {
  3009. result := BulkCreateResult{}
  3010. if len(payloads) == 0 {
  3011. return result, false, nil
  3012. }
  3013. skip := func(email, reason string) {
  3014. if strings.TrimSpace(email) == "" {
  3015. email = "(missing email)"
  3016. }
  3017. result.Skipped = append(result.Skipped, BulkCreateReport{Email: email, Reason: reason})
  3018. }
  3019. emailSubIDs, err := inboundSvc.getAllEmailSubIDs()
  3020. if err != nil {
  3021. emailSubIDs = nil
  3022. }
  3023. type prepared struct {
  3024. client model.Client
  3025. inboundIds []int
  3026. }
  3027. prep := make([]prepared, 0, len(payloads))
  3028. emails := make([]string, 0, len(payloads))
  3029. subIDs := make([]string, 0, len(payloads))
  3030. seenEmail := make(map[string]struct{}, len(payloads))
  3031. seenSubID := make(map[string]string, len(payloads))
  3032. for i := range payloads {
  3033. client := payloads[i].Client
  3034. email := strings.TrimSpace(client.Email)
  3035. if email == "" {
  3036. skip("", "client email is required")
  3037. continue
  3038. }
  3039. if verr := validateClientEmail(email); verr != nil {
  3040. skip(email, verr.Error())
  3041. continue
  3042. }
  3043. if verr := validateClientSubID(client.SubID); verr != nil {
  3044. skip(email, verr.Error())
  3045. continue
  3046. }
  3047. if len(payloads[i].InboundIds) == 0 {
  3048. skip(email, "at least one inbound is required")
  3049. continue
  3050. }
  3051. client.Email = email
  3052. if client.SubID == "" {
  3053. client.SubID = uuid.NewString()
  3054. }
  3055. if !client.Enable {
  3056. client.Enable = true
  3057. }
  3058. now := time.Now().UnixMilli()
  3059. if client.CreatedAt == 0 {
  3060. client.CreatedAt = now
  3061. }
  3062. client.UpdatedAt = now
  3063. le := strings.ToLower(email)
  3064. if _, dup := seenEmail[le]; dup {
  3065. skip(email, "email already in use: "+email)
  3066. continue
  3067. }
  3068. if owner, ok := seenSubID[client.SubID]; ok && owner != le {
  3069. skip(email, "subId already in use: "+client.SubID)
  3070. continue
  3071. }
  3072. seenEmail[le] = struct{}{}
  3073. seenSubID[client.SubID] = le
  3074. prep = append(prep, prepared{client: client, inboundIds: payloads[i].InboundIds})
  3075. emails = append(emails, email)
  3076. subIDs = append(subIDs, client.SubID)
  3077. }
  3078. if len(prep) == 0 {
  3079. return result, false, nil
  3080. }
  3081. db := database.GetDB()
  3082. const lookupChunk = 400
  3083. existingEmailSub := make(map[string]string, len(emails))
  3084. for start := 0; start < len(emails); start += lookupChunk {
  3085. end := min(start+lookupChunk, len(emails))
  3086. var rows []model.ClientRecord
  3087. if e := db.Where("email IN ?", emails[start:end]).Find(&rows).Error; e != nil {
  3088. return result, false, e
  3089. }
  3090. for i := range rows {
  3091. existingEmailSub[strings.ToLower(rows[i].Email)] = rows[i].SubID
  3092. }
  3093. }
  3094. existingSubOwner := make(map[string]string, len(subIDs))
  3095. for start := 0; start < len(subIDs); start += lookupChunk {
  3096. end := min(start+lookupChunk, len(subIDs))
  3097. var rows []model.ClientRecord
  3098. if e := db.Where("sub_id IN ?", subIDs[start:end]).Find(&rows).Error; e != nil {
  3099. return result, false, e
  3100. }
  3101. for i := range rows {
  3102. existingSubOwner[rows[i].SubID] = strings.ToLower(rows[i].Email)
  3103. }
  3104. }
  3105. inboundCache := make(map[int]*model.Inbound)
  3106. getIb := func(id int) (*model.Inbound, error) {
  3107. if ib, ok := inboundCache[id]; ok {
  3108. return ib, nil
  3109. }
  3110. ib, e := inboundSvc.GetInbound(id)
  3111. if e != nil {
  3112. return nil, e
  3113. }
  3114. inboundCache[id] = ib
  3115. return ib, nil
  3116. }
  3117. byInbound := make(map[int][]model.Client)
  3118. idxByInbound := make(map[int][]int)
  3119. inboundOrder := make([]int, 0)
  3120. failed := make([]bool, len(prep))
  3121. reason := make([]string, len(prep))
  3122. for idx := range prep {
  3123. le := strings.ToLower(prep[idx].client.Email)
  3124. if existSub, ok := existingEmailSub[le]; ok && existSub != prep[idx].client.SubID {
  3125. failed[idx] = true
  3126. reason[idx] = "email already in use: " + prep[idx].client.Email
  3127. continue
  3128. }
  3129. if owner, ok := existingSubOwner[prep[idx].client.SubID]; ok && owner != le {
  3130. failed[idx] = true
  3131. reason[idx] = "subId already in use: " + prep[idx].client.SubID
  3132. continue
  3133. }
  3134. ok := true
  3135. for _, ibId := range prep[idx].inboundIds {
  3136. ib, e := getIb(ibId)
  3137. if e != nil {
  3138. failed[idx] = true
  3139. reason[idx] = e.Error()
  3140. ok = false
  3141. break
  3142. }
  3143. if e := s.fillProtocolDefaults(&prep[idx].client, ib); e != nil {
  3144. failed[idx] = true
  3145. reason[idx] = e.Error()
  3146. ok = false
  3147. break
  3148. }
  3149. }
  3150. if !ok {
  3151. continue
  3152. }
  3153. for _, ibId := range prep[idx].inboundIds {
  3154. ib, _ := getIb(ibId)
  3155. if _, seen := byInbound[ibId]; !seen {
  3156. inboundOrder = append(inboundOrder, ibId)
  3157. }
  3158. byInbound[ibId] = append(byInbound[ibId], clientWithInboundFlow(prep[idx].client, ib))
  3159. idxByInbound[ibId] = append(idxByInbound[ibId], idx)
  3160. }
  3161. }
  3162. needRestart := false
  3163. for _, ibId := range inboundOrder {
  3164. payload, e := json.Marshal(map[string][]model.Client{"clients": byInbound[ibId]})
  3165. if e == nil {
  3166. var nr bool
  3167. nr, e = s.addInboundClient(inboundSvc, &model.Inbound{Id: ibId, Settings: string(payload)}, emailSubIDs)
  3168. if e == nil && nr {
  3169. needRestart = true
  3170. }
  3171. }
  3172. if e != nil {
  3173. for _, idx := range idxByInbound[ibId] {
  3174. failed[idx] = true
  3175. if reason[idx] == "" {
  3176. reason[idx] = e.Error()
  3177. }
  3178. }
  3179. }
  3180. }
  3181. for idx := range prep {
  3182. if failed[idx] {
  3183. skip(prep[idx].client.Email, reason[idx])
  3184. } else {
  3185. result.Created++
  3186. }
  3187. }
  3188. return result, needRestart, nil
  3189. }
  3190. func (s *ClientService) DelDepleted(inboundSvc *InboundService) (int, bool, error) {
  3191. db := database.GetDB()
  3192. now := time.Now().UnixMilli()
  3193. depletedClause := "reset = 0 and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))"
  3194. var rows []xray.ClientTraffic
  3195. if err := db.Where(depletedClause, now).Find(&rows).Error; err != nil {
  3196. return 0, false, err
  3197. }
  3198. if len(rows) == 0 {
  3199. return 0, false, nil
  3200. }
  3201. seen := make(map[string]struct{}, len(rows))
  3202. emails := make([]string, 0, len(rows))
  3203. for _, r := range rows {
  3204. if r.Email == "" {
  3205. continue
  3206. }
  3207. if _, ok := seen[r.Email]; ok {
  3208. continue
  3209. }
  3210. seen[r.Email] = struct{}{}
  3211. emails = append(emails, r.Email)
  3212. }
  3213. if len(emails) == 0 {
  3214. return 0, false, nil
  3215. }
  3216. res, needRestart, err := s.BulkDelete(inboundSvc, emails, false)
  3217. if err != nil {
  3218. return res.Deleted, needRestart, err
  3219. }
  3220. return res.Deleted, needRestart, nil
  3221. }
  3222. func (s *ClientService) ResetAllClientTraffics(inboundSvc *InboundService, id int) error {
  3223. return submitTrafficWrite(func() error {
  3224. return s.resetAllClientTrafficsLocked(id)
  3225. })
  3226. }
  3227. func (s *ClientService) resetAllClientTrafficsLocked(id int) error {
  3228. db := database.GetDB()
  3229. now := time.Now().Unix() * 1000
  3230. if err := db.Transaction(func(tx *gorm.DB) error {
  3231. whereText := "inbound_id "
  3232. if id == -1 {
  3233. whereText += " > ?"
  3234. } else {
  3235. whereText += " = ?"
  3236. }
  3237. result := tx.Model(xray.ClientTraffic{}).
  3238. Where(whereText, id).
  3239. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  3240. if result.Error != nil {
  3241. return result.Error
  3242. }
  3243. inboundWhereText := "id "
  3244. if id == -1 {
  3245. inboundWhereText += " > ?"
  3246. } else {
  3247. inboundWhereText += " = ?"
  3248. }
  3249. result = tx.Model(model.Inbound{}).
  3250. Where(inboundWhereText, id).
  3251. Update("last_traffic_reset_time", now)
  3252. return result.Error
  3253. }); err != nil {
  3254. return err
  3255. }
  3256. return nil
  3257. }
  3258. func (s *ClientService) ResetAllTraffics() (bool, error) {
  3259. res := database.GetDB().Model(&xray.ClientTraffic{}).
  3260. Where("1 = 1").
  3261. Updates(map[string]any{"up": 0, "down": 0})
  3262. if res.Error != nil {
  3263. return false, res.Error
  3264. }
  3265. return res.RowsAffected > 0, nil
  3266. }
  3267. func (s *ClientService) Detach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  3268. existing, err := s.GetByID(id)
  3269. if err != nil {
  3270. return false, err
  3271. }
  3272. currentIds, err := s.GetInboundIdsForRecord(id)
  3273. if err != nil {
  3274. return false, err
  3275. }
  3276. have := make(map[int]struct{}, len(currentIds))
  3277. for _, x := range currentIds {
  3278. have[x] = struct{}{}
  3279. }
  3280. needRestart := false
  3281. for _, ibId := range inboundIds {
  3282. if _, attached := have[ibId]; !attached {
  3283. continue
  3284. }
  3285. inbound, getErr := inboundSvc.GetInbound(ibId)
  3286. if getErr != nil {
  3287. return needRestart, getErr
  3288. }
  3289. key := clientKeyForProtocol(inbound.Protocol, existing)
  3290. if key == "" {
  3291. continue
  3292. }
  3293. nr, delErr := s.DelInboundClient(inboundSvc, ibId, key, true)
  3294. if delErr != nil {
  3295. return needRestart, delErr
  3296. }
  3297. if nr {
  3298. needRestart = true
  3299. }
  3300. }
  3301. return needRestart, nil
  3302. }
  3303. func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, clients []model.Client, emailSubIDs map[string]string) (string, error) {
  3304. if emailSubIDs == nil {
  3305. var err error
  3306. emailSubIDs, err = inboundSvc.getAllEmailSubIDs()
  3307. if err != nil {
  3308. return "", err
  3309. }
  3310. }
  3311. seen := make(map[string]string, len(clients))
  3312. for _, client := range clients {
  3313. if client.Email == "" {
  3314. continue
  3315. }
  3316. key := strings.ToLower(client.Email)
  3317. if prev, ok := seen[key]; ok {
  3318. if prev != client.SubID || client.SubID == "" {
  3319. return client.Email, nil
  3320. }
  3321. continue
  3322. }
  3323. seen[key] = client.SubID
  3324. if existingSub, ok := emailSubIDs[key]; ok {
  3325. if client.SubID == "" || existingSub == "" || existingSub != client.SubID {
  3326. return client.Email, nil
  3327. }
  3328. }
  3329. }
  3330. return "", nil
  3331. }
  3332. func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (bool, error) {
  3333. return s.addInboundClient(inboundSvc, data, nil)
  3334. }
  3335. // addInboundClient is AddInboundClient with an optional precomputed email→subId
  3336. // map. Bulk callers pass a single snapshot so the global getAllEmailSubIDs scan
  3337. // runs once for the whole batch instead of once per target inbound; a nil map
  3338. // makes it compute its own (the single-add path).
  3339. func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model.Inbound, emailSubIDs map[string]string) (bool, error) {
  3340. defer lockInbound(data.Id).Unlock()
  3341. clients, err := inboundSvc.GetClients(data)
  3342. if err != nil {
  3343. return false, err
  3344. }
  3345. var settings map[string]any
  3346. err = json.Unmarshal([]byte(data.Settings), &settings)
  3347. if err != nil {
  3348. return false, err
  3349. }
  3350. interfaceClients := settings["clients"].([]any)
  3351. nowTs := time.Now().Unix() * 1000
  3352. for i := range interfaceClients {
  3353. if cm, ok := interfaceClients[i].(map[string]any); ok {
  3354. if _, ok2 := cm["created_at"]; !ok2 {
  3355. cm["created_at"] = nowTs
  3356. }
  3357. cm["updated_at"] = nowTs
  3358. existingSub, _ := cm["subId"].(string)
  3359. if strings.TrimSpace(existingSub) == "" {
  3360. cm["subId"] = random.NumLower(16)
  3361. }
  3362. interfaceClients[i] = cm
  3363. }
  3364. }
  3365. existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients, emailSubIDs)
  3366. if err != nil {
  3367. return false, err
  3368. }
  3369. if existEmail != "" {
  3370. return false, common.NewError("Duplicate email:", existEmail)
  3371. }
  3372. oldInbound, err := inboundSvc.GetInbound(data.Id)
  3373. if err != nil {
  3374. return false, err
  3375. }
  3376. for _, client := range clients {
  3377. if strings.TrimSpace(client.Email) == "" {
  3378. return false, common.NewError("client email is required")
  3379. }
  3380. switch oldInbound.Protocol {
  3381. case "trojan":
  3382. if client.Password == "" {
  3383. return false, common.NewError("empty client ID")
  3384. }
  3385. case "shadowsocks":
  3386. if client.Email == "" {
  3387. return false, common.NewError("empty client ID")
  3388. }
  3389. case "hysteria":
  3390. if client.Auth == "" {
  3391. return false, common.NewError("empty client ID")
  3392. }
  3393. default:
  3394. if client.ID == "" {
  3395. return false, common.NewError("empty client ID")
  3396. }
  3397. }
  3398. }
  3399. var oldSettings map[string]any
  3400. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  3401. if err != nil {
  3402. return false, err
  3403. }
  3404. if oldInbound.Protocol == model.Shadowsocks {
  3405. applyShadowsocksClientMethod(interfaceClients, oldSettings)
  3406. }
  3407. oldClients := oldSettings["clients"].([]any)
  3408. oldClients = compactOrphans(database.GetDB(), oldClients)
  3409. oldClients = append(oldClients, interfaceClients...)
  3410. oldSettings["clients"] = oldClients
  3411. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  3412. if err != nil {
  3413. return false, err
  3414. }
  3415. oldInbound.Settings = string(newSettings)
  3416. db := database.GetDB()
  3417. tx := db.Begin()
  3418. markDirty := false
  3419. defer func() {
  3420. if err != nil {
  3421. tx.Rollback()
  3422. return
  3423. }
  3424. tx.Commit()
  3425. if markDirty && oldInbound.NodeID != nil {
  3426. if dErr := (&NodeService{}).MarkNodeDirty(*oldInbound.NodeID); dErr != nil {
  3427. logger.Warning("mark node dirty failed:", dErr)
  3428. }
  3429. }
  3430. }()
  3431. needRestart := false
  3432. rt, push, dirty, perr := inboundSvc.nodePushPlan(oldInbound)
  3433. if perr != nil {
  3434. err = perr
  3435. return false, err
  3436. }
  3437. if dirty {
  3438. markDirty = true
  3439. }
  3440. if oldInbound.NodeID == nil {
  3441. if !push {
  3442. needRestart = true
  3443. } else {
  3444. for _, client := range clients {
  3445. if len(client.Email) == 0 {
  3446. needRestart = true
  3447. continue
  3448. }
  3449. inboundSvc.AddClientStat(tx, data.Id, &client)
  3450. if !client.Enable {
  3451. continue
  3452. }
  3453. cipher := ""
  3454. if oldInbound.Protocol == "shadowsocks" {
  3455. cipher = oldSettings["method"].(string)
  3456. }
  3457. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  3458. "email": client.Email,
  3459. "id": client.ID,
  3460. "auth": client.Auth,
  3461. "security": client.Security,
  3462. "flow": client.Flow,
  3463. "password": client.Password,
  3464. "cipher": cipher,
  3465. })
  3466. if err1 == nil {
  3467. logger.Debug("Client added on", rt.Name(), ":", client.Email)
  3468. } else {
  3469. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  3470. needRestart = true
  3471. }
  3472. }
  3473. }
  3474. } else {
  3475. for _, client := range clients {
  3476. if len(client.Email) > 0 {
  3477. inboundSvc.AddClientStat(tx, data.Id, &client)
  3478. }
  3479. if push {
  3480. if err1 := rt.AddClient(context.Background(), oldInbound, client); err1 != nil {
  3481. logger.Warning("Error in adding client on", rt.Name(), ":", err1)
  3482. markDirty = true
  3483. push = false
  3484. }
  3485. }
  3486. }
  3487. }
  3488. if err = tx.Save(oldInbound).Error; err != nil {
  3489. return false, err
  3490. }
  3491. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  3492. if gcErr != nil {
  3493. err = gcErr
  3494. return false, err
  3495. }
  3496. if err = s.SyncInbound(tx, oldInbound.Id, finalClients); err != nil {
  3497. return false, err
  3498. }
  3499. return needRestart, nil
  3500. }
  3501. func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *model.Inbound, clientId string) (bool, error) {
  3502. defer lockInbound(data.Id).Unlock()
  3503. clients, err := inboundSvc.GetClients(data)
  3504. if err != nil {
  3505. return false, err
  3506. }
  3507. var settings map[string]any
  3508. err = json.Unmarshal([]byte(data.Settings), &settings)
  3509. if err != nil {
  3510. return false, err
  3511. }
  3512. interfaceClients := settings["clients"].([]any)
  3513. oldInbound, err := inboundSvc.GetInbound(data.Id)
  3514. if err != nil {
  3515. return false, err
  3516. }
  3517. oldClients, err := inboundSvc.GetClients(oldInbound)
  3518. if err != nil {
  3519. return false, err
  3520. }
  3521. oldEmail := ""
  3522. newClientId := ""
  3523. clientIndex := -1
  3524. for index, oldClient := range oldClients {
  3525. oldClientId := ""
  3526. switch oldInbound.Protocol {
  3527. case "trojan":
  3528. oldClientId = oldClient.Password
  3529. newClientId = clients[0].Password
  3530. case "shadowsocks":
  3531. oldClientId = oldClient.Email
  3532. newClientId = clients[0].Email
  3533. case "hysteria":
  3534. oldClientId = oldClient.Auth
  3535. newClientId = clients[0].Auth
  3536. default:
  3537. oldClientId = oldClient.ID
  3538. newClientId = clients[0].ID
  3539. }
  3540. if clientId == oldClientId {
  3541. oldEmail = oldClient.Email
  3542. clientIndex = index
  3543. break
  3544. }
  3545. }
  3546. if clientIndex == -1 {
  3547. var rec model.ClientRecord
  3548. var lookupErr error
  3549. switch oldInbound.Protocol {
  3550. case "trojan":
  3551. lookupErr = database.GetDB().Where("password = ?", clientId).First(&rec).Error
  3552. case "shadowsocks":
  3553. lookupErr = database.GetDB().Where("email = ?", clientId).First(&rec).Error
  3554. case "hysteria":
  3555. lookupErr = database.GetDB().Where("auth = ?", clientId).First(&rec).Error
  3556. default:
  3557. lookupErr = database.GetDB().Where("uuid = ?", clientId).First(&rec).Error
  3558. }
  3559. if lookupErr == nil && rec.Email != "" {
  3560. for index, oldClient := range oldClients {
  3561. if oldClient.Email == rec.Email {
  3562. oldEmail = oldClient.Email
  3563. clientIndex = index
  3564. break
  3565. }
  3566. }
  3567. }
  3568. }
  3569. if newClientId == "" || clientIndex == -1 {
  3570. return false, common.NewError("empty client ID")
  3571. }
  3572. if strings.TrimSpace(clients[0].Email) == "" {
  3573. return false, common.NewError("client email is required")
  3574. }
  3575. if clients[0].Email != oldEmail {
  3576. existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients, nil)
  3577. if err != nil {
  3578. return false, err
  3579. }
  3580. if existEmail != "" {
  3581. return false, common.NewError("Duplicate email:", existEmail)
  3582. }
  3583. }
  3584. var oldSettings map[string]any
  3585. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  3586. if err != nil {
  3587. return false, err
  3588. }
  3589. settingsClients := oldSettings["clients"].([]any)
  3590. var preservedCreated any
  3591. var preservedSubID string
  3592. if clientIndex >= 0 && clientIndex < len(settingsClients) {
  3593. if oldMap, ok := settingsClients[clientIndex].(map[string]any); ok {
  3594. if v, ok2 := oldMap["created_at"]; ok2 {
  3595. preservedCreated = v
  3596. }
  3597. preservedSubID, _ = oldMap["subId"].(string)
  3598. }
  3599. }
  3600. if len(interfaceClients) > 0 {
  3601. if newMap, ok := interfaceClients[0].(map[string]any); ok {
  3602. if preservedCreated == nil {
  3603. preservedCreated = time.Now().Unix() * 1000
  3604. }
  3605. newMap["created_at"] = preservedCreated
  3606. newMap["updated_at"] = time.Now().Unix() * 1000
  3607. newSub, _ := newMap["subId"].(string)
  3608. if strings.TrimSpace(newSub) == "" {
  3609. if strings.TrimSpace(preservedSubID) != "" {
  3610. newMap["subId"] = preservedSubID
  3611. } else {
  3612. newMap["subId"] = random.NumLower(16)
  3613. }
  3614. }
  3615. interfaceClients[0] = newMap
  3616. }
  3617. }
  3618. if oldInbound.Protocol == model.Shadowsocks {
  3619. applyShadowsocksClientMethod(interfaceClients, oldSettings)
  3620. }
  3621. settingsClients[clientIndex] = interfaceClients[0]
  3622. oldSettings["clients"] = settingsClients
  3623. if oldInbound.Protocol == model.VLESS {
  3624. hasVisionFlow := false
  3625. for _, c := range settingsClients {
  3626. cm, ok := c.(map[string]any)
  3627. if !ok {
  3628. continue
  3629. }
  3630. if flow, _ := cm["flow"].(string); flow == "xtls-rprx-vision" {
  3631. hasVisionFlow = true
  3632. break
  3633. }
  3634. }
  3635. if !hasVisionFlow {
  3636. delete(oldSettings, "testseed")
  3637. }
  3638. }
  3639. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  3640. if err != nil {
  3641. return false, err
  3642. }
  3643. oldInbound.Settings = string(newSettings)
  3644. db := database.GetDB()
  3645. tx := db.Begin()
  3646. markDirty := false
  3647. defer func() {
  3648. if err != nil {
  3649. tx.Rollback()
  3650. return
  3651. }
  3652. tx.Commit()
  3653. if markDirty && oldInbound.NodeID != nil {
  3654. if dErr := (&NodeService{}).MarkNodeDirty(*oldInbound.NodeID); dErr != nil {
  3655. logger.Warning("mark node dirty failed:", dErr)
  3656. }
  3657. }
  3658. }()
  3659. if len(clients[0].Email) > 0 {
  3660. if len(oldEmail) > 0 {
  3661. emailUnchanged := strings.EqualFold(oldEmail, clients[0].Email)
  3662. targetExists := int64(0)
  3663. if !emailUnchanged {
  3664. if err = tx.Model(xray.ClientTraffic{}).Where("email = ?", clients[0].Email).Count(&targetExists).Error; err != nil {
  3665. return false, err
  3666. }
  3667. }
  3668. if emailUnchanged || targetExists == 0 {
  3669. err = inboundSvc.UpdateClientStat(tx, oldEmail, &clients[0])
  3670. if err != nil {
  3671. return false, err
  3672. }
  3673. err = inboundSvc.UpdateClientIPs(tx, oldEmail, clients[0].Email)
  3674. if err != nil {
  3675. return false, err
  3676. }
  3677. } else {
  3678. stillUsed, sErr := inboundSvc.emailUsedByOtherInbounds(oldEmail, data.Id)
  3679. if sErr != nil {
  3680. return false, sErr
  3681. }
  3682. if !stillUsed {
  3683. if err = inboundSvc.DelClientStat(tx, oldEmail); err != nil {
  3684. return false, err
  3685. }
  3686. if err = inboundSvc.DelClientIPs(tx, oldEmail); err != nil {
  3687. return false, err
  3688. }
  3689. }
  3690. if err = inboundSvc.UpdateClientStat(tx, clients[0].Email, &clients[0]); err != nil {
  3691. return false, err
  3692. }
  3693. }
  3694. } else {
  3695. inboundSvc.AddClientStat(tx, data.Id, &clients[0])
  3696. }
  3697. } else {
  3698. stillUsed, err := inboundSvc.emailUsedByOtherInbounds(oldEmail, data.Id)
  3699. if err != nil {
  3700. return false, err
  3701. }
  3702. if !stillUsed {
  3703. err = inboundSvc.DelClientStat(tx, oldEmail)
  3704. if err != nil {
  3705. return false, err
  3706. }
  3707. err = inboundSvc.DelClientIPs(tx, oldEmail)
  3708. if err != nil {
  3709. return false, err
  3710. }
  3711. }
  3712. }
  3713. needRestart := false
  3714. if len(oldEmail) > 0 {
  3715. rt, push, dirty, perr := inboundSvc.nodePushPlan(oldInbound)
  3716. if perr != nil {
  3717. err = perr
  3718. return false, err
  3719. }
  3720. if dirty {
  3721. markDirty = true
  3722. }
  3723. if oldInbound.NodeID == nil {
  3724. if !push {
  3725. needRestart = true
  3726. } else {
  3727. if oldClients[clientIndex].Enable {
  3728. err1 := rt.RemoveUser(context.Background(), oldInbound, oldEmail)
  3729. if err1 == nil {
  3730. logger.Debug("Old client deleted on", rt.Name(), ":", oldEmail)
  3731. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", oldEmail)) {
  3732. logger.Debug("User is already deleted. Nothing to do more...")
  3733. } else {
  3734. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  3735. needRestart = true
  3736. }
  3737. }
  3738. if clients[0].Enable {
  3739. cipher := ""
  3740. if oldInbound.Protocol == "shadowsocks" {
  3741. cipher = oldSettings["method"].(string)
  3742. }
  3743. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  3744. "email": clients[0].Email,
  3745. "id": clients[0].ID,
  3746. "security": clients[0].Security,
  3747. "flow": clients[0].Flow,
  3748. "auth": clients[0].Auth,
  3749. "password": clients[0].Password,
  3750. "cipher": cipher,
  3751. })
  3752. if err1 == nil {
  3753. logger.Debug("Client edited on", rt.Name(), ":", clients[0].Email)
  3754. } else {
  3755. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  3756. needRestart = true
  3757. }
  3758. }
  3759. }
  3760. } else if push {
  3761. if err1 := rt.UpdateUser(context.Background(), oldInbound, oldEmail, clients[0]); err1 != nil {
  3762. logger.Warning("Error in updating client on", rt.Name(), ":", err1)
  3763. markDirty = true
  3764. }
  3765. }
  3766. } else {
  3767. logger.Debug("Client old email not found")
  3768. needRestart = true
  3769. }
  3770. if err = tx.Save(oldInbound).Error; err != nil {
  3771. return false, err
  3772. }
  3773. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  3774. if gcErr != nil {
  3775. err = gcErr
  3776. return false, err
  3777. }
  3778. if err = s.SyncInbound(tx, oldInbound.Id, finalClients); err != nil {
  3779. return false, err
  3780. }
  3781. return needRestart, nil
  3782. }
  3783. func (s *ClientService) DelInboundClient(inboundSvc *InboundService, inboundId int, clientId string, keepTraffic bool) (bool, error) {
  3784. defer lockInbound(inboundId).Unlock()
  3785. oldInbound, err := inboundSvc.GetInbound(inboundId)
  3786. if err != nil {
  3787. logger.Error("Load Old Data Error")
  3788. return false, err
  3789. }
  3790. var settings map[string]any
  3791. err = json.Unmarshal([]byte(oldInbound.Settings), &settings)
  3792. if err != nil {
  3793. return false, err
  3794. }
  3795. email := ""
  3796. client_key := "id"
  3797. switch oldInbound.Protocol {
  3798. case "trojan":
  3799. client_key = "password"
  3800. case "shadowsocks":
  3801. client_key = "email"
  3802. case "hysteria":
  3803. client_key = "auth"
  3804. }
  3805. interfaceClients := settings["clients"].([]any)
  3806. var newClients []any
  3807. needApiDel := false
  3808. clientFound := false
  3809. for _, client := range interfaceClients {
  3810. c := client.(map[string]any)
  3811. c_id := c[client_key].(string)
  3812. if c_id == clientId {
  3813. clientFound = true
  3814. email, _ = c["email"].(string)
  3815. needApiDel, _ = c["enable"].(bool)
  3816. } else {
  3817. newClients = append(newClients, client)
  3818. }
  3819. }
  3820. if !clientFound {
  3821. return false, common.NewError("Client Not Found In Inbound For ID:", clientId)
  3822. }
  3823. db := database.GetDB()
  3824. newClients = compactOrphans(db, newClients)
  3825. if newClients == nil {
  3826. newClients = []any{}
  3827. }
  3828. settings["clients"] = newClients
  3829. newSettings, err := json.MarshalIndent(settings, "", " ")
  3830. if err != nil {
  3831. return false, err
  3832. }
  3833. oldInbound.Settings = string(newSettings)
  3834. emailShared, err := inboundSvc.emailUsedByOtherInbounds(email, inboundId)
  3835. if err != nil {
  3836. return false, err
  3837. }
  3838. if !emailShared && !keepTraffic {
  3839. err = inboundSvc.DelClientIPs(db, email)
  3840. if err != nil {
  3841. logger.Error("Error in delete client IPs")
  3842. return false, err
  3843. }
  3844. }
  3845. needRestart := false
  3846. markDirty := false
  3847. if len(email) > 0 {
  3848. var enables []bool
  3849. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Limit(1).Pluck("enable", &enables).Error
  3850. if err != nil {
  3851. logger.Error("Get stats error")
  3852. return false, err
  3853. }
  3854. notDepleted := len(enables) > 0 && enables[0]
  3855. if !emailShared && !keepTraffic {
  3856. err = inboundSvc.DelClientStat(db, email)
  3857. if err != nil {
  3858. logger.Error("Delete stats Data Error")
  3859. return false, err
  3860. }
  3861. }
  3862. if needApiDel && notDepleted && oldInbound.NodeID == nil {
  3863. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  3864. if rterr != nil {
  3865. needRestart = true
  3866. } else {
  3867. err1 := rt.RemoveUser(context.Background(), oldInbound, email)
  3868. if err1 == nil {
  3869. logger.Debug("Client deleted on", rt.Name(), ":", email)
  3870. needRestart = false
  3871. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  3872. logger.Debug("User is already deleted. Nothing to do more...")
  3873. } else {
  3874. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  3875. needRestart = true
  3876. }
  3877. }
  3878. }
  3879. }
  3880. if oldInbound.NodeID != nil && len(email) > 0 {
  3881. rt, push, dirty, perr := inboundSvc.nodePushPlan(oldInbound)
  3882. if perr != nil {
  3883. return false, perr
  3884. }
  3885. if dirty {
  3886. markDirty = true
  3887. }
  3888. if push {
  3889. if err1 := rt.DeleteUser(context.Background(), oldInbound, email); err1 != nil {
  3890. logger.Warning("Error in deleting client on", rt.Name(), ":", err1)
  3891. markDirty = true
  3892. }
  3893. }
  3894. }
  3895. if err := db.Save(oldInbound).Error; err != nil {
  3896. return false, err
  3897. }
  3898. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  3899. if gcErr != nil {
  3900. return false, gcErr
  3901. }
  3902. if err := s.SyncInbound(db, inboundId, finalClients); err != nil {
  3903. return false, err
  3904. }
  3905. if markDirty && oldInbound.NodeID != nil {
  3906. if dErr := (&NodeService{}).MarkNodeDirty(*oldInbound.NodeID); dErr != nil {
  3907. logger.Warning("mark node dirty failed:", dErr)
  3908. }
  3909. }
  3910. return needRestart, nil
  3911. }
  3912. func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inboundId int, email string, keepTraffic bool) (bool, error) {
  3913. defer lockInbound(inboundId).Unlock()
  3914. oldInbound, err := inboundSvc.GetInbound(inboundId)
  3915. if err != nil {
  3916. logger.Error("Load Old Data Error")
  3917. return false, err
  3918. }
  3919. var settings map[string]any
  3920. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  3921. return false, err
  3922. }
  3923. interfaceClients, ok := settings["clients"].([]any)
  3924. if !ok {
  3925. return false, common.NewError("invalid clients format in inbound settings")
  3926. }
  3927. var newClients []any
  3928. needApiDel := false
  3929. found := false
  3930. for _, client := range interfaceClients {
  3931. c, ok := client.(map[string]any)
  3932. if !ok {
  3933. continue
  3934. }
  3935. if cEmail, ok := c["email"].(string); ok && cEmail == email {
  3936. found = true
  3937. needApiDel, _ = c["enable"].(bool)
  3938. } else {
  3939. newClients = append(newClients, client)
  3940. }
  3941. }
  3942. if !found {
  3943. return false, common.NewError(fmt.Sprintf("client with email %s not found", email))
  3944. }
  3945. db := database.GetDB()
  3946. newClients = compactOrphans(db, newClients)
  3947. if newClients == nil {
  3948. newClients = []any{}
  3949. }
  3950. settings["clients"] = newClients
  3951. newSettings, err := json.MarshalIndent(settings, "", " ")
  3952. if err != nil {
  3953. return false, err
  3954. }
  3955. oldInbound.Settings = string(newSettings)
  3956. emailShared, err := inboundSvc.emailUsedByOtherInbounds(email, inboundId)
  3957. if err != nil {
  3958. return false, err
  3959. }
  3960. if !emailShared && !keepTraffic {
  3961. if err := inboundSvc.DelClientIPs(db, email); err != nil {
  3962. logger.Error("Error in delete client IPs")
  3963. return false, err
  3964. }
  3965. }
  3966. needRestart := false
  3967. markDirty := false
  3968. if len(email) > 0 && !emailShared {
  3969. if !keepTraffic {
  3970. traffic, err := inboundSvc.GetClientTrafficByEmail(email)
  3971. if err != nil {
  3972. return false, err
  3973. }
  3974. if traffic != nil {
  3975. if err := inboundSvc.DelClientStat(db, email); err != nil {
  3976. logger.Error("Delete stats Data Error")
  3977. return false, err
  3978. }
  3979. }
  3980. }
  3981. if needApiDel {
  3982. rt, push, dirty, perr := inboundSvc.nodePushPlan(oldInbound)
  3983. if perr != nil {
  3984. return false, perr
  3985. }
  3986. if dirty {
  3987. markDirty = true
  3988. }
  3989. if oldInbound.NodeID == nil {
  3990. if !push {
  3991. needRestart = true
  3992. } else if err1 := rt.RemoveUser(context.Background(), oldInbound, email); err1 == nil {
  3993. logger.Debug("Client deleted on", rt.Name(), ":", email)
  3994. needRestart = false
  3995. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  3996. logger.Debug("User is already deleted. Nothing to do more...")
  3997. } else {
  3998. logger.Debug("Error in deleting client on", rt.Name(), ":", email)
  3999. needRestart = true
  4000. }
  4001. } else if push {
  4002. if err1 := rt.DeleteUser(context.Background(), oldInbound, email); err1 != nil {
  4003. logger.Warning("Error in deleting client on", rt.Name(), ":", err1)
  4004. markDirty = true
  4005. }
  4006. }
  4007. }
  4008. }
  4009. if err := db.Save(oldInbound).Error; err != nil {
  4010. return false, err
  4011. }
  4012. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  4013. if gcErr != nil {
  4014. return false, gcErr
  4015. }
  4016. if err := s.SyncInbound(db, inboundId, finalClients); err != nil {
  4017. return false, err
  4018. }
  4019. if markDirty && oldInbound.NodeID != nil {
  4020. if dErr := (&NodeService{}).MarkNodeDirty(*oldInbound.NodeID); dErr != nil {
  4021. logger.Warning("mark node dirty failed:", dErr)
  4022. }
  4023. }
  4024. return needRestart, nil
  4025. }
  4026. func (s *ClientService) SetClientTelegramUserID(inboundSvc *InboundService, trafficId int, tgId int64) (bool, error) {
  4027. traffic, inbound, err := inboundSvc.GetClientInboundByTrafficID(trafficId)
  4028. if err != nil {
  4029. return false, err
  4030. }
  4031. if inbound == nil {
  4032. return false, common.NewError("Inbound Not Found For Traffic ID:", trafficId)
  4033. }
  4034. clientEmail := traffic.Email
  4035. oldClients, err := inboundSvc.GetClients(inbound)
  4036. if err != nil {
  4037. return false, err
  4038. }
  4039. clientId := ""
  4040. for _, oldClient := range oldClients {
  4041. if oldClient.Email == clientEmail {
  4042. switch inbound.Protocol {
  4043. case "trojan":
  4044. clientId = oldClient.Password
  4045. case "shadowsocks":
  4046. clientId = oldClient.Email
  4047. default:
  4048. clientId = oldClient.ID
  4049. }
  4050. break
  4051. }
  4052. }
  4053. if len(clientId) == 0 {
  4054. return false, common.NewError("Client Not Found For Email:", clientEmail)
  4055. }
  4056. var settings map[string]any
  4057. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  4058. if err != nil {
  4059. return false, err
  4060. }
  4061. clients := settings["clients"].([]any)
  4062. var newClients []any
  4063. for client_index := range clients {
  4064. c := clients[client_index].(map[string]any)
  4065. if c["email"] == clientEmail {
  4066. c["tgId"] = tgId
  4067. c["updated_at"] = time.Now().Unix() * 1000
  4068. newClients = append(newClients, any(c))
  4069. }
  4070. }
  4071. settings["clients"] = newClients
  4072. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  4073. if err != nil {
  4074. return false, err
  4075. }
  4076. inbound.Settings = string(modifiedSettings)
  4077. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  4078. return needRestart, err
  4079. }
  4080. func (s *ClientService) checkIsEnabledByEmail(inboundSvc *InboundService, clientEmail string) (bool, error) {
  4081. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  4082. if err != nil {
  4083. return false, err
  4084. }
  4085. if inbound == nil {
  4086. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  4087. }
  4088. clients, err := inboundSvc.GetClients(inbound)
  4089. if err != nil {
  4090. return false, err
  4091. }
  4092. isEnable := false
  4093. for _, client := range clients {
  4094. if client.Email == clientEmail {
  4095. isEnable = client.Enable
  4096. break
  4097. }
  4098. }
  4099. return isEnable, err
  4100. }
  4101. func (s *ClientService) ToggleClientEnableByEmail(inboundSvc *InboundService, clientEmail string) (bool, bool, error) {
  4102. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  4103. if err != nil {
  4104. return false, false, err
  4105. }
  4106. if inbound == nil {
  4107. return false, false, common.NewError("Inbound Not Found For Email:", clientEmail)
  4108. }
  4109. oldClients, err := inboundSvc.GetClients(inbound)
  4110. if err != nil {
  4111. return false, false, err
  4112. }
  4113. clientId := ""
  4114. clientOldEnabled := false
  4115. for _, oldClient := range oldClients {
  4116. if oldClient.Email == clientEmail {
  4117. switch inbound.Protocol {
  4118. case "trojan":
  4119. clientId = oldClient.Password
  4120. case "shadowsocks":
  4121. clientId = oldClient.Email
  4122. default:
  4123. clientId = oldClient.ID
  4124. }
  4125. clientOldEnabled = oldClient.Enable
  4126. break
  4127. }
  4128. }
  4129. if len(clientId) == 0 {
  4130. return false, false, common.NewError("Client Not Found For Email:", clientEmail)
  4131. }
  4132. var settings map[string]any
  4133. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  4134. if err != nil {
  4135. return false, false, err
  4136. }
  4137. clients := settings["clients"].([]any)
  4138. var newClients []any
  4139. for client_index := range clients {
  4140. c := clients[client_index].(map[string]any)
  4141. if c["email"] == clientEmail {
  4142. c["enable"] = !clientOldEnabled
  4143. c["updated_at"] = time.Now().Unix() * 1000
  4144. newClients = append(newClients, any(c))
  4145. }
  4146. }
  4147. settings["clients"] = newClients
  4148. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  4149. if err != nil {
  4150. return false, false, err
  4151. }
  4152. inbound.Settings = string(modifiedSettings)
  4153. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  4154. if err != nil {
  4155. return false, needRestart, err
  4156. }
  4157. return !clientOldEnabled, needRestart, nil
  4158. }
  4159. func (s *ClientService) SetClientEnableByEmail(inboundSvc *InboundService, clientEmail string, enable bool) (bool, bool, error) {
  4160. current, err := s.checkIsEnabledByEmail(inboundSvc, clientEmail)
  4161. if err != nil {
  4162. return false, false, err
  4163. }
  4164. if current == enable {
  4165. return false, false, nil
  4166. }
  4167. newEnabled, needRestart, err := s.ToggleClientEnableByEmail(inboundSvc, clientEmail)
  4168. if err != nil {
  4169. return false, needRestart, err
  4170. }
  4171. return newEnabled == enable, needRestart, nil
  4172. }
  4173. func (s *ClientService) ResetClientIpLimitByEmail(inboundSvc *InboundService, clientEmail string, count int) (bool, error) {
  4174. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  4175. if err != nil {
  4176. return false, err
  4177. }
  4178. if inbound == nil {
  4179. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  4180. }
  4181. oldClients, err := inboundSvc.GetClients(inbound)
  4182. if err != nil {
  4183. return false, err
  4184. }
  4185. clientId := ""
  4186. for _, oldClient := range oldClients {
  4187. if oldClient.Email == clientEmail {
  4188. switch inbound.Protocol {
  4189. case "trojan":
  4190. clientId = oldClient.Password
  4191. case "shadowsocks":
  4192. clientId = oldClient.Email
  4193. default:
  4194. clientId = oldClient.ID
  4195. }
  4196. break
  4197. }
  4198. }
  4199. if len(clientId) == 0 {
  4200. return false, common.NewError("Client Not Found For Email:", clientEmail)
  4201. }
  4202. var settings map[string]any
  4203. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  4204. if err != nil {
  4205. return false, err
  4206. }
  4207. clients := settings["clients"].([]any)
  4208. var newClients []any
  4209. for client_index := range clients {
  4210. c := clients[client_index].(map[string]any)
  4211. if c["email"] == clientEmail {
  4212. c["limitIp"] = count
  4213. c["updated_at"] = time.Now().Unix() * 1000
  4214. newClients = append(newClients, any(c))
  4215. }
  4216. }
  4217. settings["clients"] = newClients
  4218. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  4219. if err != nil {
  4220. return false, err
  4221. }
  4222. inbound.Settings = string(modifiedSettings)
  4223. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  4224. return needRestart, err
  4225. }
  4226. func (s *ClientService) ResetClientExpiryTimeByEmail(inboundSvc *InboundService, clientEmail string, expiry_time int64) (bool, error) {
  4227. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  4228. if err != nil {
  4229. return false, err
  4230. }
  4231. if inbound == nil {
  4232. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  4233. }
  4234. oldClients, err := inboundSvc.GetClients(inbound)
  4235. if err != nil {
  4236. return false, err
  4237. }
  4238. clientId := ""
  4239. for _, oldClient := range oldClients {
  4240. if oldClient.Email == clientEmail {
  4241. switch inbound.Protocol {
  4242. case "trojan":
  4243. clientId = oldClient.Password
  4244. case "shadowsocks":
  4245. clientId = oldClient.Email
  4246. default:
  4247. clientId = oldClient.ID
  4248. }
  4249. break
  4250. }
  4251. }
  4252. if len(clientId) == 0 {
  4253. return false, common.NewError("Client Not Found For Email:", clientEmail)
  4254. }
  4255. var settings map[string]any
  4256. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  4257. if err != nil {
  4258. return false, err
  4259. }
  4260. clients := settings["clients"].([]any)
  4261. var newClients []any
  4262. for client_index := range clients {
  4263. c := clients[client_index].(map[string]any)
  4264. if c["email"] == clientEmail {
  4265. c["expiryTime"] = expiry_time
  4266. c["updated_at"] = time.Now().Unix() * 1000
  4267. newClients = append(newClients, any(c))
  4268. }
  4269. }
  4270. settings["clients"] = newClients
  4271. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  4272. if err != nil {
  4273. return false, err
  4274. }
  4275. inbound.Settings = string(modifiedSettings)
  4276. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  4277. return needRestart, err
  4278. }
  4279. func (s *ClientService) ResetClientTrafficLimitByEmail(inboundSvc *InboundService, clientEmail string, totalGB int) (bool, error) {
  4280. if totalGB < 0 {
  4281. return false, common.NewError("totalGB must be >= 0")
  4282. }
  4283. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  4284. if err != nil {
  4285. return false, err
  4286. }
  4287. if inbound == nil {
  4288. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  4289. }
  4290. oldClients, err := inboundSvc.GetClients(inbound)
  4291. if err != nil {
  4292. return false, err
  4293. }
  4294. clientId := ""
  4295. for _, oldClient := range oldClients {
  4296. if oldClient.Email == clientEmail {
  4297. switch inbound.Protocol {
  4298. case "trojan":
  4299. clientId = oldClient.Password
  4300. case "shadowsocks":
  4301. clientId = oldClient.Email
  4302. default:
  4303. clientId = oldClient.ID
  4304. }
  4305. break
  4306. }
  4307. }
  4308. if len(clientId) == 0 {
  4309. return false, common.NewError("Client Not Found For Email:", clientEmail)
  4310. }
  4311. var settings map[string]any
  4312. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  4313. if err != nil {
  4314. return false, err
  4315. }
  4316. clients := settings["clients"].([]any)
  4317. var newClients []any
  4318. for client_index := range clients {
  4319. c := clients[client_index].(map[string]any)
  4320. if c["email"] == clientEmail {
  4321. c["totalGB"] = totalGB * 1024 * 1024 * 1024
  4322. c["updated_at"] = time.Now().Unix() * 1000
  4323. newClients = append(newClients, any(c))
  4324. }
  4325. }
  4326. settings["clients"] = newClients
  4327. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  4328. if err != nil {
  4329. return false, err
  4330. }
  4331. inbound.Settings = string(modifiedSettings)
  4332. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  4333. return needRestart, err
  4334. }