1
0

client.go 101 KB

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