client.go 117 KB

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