client.go 101 KB

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