client.go 101 KB

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