client.go 98 KB

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