1
0

client.go 107 KB

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