client.go 85 KB

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