client.go 118 KB

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