1
0

client.go 108 KB

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