1
0

client.go 102 KB

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