client.go 110 KB

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