client.go 102 KB

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