client.go 100 KB

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