client.go 120 KB

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