client.go 101 KB

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