client.go 117 KB

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