client.go 94 KB

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