client.go 101 KB

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