client.go 95 KB

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