client.go 108 KB

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