client.go 101 KB

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