client.go 109 KB

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