client.go 121 KB

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