client.go 115 KB

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