inbound.go 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600
  1. // Package service provides business logic services for the 3x-ui web panel,
  2. // including inbound/outbound management, user administration, settings, and Xray integration.
  3. package service
  4. import (
  5. "encoding/json"
  6. "fmt"
  7. "sort"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/mhsanaei/3x-ui/v2/database"
  12. "github.com/mhsanaei/3x-ui/v2/database/model"
  13. "github.com/mhsanaei/3x-ui/v2/logger"
  14. "github.com/mhsanaei/3x-ui/v2/util/common"
  15. "github.com/mhsanaei/3x-ui/v2/xray"
  16. "gorm.io/gorm"
  17. )
  18. // InboundService provides business logic for managing Xray inbound configurations.
  19. // It handles CRUD operations for inbounds, client management, traffic monitoring,
  20. // and integration with the Xray API for real-time updates.
  21. type InboundService struct {
  22. xrayApi xray.XrayAPI
  23. }
  24. // GetInbounds retrieves all inbounds for a specific user.
  25. // Returns a slice of inbound models with their associated client statistics.
  26. func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) {
  27. db := database.GetDB()
  28. var inbounds []*model.Inbound
  29. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Find(&inbounds).Error
  30. if err != nil && err != gorm.ErrRecordNotFound {
  31. return nil, err
  32. }
  33. // Enrich client stats with UUID/SubId from inbound settings
  34. for _, inbound := range inbounds {
  35. clients, _ := s.GetClients(inbound)
  36. if len(clients) == 0 || len(inbound.ClientStats) == 0 {
  37. continue
  38. }
  39. // Build a map email -> client
  40. cMap := make(map[string]model.Client, len(clients))
  41. for _, c := range clients {
  42. cMap[strings.ToLower(c.Email)] = c
  43. }
  44. for i := range inbound.ClientStats {
  45. email := strings.ToLower(inbound.ClientStats[i].Email)
  46. if c, ok := cMap[email]; ok {
  47. inbound.ClientStats[i].UUID = c.ID
  48. inbound.ClientStats[i].SubId = c.SubID
  49. }
  50. }
  51. }
  52. return inbounds, nil
  53. }
  54. // GetAllInbounds retrieves all inbounds from the database.
  55. // Returns a slice of all inbound models with their associated client statistics.
  56. func (s *InboundService) GetAllInbounds() ([]*model.Inbound, error) {
  57. db := database.GetDB()
  58. var inbounds []*model.Inbound
  59. err := db.Model(model.Inbound{}).Preload("ClientStats").Find(&inbounds).Error
  60. if err != nil && err != gorm.ErrRecordNotFound {
  61. return nil, err
  62. }
  63. // Enrich client stats with UUID/SubId from inbound settings
  64. for _, inbound := range inbounds {
  65. clients, _ := s.GetClients(inbound)
  66. if len(clients) == 0 || len(inbound.ClientStats) == 0 {
  67. continue
  68. }
  69. cMap := make(map[string]model.Client, len(clients))
  70. for _, c := range clients {
  71. cMap[strings.ToLower(c.Email)] = c
  72. }
  73. for i := range inbound.ClientStats {
  74. email := strings.ToLower(inbound.ClientStats[i].Email)
  75. if c, ok := cMap[email]; ok {
  76. inbound.ClientStats[i].UUID = c.ID
  77. inbound.ClientStats[i].SubId = c.SubID
  78. }
  79. }
  80. }
  81. return inbounds, nil
  82. }
  83. func (s *InboundService) GetInboundsByTrafficReset(period string) ([]*model.Inbound, error) {
  84. db := database.GetDB()
  85. var inbounds []*model.Inbound
  86. err := db.Model(model.Inbound{}).Where("traffic_reset = ?", period).Find(&inbounds).Error
  87. if err != nil && err != gorm.ErrRecordNotFound {
  88. return nil, err
  89. }
  90. return inbounds, nil
  91. }
  92. func (s *InboundService) checkPortExist(listen string, port int, ignoreId int) (bool, error) {
  93. db := database.GetDB()
  94. if listen == "" || listen == "0.0.0.0" || listen == "::" || listen == "::0" {
  95. db = db.Model(model.Inbound{}).Where("port = ?", port)
  96. } else {
  97. db = db.Model(model.Inbound{}).
  98. Where("port = ?", port).
  99. Where(
  100. db.Model(model.Inbound{}).Where(
  101. "listen = ?", listen,
  102. ).Or(
  103. "listen = \"\"",
  104. ).Or(
  105. "listen = \"0.0.0.0\"",
  106. ).Or(
  107. "listen = \"::\"",
  108. ).Or(
  109. "listen = \"::0\""))
  110. }
  111. if ignoreId > 0 {
  112. db = db.Where("id != ?", ignoreId)
  113. }
  114. var count int64
  115. err := db.Count(&count).Error
  116. if err != nil {
  117. return false, err
  118. }
  119. return count > 0, nil
  120. }
  121. func (s *InboundService) GetClients(inbound *model.Inbound) ([]model.Client, error) {
  122. settings := map[string][]model.Client{}
  123. json.Unmarshal([]byte(inbound.Settings), &settings)
  124. if settings == nil {
  125. return nil, fmt.Errorf("setting is null")
  126. }
  127. clients := settings["clients"]
  128. if clients == nil {
  129. return nil, nil
  130. }
  131. return clients, nil
  132. }
  133. func (s *InboundService) getAllEmails() ([]string, error) {
  134. db := database.GetDB()
  135. var emails []string
  136. err := db.Raw(`
  137. SELECT JSON_EXTRACT(client.value, '$.email')
  138. FROM inbounds,
  139. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  140. `).Scan(&emails).Error
  141. if err != nil {
  142. return nil, err
  143. }
  144. return emails, nil
  145. }
  146. func (s *InboundService) contains(slice []string, str string) bool {
  147. lowerStr := strings.ToLower(str)
  148. for _, s := range slice {
  149. if strings.ToLower(s) == lowerStr {
  150. return true
  151. }
  152. }
  153. return false
  154. }
  155. func (s *InboundService) checkEmailsExistForClients(clients []model.Client) (string, error) {
  156. allEmails, err := s.getAllEmails()
  157. if err != nil {
  158. return "", err
  159. }
  160. var emails []string
  161. for _, client := range clients {
  162. if client.Email != "" {
  163. if s.contains(emails, client.Email) {
  164. return client.Email, nil
  165. }
  166. if s.contains(allEmails, client.Email) {
  167. return client.Email, nil
  168. }
  169. emails = append(emails, client.Email)
  170. }
  171. }
  172. return "", nil
  173. }
  174. func (s *InboundService) checkEmailExistForInbound(inbound *model.Inbound) (string, error) {
  175. clients, err := s.GetClients(inbound)
  176. if err != nil {
  177. return "", err
  178. }
  179. allEmails, err := s.getAllEmails()
  180. if err != nil {
  181. return "", err
  182. }
  183. var emails []string
  184. for _, client := range clients {
  185. if client.Email != "" {
  186. if s.contains(emails, client.Email) {
  187. return client.Email, nil
  188. }
  189. if s.contains(allEmails, client.Email) {
  190. return client.Email, nil
  191. }
  192. emails = append(emails, client.Email)
  193. }
  194. }
  195. return "", nil
  196. }
  197. // AddInbound creates a new inbound configuration.
  198. // It validates port uniqueness, client email uniqueness, and required fields,
  199. // then saves the inbound to the database and optionally adds it to the running Xray instance.
  200. // Returns the created inbound, whether Xray needs restart, and any error.
  201. func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  202. exist, err := s.checkPortExist(inbound.Listen, inbound.Port, 0)
  203. if err != nil {
  204. return inbound, false, err
  205. }
  206. if exist {
  207. return inbound, false, common.NewError("Port already exists:", inbound.Port)
  208. }
  209. existEmail, err := s.checkEmailExistForInbound(inbound)
  210. if err != nil {
  211. return inbound, false, err
  212. }
  213. if existEmail != "" {
  214. return inbound, false, common.NewError("Duplicate email:", existEmail)
  215. }
  216. clients, err := s.GetClients(inbound)
  217. if err != nil {
  218. return inbound, false, err
  219. }
  220. // Ensure created_at and updated_at on clients in settings
  221. if len(clients) > 0 {
  222. var settings map[string]any
  223. if err2 := json.Unmarshal([]byte(inbound.Settings), &settings); err2 == nil && settings != nil {
  224. now := time.Now().Unix() * 1000
  225. updatedClients := make([]model.Client, 0, len(clients))
  226. for _, c := range clients {
  227. if c.CreatedAt == 0 {
  228. c.CreatedAt = now
  229. }
  230. c.UpdatedAt = now
  231. updatedClients = append(updatedClients, c)
  232. }
  233. settings["clients"] = updatedClients
  234. if bs, err3 := json.MarshalIndent(settings, "", " "); err3 == nil {
  235. inbound.Settings = string(bs)
  236. } else {
  237. logger.Debug("Unable to marshal inbound settings with timestamps:", err3)
  238. }
  239. } else if err2 != nil {
  240. logger.Debug("Unable to parse inbound settings for timestamps:", err2)
  241. }
  242. }
  243. // Secure client ID
  244. for _, client := range clients {
  245. switch inbound.Protocol {
  246. case "trojan":
  247. if client.Password == "" {
  248. return inbound, false, common.NewError("empty client ID")
  249. }
  250. case "shadowsocks":
  251. if client.Email == "" {
  252. return inbound, false, common.NewError("empty client ID")
  253. }
  254. case "hysteria":
  255. if client.Auth == "" {
  256. return inbound, false, common.NewError("empty client ID")
  257. }
  258. default:
  259. if client.ID == "" {
  260. return inbound, false, common.NewError("empty client ID")
  261. }
  262. }
  263. }
  264. db := database.GetDB()
  265. tx := db.Begin()
  266. defer func() {
  267. if err == nil {
  268. tx.Commit()
  269. } else {
  270. tx.Rollback()
  271. }
  272. }()
  273. err = tx.Save(inbound).Error
  274. if err == nil {
  275. if len(inbound.ClientStats) == 0 {
  276. for _, client := range clients {
  277. s.AddClientStat(tx, inbound.Id, &client)
  278. }
  279. }
  280. } else {
  281. return inbound, false, err
  282. }
  283. needRestart := false
  284. if inbound.Enable {
  285. s.xrayApi.Init(p.GetAPIPort())
  286. inboundJson, err1 := json.MarshalIndent(inbound.GenXrayInboundConfig(), "", " ")
  287. if err1 != nil {
  288. logger.Debug("Unable to marshal inbound config:", err1)
  289. }
  290. err1 = s.xrayApi.AddInbound(inboundJson)
  291. if err1 == nil {
  292. logger.Debug("New inbound added by api:", inbound.Tag)
  293. } else {
  294. logger.Debug("Unable to add inbound by api:", err1)
  295. needRestart = true
  296. }
  297. s.xrayApi.Close()
  298. }
  299. return inbound, needRestart, err
  300. }
  301. // DelInbound deletes an inbound configuration by ID.
  302. // It removes the inbound from the database and the running Xray instance if active.
  303. // Returns whether Xray needs restart and any error.
  304. func (s *InboundService) DelInbound(id int) (bool, error) {
  305. db := database.GetDB()
  306. var tag string
  307. needRestart := false
  308. result := db.Model(model.Inbound{}).Select("tag").Where("id = ? and enable = ?", id, true).First(&tag)
  309. if result.Error == nil {
  310. s.xrayApi.Init(p.GetAPIPort())
  311. err1 := s.xrayApi.DelInbound(tag)
  312. if err1 == nil {
  313. logger.Debug("Inbound deleted by api:", tag)
  314. } else {
  315. logger.Debug("Unable to delete inbound by api:", err1)
  316. needRestart = true
  317. }
  318. s.xrayApi.Close()
  319. } else {
  320. logger.Debug("No enabled inbound founded to removing by api", tag)
  321. }
  322. // Delete client traffics of inbounds
  323. err := db.Where("inbound_id = ?", id).Delete(xray.ClientTraffic{}).Error
  324. if err != nil {
  325. return false, err
  326. }
  327. inbound, err := s.GetInbound(id)
  328. if err != nil {
  329. return false, err
  330. }
  331. clients, err := s.GetClients(inbound)
  332. if err != nil {
  333. return false, err
  334. }
  335. for _, client := range clients {
  336. err := s.DelClientIPs(db, client.Email)
  337. if err != nil {
  338. return false, err
  339. }
  340. }
  341. return needRestart, db.Delete(model.Inbound{}, id).Error
  342. }
  343. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  344. db := database.GetDB()
  345. inbound := &model.Inbound{}
  346. err := db.Model(model.Inbound{}).First(inbound, id).Error
  347. if err != nil {
  348. return nil, err
  349. }
  350. return inbound, nil
  351. }
  352. // UpdateInbound modifies an existing inbound configuration.
  353. // It validates changes, updates the database, and syncs with the running Xray instance.
  354. // Returns the updated inbound, whether Xray needs restart, and any error.
  355. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  356. exist, err := s.checkPortExist(inbound.Listen, inbound.Port, inbound.Id)
  357. if err != nil {
  358. return inbound, false, err
  359. }
  360. if exist {
  361. return inbound, false, common.NewError("Port already exists:", inbound.Port)
  362. }
  363. oldInbound, err := s.GetInbound(inbound.Id)
  364. if err != nil {
  365. return inbound, false, err
  366. }
  367. tag := oldInbound.Tag
  368. db := database.GetDB()
  369. tx := db.Begin()
  370. defer func() {
  371. if err != nil {
  372. tx.Rollback()
  373. } else {
  374. tx.Commit()
  375. }
  376. }()
  377. err = s.updateClientTraffics(tx, oldInbound, inbound)
  378. if err != nil {
  379. return inbound, false, err
  380. }
  381. // Ensure created_at and updated_at exist in inbound.Settings clients
  382. {
  383. var oldSettings map[string]any
  384. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  385. emailToCreated := map[string]int64{}
  386. emailToUpdated := map[string]int64{}
  387. if oldSettings != nil {
  388. if oc, ok := oldSettings["clients"].([]any); ok {
  389. for _, it := range oc {
  390. if m, ok2 := it.(map[string]any); ok2 {
  391. if email, ok3 := m["email"].(string); ok3 {
  392. switch v := m["created_at"].(type) {
  393. case float64:
  394. emailToCreated[email] = int64(v)
  395. case int64:
  396. emailToCreated[email] = v
  397. }
  398. switch v := m["updated_at"].(type) {
  399. case float64:
  400. emailToUpdated[email] = int64(v)
  401. case int64:
  402. emailToUpdated[email] = v
  403. }
  404. }
  405. }
  406. }
  407. }
  408. }
  409. var newSettings map[string]any
  410. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  411. now := time.Now().Unix() * 1000
  412. if nSlice, ok := newSettings["clients"].([]any); ok {
  413. for i := range nSlice {
  414. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  415. email, _ := m["email"].(string)
  416. if _, ok3 := m["created_at"]; !ok3 {
  417. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  418. m["created_at"] = v
  419. } else {
  420. m["created_at"] = now
  421. }
  422. }
  423. // Preserve client's updated_at if present; do not bump on parent inbound update
  424. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  425. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  426. m["updated_at"] = v
  427. }
  428. }
  429. nSlice[i] = m
  430. }
  431. }
  432. newSettings["clients"] = nSlice
  433. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  434. inbound.Settings = string(bs)
  435. }
  436. }
  437. }
  438. }
  439. oldInbound.Up = inbound.Up
  440. oldInbound.Down = inbound.Down
  441. oldInbound.Total = inbound.Total
  442. oldInbound.Remark = inbound.Remark
  443. oldInbound.Enable = inbound.Enable
  444. oldInbound.ExpiryTime = inbound.ExpiryTime
  445. oldInbound.TrafficReset = inbound.TrafficReset
  446. oldInbound.Listen = inbound.Listen
  447. oldInbound.Port = inbound.Port
  448. oldInbound.Protocol = inbound.Protocol
  449. oldInbound.Settings = inbound.Settings
  450. oldInbound.StreamSettings = inbound.StreamSettings
  451. oldInbound.Sniffing = inbound.Sniffing
  452. if inbound.Listen == "" || inbound.Listen == "0.0.0.0" || inbound.Listen == "::" || inbound.Listen == "::0" {
  453. oldInbound.Tag = fmt.Sprintf("inbound-%v", inbound.Port)
  454. } else {
  455. oldInbound.Tag = fmt.Sprintf("inbound-%v:%v", inbound.Listen, inbound.Port)
  456. }
  457. needRestart := false
  458. s.xrayApi.Init(p.GetAPIPort())
  459. if s.xrayApi.DelInbound(tag) == nil {
  460. logger.Debug("Old inbound deleted by api:", tag)
  461. }
  462. if inbound.Enable {
  463. runtimeInbound, err2 := s.buildRuntimeInboundForAPI(tx, oldInbound)
  464. if err2 != nil {
  465. logger.Debug("Unable to prepare runtime inbound config:", err2)
  466. needRestart = true
  467. } else {
  468. inboundJson, err2 := json.MarshalIndent(runtimeInbound.GenXrayInboundConfig(), "", " ")
  469. if err2 != nil {
  470. logger.Debug("Unable to marshal updated inbound config:", err2)
  471. needRestart = true
  472. } else {
  473. err2 = s.xrayApi.AddInbound(inboundJson)
  474. if err2 == nil {
  475. logger.Debug("Updated inbound added by api:", oldInbound.Tag)
  476. } else {
  477. logger.Debug("Unable to update inbound by api:", err2)
  478. needRestart = true
  479. }
  480. }
  481. }
  482. }
  483. s.xrayApi.Close()
  484. return inbound, needRestart, tx.Save(oldInbound).Error
  485. }
  486. func (s *InboundService) buildRuntimeInboundForAPI(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  487. if inbound == nil {
  488. return nil, fmt.Errorf("inbound is nil")
  489. }
  490. runtimeInbound := *inbound
  491. settings := map[string]any{}
  492. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  493. return nil, err
  494. }
  495. clients, ok := settings["clients"].([]any)
  496. if !ok {
  497. return &runtimeInbound, nil
  498. }
  499. var clientStats []xray.ClientTraffic
  500. err := tx.Model(xray.ClientTraffic{}).
  501. Where("inbound_id = ?", inbound.Id).
  502. Select("email", "enable").
  503. Find(&clientStats).Error
  504. if err != nil {
  505. return nil, err
  506. }
  507. enableMap := make(map[string]bool, len(clientStats))
  508. for _, clientTraffic := range clientStats {
  509. enableMap[clientTraffic.Email] = clientTraffic.Enable
  510. }
  511. finalClients := make([]any, 0, len(clients))
  512. for _, client := range clients {
  513. c, ok := client.(map[string]any)
  514. if !ok {
  515. continue
  516. }
  517. email, _ := c["email"].(string)
  518. if enable, exists := enableMap[email]; exists && !enable {
  519. continue
  520. }
  521. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  522. continue
  523. }
  524. finalClients = append(finalClients, c)
  525. }
  526. settings["clients"] = finalClients
  527. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  528. if err != nil {
  529. return nil, err
  530. }
  531. runtimeInbound.Settings = string(modifiedSettings)
  532. return &runtimeInbound, nil
  533. }
  534. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  535. oldClients, err := s.GetClients(oldInbound)
  536. if err != nil {
  537. return err
  538. }
  539. newClients, err := s.GetClients(newInbound)
  540. if err != nil {
  541. return err
  542. }
  543. var emailExists bool
  544. for _, oldClient := range oldClients {
  545. emailExists = false
  546. for _, newClient := range newClients {
  547. if oldClient.Email == newClient.Email {
  548. emailExists = true
  549. break
  550. }
  551. }
  552. if !emailExists {
  553. err = s.DelClientStat(tx, oldClient.Email)
  554. if err != nil {
  555. return err
  556. }
  557. }
  558. }
  559. for _, newClient := range newClients {
  560. emailExists = false
  561. for _, oldClient := range oldClients {
  562. if newClient.Email == oldClient.Email {
  563. emailExists = true
  564. break
  565. }
  566. }
  567. if !emailExists {
  568. err = s.AddClientStat(tx, oldInbound.Id, &newClient)
  569. if err != nil {
  570. return err
  571. }
  572. }
  573. }
  574. return nil
  575. }
  576. func (s *InboundService) AddInboundClient(data *model.Inbound) (bool, error) {
  577. clients, err := s.GetClients(data)
  578. if err != nil {
  579. return false, err
  580. }
  581. var settings map[string]any
  582. err = json.Unmarshal([]byte(data.Settings), &settings)
  583. if err != nil {
  584. return false, err
  585. }
  586. interfaceClients := settings["clients"].([]any)
  587. // Add timestamps for new clients being appended
  588. nowTs := time.Now().Unix() * 1000
  589. for i := range interfaceClients {
  590. if cm, ok := interfaceClients[i].(map[string]any); ok {
  591. if _, ok2 := cm["created_at"]; !ok2 {
  592. cm["created_at"] = nowTs
  593. }
  594. cm["updated_at"] = nowTs
  595. interfaceClients[i] = cm
  596. }
  597. }
  598. existEmail, err := s.checkEmailsExistForClients(clients)
  599. if err != nil {
  600. return false, err
  601. }
  602. if existEmail != "" {
  603. return false, common.NewError("Duplicate email:", existEmail)
  604. }
  605. oldInbound, err := s.GetInbound(data.Id)
  606. if err != nil {
  607. return false, err
  608. }
  609. // Secure client ID
  610. for _, client := range clients {
  611. switch oldInbound.Protocol {
  612. case "trojan":
  613. if client.Password == "" {
  614. return false, common.NewError("empty client ID")
  615. }
  616. case "shadowsocks":
  617. if client.Email == "" {
  618. return false, common.NewError("empty client ID")
  619. }
  620. case "hysteria":
  621. if client.Auth == "" {
  622. return false, common.NewError("empty client ID")
  623. }
  624. default:
  625. if client.ID == "" {
  626. return false, common.NewError("empty client ID")
  627. }
  628. }
  629. }
  630. var oldSettings map[string]any
  631. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  632. if err != nil {
  633. return false, err
  634. }
  635. oldClients := oldSettings["clients"].([]any)
  636. oldClients = append(oldClients, interfaceClients...)
  637. oldSettings["clients"] = oldClients
  638. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  639. if err != nil {
  640. return false, err
  641. }
  642. oldInbound.Settings = string(newSettings)
  643. db := database.GetDB()
  644. tx := db.Begin()
  645. defer func() {
  646. if err != nil {
  647. tx.Rollback()
  648. } else {
  649. tx.Commit()
  650. }
  651. }()
  652. needRestart := false
  653. s.xrayApi.Init(p.GetAPIPort())
  654. for _, client := range clients {
  655. if len(client.Email) > 0 {
  656. s.AddClientStat(tx, data.Id, &client)
  657. if client.Enable {
  658. cipher := ""
  659. if oldInbound.Protocol == "shadowsocks" {
  660. cipher = oldSettings["method"].(string)
  661. }
  662. err1 := s.xrayApi.AddUser(string(oldInbound.Protocol), oldInbound.Tag, map[string]any{
  663. "email": client.Email,
  664. "id": client.ID,
  665. "auth": client.Auth,
  666. "security": client.Security,
  667. "flow": client.Flow,
  668. "password": client.Password,
  669. "cipher": cipher,
  670. })
  671. if err1 == nil {
  672. logger.Debug("Client added by api:", client.Email)
  673. } else {
  674. logger.Debug("Error in adding client by api:", err1)
  675. needRestart = true
  676. }
  677. }
  678. } else {
  679. needRestart = true
  680. }
  681. }
  682. s.xrayApi.Close()
  683. return needRestart, tx.Save(oldInbound).Error
  684. }
  685. func (s *InboundService) DelInboundClient(inboundId int, clientId string) (bool, error) {
  686. oldInbound, err := s.GetInbound(inboundId)
  687. if err != nil {
  688. logger.Error("Load Old Data Error")
  689. return false, err
  690. }
  691. var settings map[string]any
  692. err = json.Unmarshal([]byte(oldInbound.Settings), &settings)
  693. if err != nil {
  694. return false, err
  695. }
  696. email := ""
  697. client_key := "id"
  698. switch oldInbound.Protocol {
  699. case "trojan":
  700. client_key = "password"
  701. case "shadowsocks":
  702. client_key = "email"
  703. case "hysteria":
  704. client_key = "auth"
  705. }
  706. interfaceClients := settings["clients"].([]any)
  707. var newClients []any
  708. needApiDel := false
  709. for _, client := range interfaceClients {
  710. c := client.(map[string]any)
  711. c_id := c[client_key].(string)
  712. if c_id == clientId {
  713. email, _ = c["email"].(string)
  714. needApiDel, _ = c["enable"].(bool)
  715. } else {
  716. newClients = append(newClients, client)
  717. }
  718. }
  719. if len(newClients) == 0 {
  720. return false, common.NewError("no client remained in Inbound")
  721. }
  722. settings["clients"] = newClients
  723. newSettings, err := json.MarshalIndent(settings, "", " ")
  724. if err != nil {
  725. return false, err
  726. }
  727. oldInbound.Settings = string(newSettings)
  728. db := database.GetDB()
  729. err = s.DelClientIPs(db, email)
  730. if err != nil {
  731. logger.Error("Error in delete client IPs")
  732. return false, err
  733. }
  734. needRestart := false
  735. if len(email) > 0 {
  736. notDepleted := true
  737. err = db.Model(xray.ClientTraffic{}).Select("enable").Where("email = ?", email).First(&notDepleted).Error
  738. if err != nil {
  739. logger.Error("Get stats error")
  740. return false, err
  741. }
  742. err = s.DelClientStat(db, email)
  743. if err != nil {
  744. logger.Error("Delete stats Data Error")
  745. return false, err
  746. }
  747. if needApiDel && notDepleted {
  748. s.xrayApi.Init(p.GetAPIPort())
  749. err1 := s.xrayApi.RemoveUser(oldInbound.Tag, email)
  750. if err1 == nil {
  751. logger.Debug("Client deleted by api:", email)
  752. needRestart = false
  753. } else {
  754. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  755. logger.Debug("User is already deleted. Nothing to do more...")
  756. } else {
  757. logger.Debug("Error in deleting client by api:", err1)
  758. needRestart = true
  759. }
  760. }
  761. s.xrayApi.Close()
  762. }
  763. }
  764. return needRestart, db.Save(oldInbound).Error
  765. }
  766. func (s *InboundService) UpdateInboundClient(data *model.Inbound, clientId string) (bool, error) {
  767. // TODO: check if TrafficReset field is updating
  768. clients, err := s.GetClients(data)
  769. if err != nil {
  770. return false, err
  771. }
  772. var settings map[string]any
  773. err = json.Unmarshal([]byte(data.Settings), &settings)
  774. if err != nil {
  775. return false, err
  776. }
  777. interfaceClients := settings["clients"].([]any)
  778. oldInbound, err := s.GetInbound(data.Id)
  779. if err != nil {
  780. return false, err
  781. }
  782. oldClients, err := s.GetClients(oldInbound)
  783. if err != nil {
  784. return false, err
  785. }
  786. oldEmail := ""
  787. newClientId := ""
  788. clientIndex := -1
  789. for index, oldClient := range oldClients {
  790. oldClientId := ""
  791. switch oldInbound.Protocol {
  792. case "trojan":
  793. oldClientId = oldClient.Password
  794. newClientId = clients[0].Password
  795. case "shadowsocks":
  796. oldClientId = oldClient.Email
  797. newClientId = clients[0].Email
  798. case "hysteria":
  799. oldClientId = oldClient.Auth
  800. newClientId = clients[0].Auth
  801. default:
  802. oldClientId = oldClient.ID
  803. newClientId = clients[0].ID
  804. }
  805. if clientId == oldClientId {
  806. oldEmail = oldClient.Email
  807. clientIndex = index
  808. break
  809. }
  810. }
  811. // Validate new client ID
  812. if newClientId == "" || clientIndex == -1 {
  813. return false, common.NewError("empty client ID")
  814. }
  815. if len(clients[0].Email) > 0 && clients[0].Email != oldEmail {
  816. existEmail, err := s.checkEmailsExistForClients(clients)
  817. if err != nil {
  818. return false, err
  819. }
  820. if existEmail != "" {
  821. return false, common.NewError("Duplicate email:", existEmail)
  822. }
  823. }
  824. var oldSettings map[string]any
  825. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  826. if err != nil {
  827. return false, err
  828. }
  829. settingsClients := oldSettings["clients"].([]any)
  830. // Preserve created_at and set updated_at for the replacing client
  831. var preservedCreated any
  832. if clientIndex >= 0 && clientIndex < len(settingsClients) {
  833. if oldMap, ok := settingsClients[clientIndex].(map[string]any); ok {
  834. if v, ok2 := oldMap["created_at"]; ok2 {
  835. preservedCreated = v
  836. }
  837. }
  838. }
  839. if len(interfaceClients) > 0 {
  840. if newMap, ok := interfaceClients[0].(map[string]any); ok {
  841. if preservedCreated == nil {
  842. preservedCreated = time.Now().Unix() * 1000
  843. }
  844. newMap["created_at"] = preservedCreated
  845. newMap["updated_at"] = time.Now().Unix() * 1000
  846. interfaceClients[0] = newMap
  847. }
  848. }
  849. settingsClients[clientIndex] = interfaceClients[0]
  850. oldSettings["clients"] = settingsClients
  851. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  852. if err != nil {
  853. return false, err
  854. }
  855. oldInbound.Settings = string(newSettings)
  856. db := database.GetDB()
  857. tx := db.Begin()
  858. defer func() {
  859. if err != nil {
  860. tx.Rollback()
  861. } else {
  862. tx.Commit()
  863. }
  864. }()
  865. if len(clients[0].Email) > 0 {
  866. if len(oldEmail) > 0 {
  867. err = s.UpdateClientStat(tx, oldEmail, &clients[0])
  868. if err != nil {
  869. return false, err
  870. }
  871. err = s.UpdateClientIPs(tx, oldEmail, clients[0].Email)
  872. if err != nil {
  873. return false, err
  874. }
  875. } else {
  876. s.AddClientStat(tx, data.Id, &clients[0])
  877. }
  878. } else {
  879. err = s.DelClientStat(tx, oldEmail)
  880. if err != nil {
  881. return false, err
  882. }
  883. err = s.DelClientIPs(tx, oldEmail)
  884. if err != nil {
  885. return false, err
  886. }
  887. }
  888. needRestart := false
  889. if len(oldEmail) > 0 {
  890. s.xrayApi.Init(p.GetAPIPort())
  891. if oldClients[clientIndex].Enable {
  892. err1 := s.xrayApi.RemoveUser(oldInbound.Tag, oldEmail)
  893. if err1 == nil {
  894. logger.Debug("Old client deleted by api:", oldEmail)
  895. } else {
  896. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", oldEmail)) {
  897. logger.Debug("User is already deleted. Nothing to do more...")
  898. } else {
  899. logger.Debug("Error in deleting client by api:", err1)
  900. needRestart = true
  901. }
  902. }
  903. }
  904. if clients[0].Enable {
  905. cipher := ""
  906. if oldInbound.Protocol == "shadowsocks" {
  907. cipher = oldSettings["method"].(string)
  908. }
  909. err1 := s.xrayApi.AddUser(string(oldInbound.Protocol), oldInbound.Tag, map[string]any{
  910. "email": clients[0].Email,
  911. "id": clients[0].ID,
  912. "security": clients[0].Security,
  913. "flow": clients[0].Flow,
  914. "auth": clients[0].Auth,
  915. "password": clients[0].Password,
  916. "cipher": cipher,
  917. })
  918. if err1 == nil {
  919. logger.Debug("Client edited by api:", clients[0].Email)
  920. } else {
  921. logger.Debug("Error in adding client by api:", err1)
  922. needRestart = true
  923. }
  924. }
  925. s.xrayApi.Close()
  926. } else {
  927. logger.Debug("Client old email not found")
  928. needRestart = true
  929. }
  930. return needRestart, tx.Save(oldInbound).Error
  931. }
  932. func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (error, bool) {
  933. var err error
  934. db := database.GetDB()
  935. tx := db.Begin()
  936. defer func() {
  937. if err != nil {
  938. tx.Rollback()
  939. } else {
  940. tx.Commit()
  941. }
  942. }()
  943. err = s.addInboundTraffic(tx, inboundTraffics)
  944. if err != nil {
  945. return err, false
  946. }
  947. err = s.addClientTraffic(tx, clientTraffics)
  948. if err != nil {
  949. return err, false
  950. }
  951. needRestart0, count, err := s.autoRenewClients(tx)
  952. if err != nil {
  953. logger.Warning("Error in renew clients:", err)
  954. } else if count > 0 {
  955. logger.Debugf("%v clients renewed", count)
  956. }
  957. needRestart1, count, err := s.disableInvalidClients(tx)
  958. if err != nil {
  959. logger.Warning("Error in disabling invalid clients:", err)
  960. } else if count > 0 {
  961. logger.Debugf("%v clients disabled", count)
  962. }
  963. needRestart2, count, err := s.disableInvalidInbounds(tx)
  964. if err != nil {
  965. logger.Warning("Error in disabling invalid inbounds:", err)
  966. } else if count > 0 {
  967. logger.Debugf("%v inbounds disabled", count)
  968. }
  969. return nil, (needRestart0 || needRestart1 || needRestart2)
  970. }
  971. func (s *InboundService) addInboundTraffic(tx *gorm.DB, traffics []*xray.Traffic) error {
  972. if len(traffics) == 0 {
  973. return nil
  974. }
  975. var err error
  976. for _, traffic := range traffics {
  977. if traffic.IsInbound {
  978. err = tx.Model(&model.Inbound{}).Where("tag = ?", traffic.Tag).
  979. Updates(map[string]any{
  980. "up": gorm.Expr("up + ?", traffic.Up),
  981. "down": gorm.Expr("down + ?", traffic.Down),
  982. "all_time": gorm.Expr("COALESCE(all_time, 0) + ?", traffic.Up+traffic.Down),
  983. }).Error
  984. if err != nil {
  985. return err
  986. }
  987. }
  988. }
  989. return nil
  990. }
  991. func (s *InboundService) addClientTraffic(tx *gorm.DB, traffics []*xray.ClientTraffic) (err error) {
  992. if len(traffics) == 0 {
  993. // Empty onlineUsers
  994. if p != nil {
  995. p.SetOnlineClients(make([]string, 0))
  996. }
  997. return nil
  998. }
  999. onlineClients := make([]string, 0)
  1000. emails := make([]string, 0, len(traffics))
  1001. for _, traffic := range traffics {
  1002. emails = append(emails, traffic.Email)
  1003. }
  1004. dbClientTraffics := make([]*xray.ClientTraffic, 0, len(traffics))
  1005. err = tx.Model(xray.ClientTraffic{}).Where("email IN (?)", emails).Find(&dbClientTraffics).Error
  1006. if err != nil {
  1007. return err
  1008. }
  1009. // Avoid empty slice error
  1010. if len(dbClientTraffics) == 0 {
  1011. return nil
  1012. }
  1013. dbClientTraffics, err = s.adjustTraffics(tx, dbClientTraffics)
  1014. if err != nil {
  1015. return err
  1016. }
  1017. for dbTraffic_index := range dbClientTraffics {
  1018. for traffic_index := range traffics {
  1019. if dbClientTraffics[dbTraffic_index].Email == traffics[traffic_index].Email {
  1020. dbClientTraffics[dbTraffic_index].Up += traffics[traffic_index].Up
  1021. dbClientTraffics[dbTraffic_index].Down += traffics[traffic_index].Down
  1022. dbClientTraffics[dbTraffic_index].AllTime += (traffics[traffic_index].Up + traffics[traffic_index].Down)
  1023. // Add user in onlineUsers array on traffic
  1024. if traffics[traffic_index].Up+traffics[traffic_index].Down > 0 {
  1025. onlineClients = append(onlineClients, traffics[traffic_index].Email)
  1026. dbClientTraffics[dbTraffic_index].LastOnline = time.Now().UnixMilli()
  1027. }
  1028. break
  1029. }
  1030. }
  1031. }
  1032. // Set onlineUsers
  1033. p.SetOnlineClients(onlineClients)
  1034. err = tx.Save(dbClientTraffics).Error
  1035. if err != nil {
  1036. logger.Warning("AddClientTraffic update data ", err)
  1037. }
  1038. return nil
  1039. }
  1040. func (s *InboundService) adjustTraffics(tx *gorm.DB, dbClientTraffics []*xray.ClientTraffic) ([]*xray.ClientTraffic, error) {
  1041. inboundIds := make([]int, 0, len(dbClientTraffics))
  1042. for _, dbClientTraffic := range dbClientTraffics {
  1043. if dbClientTraffic.ExpiryTime < 0 {
  1044. inboundIds = append(inboundIds, dbClientTraffic.InboundId)
  1045. }
  1046. }
  1047. if len(inboundIds) > 0 {
  1048. var inbounds []*model.Inbound
  1049. err := tx.Model(model.Inbound{}).Where("id IN (?)", inboundIds).Find(&inbounds).Error
  1050. if err != nil {
  1051. return nil, err
  1052. }
  1053. for inbound_index := range inbounds {
  1054. settings := map[string]any{}
  1055. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1056. clients, ok := settings["clients"].([]any)
  1057. if ok {
  1058. var newClients []any
  1059. for client_index := range clients {
  1060. c := clients[client_index].(map[string]any)
  1061. for traffic_index := range dbClientTraffics {
  1062. if dbClientTraffics[traffic_index].ExpiryTime < 0 && c["email"] == dbClientTraffics[traffic_index].Email {
  1063. oldExpiryTime := c["expiryTime"].(float64)
  1064. newExpiryTime := (time.Now().Unix() * 1000) - int64(oldExpiryTime)
  1065. c["expiryTime"] = newExpiryTime
  1066. c["updated_at"] = time.Now().Unix() * 1000
  1067. dbClientTraffics[traffic_index].ExpiryTime = newExpiryTime
  1068. break
  1069. }
  1070. }
  1071. // Backfill created_at and updated_at
  1072. if _, ok := c["created_at"]; !ok {
  1073. c["created_at"] = time.Now().Unix() * 1000
  1074. }
  1075. c["updated_at"] = time.Now().Unix() * 1000
  1076. newClients = append(newClients, any(c))
  1077. }
  1078. settings["clients"] = newClients
  1079. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1080. if err != nil {
  1081. return nil, err
  1082. }
  1083. inbounds[inbound_index].Settings = string(modifiedSettings)
  1084. }
  1085. }
  1086. err = tx.Save(inbounds).Error
  1087. if err != nil {
  1088. logger.Warning("AddClientTraffic update inbounds ", err)
  1089. logger.Error(inbounds)
  1090. }
  1091. }
  1092. return dbClientTraffics, nil
  1093. }
  1094. func (s *InboundService) autoRenewClients(tx *gorm.DB) (bool, int64, error) {
  1095. // check for time expired
  1096. var traffics []*xray.ClientTraffic
  1097. now := time.Now().Unix() * 1000
  1098. var err, err1 error
  1099. err = tx.Model(xray.ClientTraffic{}).Where("reset > 0 and expiry_time > 0 and expiry_time <= ?", now).Find(&traffics).Error
  1100. if err != nil {
  1101. return false, 0, err
  1102. }
  1103. // return if there is no client to renew
  1104. if len(traffics) == 0 {
  1105. return false, 0, nil
  1106. }
  1107. var inbound_ids []int
  1108. var inbounds []*model.Inbound
  1109. needRestart := false
  1110. var clientsToAdd []struct {
  1111. protocol string
  1112. tag string
  1113. client map[string]any
  1114. }
  1115. for _, traffic := range traffics {
  1116. inbound_ids = append(inbound_ids, traffic.InboundId)
  1117. }
  1118. err = tx.Model(model.Inbound{}).Where("id IN ?", inbound_ids).Find(&inbounds).Error
  1119. if err != nil {
  1120. return false, 0, err
  1121. }
  1122. for inbound_index := range inbounds {
  1123. settings := map[string]any{}
  1124. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1125. clients := settings["clients"].([]any)
  1126. for client_index := range clients {
  1127. c := clients[client_index].(map[string]any)
  1128. for traffic_index, traffic := range traffics {
  1129. if traffic.Email == c["email"].(string) {
  1130. newExpiryTime := traffic.ExpiryTime
  1131. for newExpiryTime < now {
  1132. newExpiryTime += (int64(traffic.Reset) * 86400000)
  1133. }
  1134. c["expiryTime"] = newExpiryTime
  1135. traffics[traffic_index].ExpiryTime = newExpiryTime
  1136. traffics[traffic_index].Down = 0
  1137. traffics[traffic_index].Up = 0
  1138. if !traffic.Enable {
  1139. traffics[traffic_index].Enable = true
  1140. clientsToAdd = append(clientsToAdd,
  1141. struct {
  1142. protocol string
  1143. tag string
  1144. client map[string]any
  1145. }{
  1146. protocol: string(inbounds[inbound_index].Protocol),
  1147. tag: inbounds[inbound_index].Tag,
  1148. client: c,
  1149. })
  1150. }
  1151. clients[client_index] = any(c)
  1152. break
  1153. }
  1154. }
  1155. }
  1156. settings["clients"] = clients
  1157. newSettings, err := json.MarshalIndent(settings, "", " ")
  1158. if err != nil {
  1159. return false, 0, err
  1160. }
  1161. inbounds[inbound_index].Settings = string(newSettings)
  1162. }
  1163. err = tx.Save(inbounds).Error
  1164. if err != nil {
  1165. return false, 0, err
  1166. }
  1167. err = tx.Save(traffics).Error
  1168. if err != nil {
  1169. return false, 0, err
  1170. }
  1171. if p != nil {
  1172. err1 = s.xrayApi.Init(p.GetAPIPort())
  1173. if err1 != nil {
  1174. return true, int64(len(traffics)), nil
  1175. }
  1176. for _, clientToAdd := range clientsToAdd {
  1177. err1 = s.xrayApi.AddUser(clientToAdd.protocol, clientToAdd.tag, clientToAdd.client)
  1178. if err1 != nil {
  1179. needRestart = true
  1180. }
  1181. }
  1182. s.xrayApi.Close()
  1183. }
  1184. return needRestart, int64(len(traffics)), nil
  1185. }
  1186. func (s *InboundService) disableInvalidInbounds(tx *gorm.DB) (bool, int64, error) {
  1187. now := time.Now().Unix() * 1000
  1188. needRestart := false
  1189. if p != nil {
  1190. var tags []string
  1191. err := tx.Table("inbounds").
  1192. Select("inbounds.tag").
  1193. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  1194. Scan(&tags).Error
  1195. if err != nil {
  1196. return false, 0, err
  1197. }
  1198. s.xrayApi.Init(p.GetAPIPort())
  1199. for _, tag := range tags {
  1200. err1 := s.xrayApi.DelInbound(tag)
  1201. if err1 == nil {
  1202. logger.Debug("Inbound disabled by api:", tag)
  1203. } else {
  1204. logger.Debug("Error in disabling inbound by api:", err1)
  1205. needRestart = true
  1206. }
  1207. }
  1208. s.xrayApi.Close()
  1209. }
  1210. result := tx.Model(model.Inbound{}).
  1211. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  1212. Update("enable", false)
  1213. err := result.Error
  1214. count := result.RowsAffected
  1215. return needRestart, count, err
  1216. }
  1217. func (s *InboundService) disableInvalidClients(tx *gorm.DB) (bool, int64, error) {
  1218. now := time.Now().Unix() * 1000
  1219. needRestart := false
  1220. if p != nil {
  1221. var results []struct {
  1222. Tag string
  1223. Email string
  1224. }
  1225. err := tx.Table("inbounds").
  1226. Select("inbounds.tag, client_traffics.email").
  1227. Joins("JOIN client_traffics ON inbounds.id = client_traffics.inbound_id").
  1228. Where("((client_traffics.total > 0 AND client_traffics.up + client_traffics.down >= client_traffics.total) OR (client_traffics.expiry_time > 0 AND client_traffics.expiry_time <= ?)) AND client_traffics.enable = ?", now, true).
  1229. Scan(&results).Error
  1230. if err != nil {
  1231. return false, 0, err
  1232. }
  1233. s.xrayApi.Init(p.GetAPIPort())
  1234. for _, result := range results {
  1235. err1 := s.xrayApi.RemoveUser(result.Tag, result.Email)
  1236. if err1 == nil {
  1237. logger.Debug("Client disabled by api:", result.Email)
  1238. } else {
  1239. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", result.Email)) {
  1240. logger.Debug("User is already disabled. Nothing to do more...")
  1241. } else {
  1242. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", result.Email)) {
  1243. logger.Debug("User is already disabled. Nothing to do more...")
  1244. } else {
  1245. logger.Debug("Error in disabling client by api:", err1)
  1246. needRestart = true
  1247. }
  1248. }
  1249. }
  1250. }
  1251. s.xrayApi.Close()
  1252. }
  1253. result := tx.Model(xray.ClientTraffic{}).
  1254. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  1255. Update("enable", false)
  1256. err := result.Error
  1257. count := result.RowsAffected
  1258. return needRestart, count, err
  1259. }
  1260. func (s *InboundService) GetInboundTags() (string, error) {
  1261. db := database.GetDB()
  1262. var inboundTags []string
  1263. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  1264. if err != nil && err != gorm.ErrRecordNotFound {
  1265. return "", err
  1266. }
  1267. tags, _ := json.Marshal(inboundTags)
  1268. return string(tags), nil
  1269. }
  1270. func (s *InboundService) MigrationRemoveOrphanedTraffics() {
  1271. db := database.GetDB()
  1272. db.Exec(`
  1273. DELETE FROM client_traffics
  1274. WHERE email NOT IN (
  1275. SELECT JSON_EXTRACT(client.value, '$.email')
  1276. FROM inbounds,
  1277. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  1278. )
  1279. `)
  1280. }
  1281. func (s *InboundService) AddClientStat(tx *gorm.DB, inboundId int, client *model.Client) error {
  1282. clientTraffic := xray.ClientTraffic{}
  1283. clientTraffic.InboundId = inboundId
  1284. clientTraffic.Email = client.Email
  1285. clientTraffic.Total = client.TotalGB
  1286. clientTraffic.ExpiryTime = client.ExpiryTime
  1287. clientTraffic.Enable = client.Enable
  1288. clientTraffic.Up = 0
  1289. clientTraffic.Down = 0
  1290. clientTraffic.Reset = client.Reset
  1291. result := tx.Create(&clientTraffic)
  1292. err := result.Error
  1293. return err
  1294. }
  1295. func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *model.Client) error {
  1296. result := tx.Model(xray.ClientTraffic{}).
  1297. Where("email = ?", email).
  1298. Updates(map[string]any{
  1299. "enable": client.Enable,
  1300. "email": client.Email,
  1301. "total": client.TotalGB,
  1302. "expiry_time": client.ExpiryTime,
  1303. "reset": client.Reset,
  1304. })
  1305. err := result.Error
  1306. return err
  1307. }
  1308. func (s *InboundService) UpdateClientIPs(tx *gorm.DB, oldEmail string, newEmail string) error {
  1309. return tx.Model(model.InboundClientIps{}).Where("client_email = ?", oldEmail).Update("client_email", newEmail).Error
  1310. }
  1311. func (s *InboundService) DelClientStat(tx *gorm.DB, email string) error {
  1312. return tx.Where("email = ?", email).Delete(xray.ClientTraffic{}).Error
  1313. }
  1314. func (s *InboundService) DelClientIPs(tx *gorm.DB, email string) error {
  1315. return tx.Where("client_email = ?", email).Delete(model.InboundClientIps{}).Error
  1316. }
  1317. func (s *InboundService) GetClientInboundByTrafficID(trafficId int) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  1318. db := database.GetDB()
  1319. var traffics []*xray.ClientTraffic
  1320. err = db.Model(xray.ClientTraffic{}).Where("id = ?", trafficId).Find(&traffics).Error
  1321. if err != nil {
  1322. logger.Warningf("Error retrieving ClientTraffic with trafficId %d: %v", trafficId, err)
  1323. return nil, nil, err
  1324. }
  1325. if len(traffics) > 0 {
  1326. inbound, err = s.GetInbound(traffics[0].InboundId)
  1327. return traffics[0], inbound, err
  1328. }
  1329. return nil, nil, nil
  1330. }
  1331. func (s *InboundService) GetClientInboundByEmail(email string) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  1332. db := database.GetDB()
  1333. var traffics []*xray.ClientTraffic
  1334. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error
  1335. if err != nil {
  1336. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  1337. return nil, nil, err
  1338. }
  1339. if len(traffics) > 0 {
  1340. inbound, err = s.GetInbound(traffics[0].InboundId)
  1341. return traffics[0], inbound, err
  1342. }
  1343. return nil, nil, nil
  1344. }
  1345. func (s *InboundService) GetClientByEmail(clientEmail string) (*xray.ClientTraffic, *model.Client, error) {
  1346. traffic, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1347. if err != nil {
  1348. return nil, nil, err
  1349. }
  1350. if inbound == nil {
  1351. return nil, nil, common.NewError("Inbound Not Found For Email:", clientEmail)
  1352. }
  1353. clients, err := s.GetClients(inbound)
  1354. if err != nil {
  1355. return nil, nil, err
  1356. }
  1357. for _, client := range clients {
  1358. if client.Email == clientEmail {
  1359. return traffic, &client, nil
  1360. }
  1361. }
  1362. return nil, nil, common.NewError("Client Not Found In Inbound For Email:", clientEmail)
  1363. }
  1364. func (s *InboundService) SetClientTelegramUserID(trafficId int, tgId int64) (bool, error) {
  1365. traffic, inbound, err := s.GetClientInboundByTrafficID(trafficId)
  1366. if err != nil {
  1367. return false, err
  1368. }
  1369. if inbound == nil {
  1370. return false, common.NewError("Inbound Not Found For Traffic ID:", trafficId)
  1371. }
  1372. clientEmail := traffic.Email
  1373. oldClients, err := s.GetClients(inbound)
  1374. if err != nil {
  1375. return false, err
  1376. }
  1377. clientId := ""
  1378. for _, oldClient := range oldClients {
  1379. if oldClient.Email == clientEmail {
  1380. switch inbound.Protocol {
  1381. case "trojan":
  1382. clientId = oldClient.Password
  1383. case "shadowsocks":
  1384. clientId = oldClient.Email
  1385. default:
  1386. clientId = oldClient.ID
  1387. }
  1388. break
  1389. }
  1390. }
  1391. if len(clientId) == 0 {
  1392. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1393. }
  1394. var settings map[string]any
  1395. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1396. if err != nil {
  1397. return false, err
  1398. }
  1399. clients := settings["clients"].([]any)
  1400. var newClients []any
  1401. for client_index := range clients {
  1402. c := clients[client_index].(map[string]any)
  1403. if c["email"] == clientEmail {
  1404. c["tgId"] = tgId
  1405. c["updated_at"] = time.Now().Unix() * 1000
  1406. newClients = append(newClients, any(c))
  1407. }
  1408. }
  1409. settings["clients"] = newClients
  1410. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1411. if err != nil {
  1412. return false, err
  1413. }
  1414. inbound.Settings = string(modifiedSettings)
  1415. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1416. return needRestart, err
  1417. }
  1418. func (s *InboundService) checkIsEnabledByEmail(clientEmail string) (bool, error) {
  1419. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1420. if err != nil {
  1421. return false, err
  1422. }
  1423. if inbound == nil {
  1424. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1425. }
  1426. clients, err := s.GetClients(inbound)
  1427. if err != nil {
  1428. return false, err
  1429. }
  1430. isEnable := false
  1431. for _, client := range clients {
  1432. if client.Email == clientEmail {
  1433. isEnable = client.Enable
  1434. break
  1435. }
  1436. }
  1437. return isEnable, err
  1438. }
  1439. func (s *InboundService) ToggleClientEnableByEmail(clientEmail string) (bool, bool, error) {
  1440. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1441. if err != nil {
  1442. return false, false, err
  1443. }
  1444. if inbound == nil {
  1445. return false, false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1446. }
  1447. oldClients, err := s.GetClients(inbound)
  1448. if err != nil {
  1449. return false, false, err
  1450. }
  1451. clientId := ""
  1452. clientOldEnabled := false
  1453. for _, oldClient := range oldClients {
  1454. if oldClient.Email == clientEmail {
  1455. switch inbound.Protocol {
  1456. case "trojan":
  1457. clientId = oldClient.Password
  1458. case "shadowsocks":
  1459. clientId = oldClient.Email
  1460. default:
  1461. clientId = oldClient.ID
  1462. }
  1463. clientOldEnabled = oldClient.Enable
  1464. break
  1465. }
  1466. }
  1467. if len(clientId) == 0 {
  1468. return false, false, common.NewError("Client Not Found For Email:", clientEmail)
  1469. }
  1470. var settings map[string]any
  1471. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1472. if err != nil {
  1473. return false, false, err
  1474. }
  1475. clients := settings["clients"].([]any)
  1476. var newClients []any
  1477. for client_index := range clients {
  1478. c := clients[client_index].(map[string]any)
  1479. if c["email"] == clientEmail {
  1480. c["enable"] = !clientOldEnabled
  1481. c["updated_at"] = time.Now().Unix() * 1000
  1482. newClients = append(newClients, any(c))
  1483. }
  1484. }
  1485. settings["clients"] = newClients
  1486. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1487. if err != nil {
  1488. return false, false, err
  1489. }
  1490. inbound.Settings = string(modifiedSettings)
  1491. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1492. if err != nil {
  1493. return false, needRestart, err
  1494. }
  1495. return !clientOldEnabled, needRestart, nil
  1496. }
  1497. // SetClientEnableByEmail sets client enable state to desired value; returns (changed, needRestart, error)
  1498. func (s *InboundService) SetClientEnableByEmail(clientEmail string, enable bool) (bool, bool, error) {
  1499. current, err := s.checkIsEnabledByEmail(clientEmail)
  1500. if err != nil {
  1501. return false, false, err
  1502. }
  1503. if current == enable {
  1504. return false, false, nil
  1505. }
  1506. newEnabled, needRestart, err := s.ToggleClientEnableByEmail(clientEmail)
  1507. if err != nil {
  1508. return false, needRestart, err
  1509. }
  1510. return newEnabled == enable, needRestart, nil
  1511. }
  1512. func (s *InboundService) ResetClientIpLimitByEmail(clientEmail string, count int) (bool, error) {
  1513. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1514. if err != nil {
  1515. return false, err
  1516. }
  1517. if inbound == nil {
  1518. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1519. }
  1520. oldClients, err := s.GetClients(inbound)
  1521. if err != nil {
  1522. return false, err
  1523. }
  1524. clientId := ""
  1525. for _, oldClient := range oldClients {
  1526. if oldClient.Email == clientEmail {
  1527. switch inbound.Protocol {
  1528. case "trojan":
  1529. clientId = oldClient.Password
  1530. case "shadowsocks":
  1531. clientId = oldClient.Email
  1532. default:
  1533. clientId = oldClient.ID
  1534. }
  1535. break
  1536. }
  1537. }
  1538. if len(clientId) == 0 {
  1539. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1540. }
  1541. var settings map[string]any
  1542. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1543. if err != nil {
  1544. return false, err
  1545. }
  1546. clients := settings["clients"].([]any)
  1547. var newClients []any
  1548. for client_index := range clients {
  1549. c := clients[client_index].(map[string]any)
  1550. if c["email"] == clientEmail {
  1551. c["limitIp"] = count
  1552. c["updated_at"] = time.Now().Unix() * 1000
  1553. newClients = append(newClients, any(c))
  1554. }
  1555. }
  1556. settings["clients"] = newClients
  1557. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1558. if err != nil {
  1559. return false, err
  1560. }
  1561. inbound.Settings = string(modifiedSettings)
  1562. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1563. return needRestart, err
  1564. }
  1565. func (s *InboundService) ResetClientExpiryTimeByEmail(clientEmail string, expiry_time int64) (bool, error) {
  1566. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1567. if err != nil {
  1568. return false, err
  1569. }
  1570. if inbound == nil {
  1571. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1572. }
  1573. oldClients, err := s.GetClients(inbound)
  1574. if err != nil {
  1575. return false, err
  1576. }
  1577. clientId := ""
  1578. for _, oldClient := range oldClients {
  1579. if oldClient.Email == clientEmail {
  1580. switch inbound.Protocol {
  1581. case "trojan":
  1582. clientId = oldClient.Password
  1583. case "shadowsocks":
  1584. clientId = oldClient.Email
  1585. default:
  1586. clientId = oldClient.ID
  1587. }
  1588. break
  1589. }
  1590. }
  1591. if len(clientId) == 0 {
  1592. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1593. }
  1594. var settings map[string]any
  1595. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1596. if err != nil {
  1597. return false, err
  1598. }
  1599. clients := settings["clients"].([]any)
  1600. var newClients []any
  1601. for client_index := range clients {
  1602. c := clients[client_index].(map[string]any)
  1603. if c["email"] == clientEmail {
  1604. c["expiryTime"] = expiry_time
  1605. c["updated_at"] = time.Now().Unix() * 1000
  1606. newClients = append(newClients, any(c))
  1607. }
  1608. }
  1609. settings["clients"] = newClients
  1610. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1611. if err != nil {
  1612. return false, err
  1613. }
  1614. inbound.Settings = string(modifiedSettings)
  1615. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1616. return needRestart, err
  1617. }
  1618. func (s *InboundService) ResetClientTrafficLimitByEmail(clientEmail string, totalGB int) (bool, error) {
  1619. if totalGB < 0 {
  1620. return false, common.NewError("totalGB must be >= 0")
  1621. }
  1622. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1623. if err != nil {
  1624. return false, err
  1625. }
  1626. if inbound == nil {
  1627. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1628. }
  1629. oldClients, err := s.GetClients(inbound)
  1630. if err != nil {
  1631. return false, err
  1632. }
  1633. clientId := ""
  1634. for _, oldClient := range oldClients {
  1635. if oldClient.Email == clientEmail {
  1636. switch inbound.Protocol {
  1637. case "trojan":
  1638. clientId = oldClient.Password
  1639. case "shadowsocks":
  1640. clientId = oldClient.Email
  1641. default:
  1642. clientId = oldClient.ID
  1643. }
  1644. break
  1645. }
  1646. }
  1647. if len(clientId) == 0 {
  1648. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1649. }
  1650. var settings map[string]any
  1651. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1652. if err != nil {
  1653. return false, err
  1654. }
  1655. clients := settings["clients"].([]any)
  1656. var newClients []any
  1657. for client_index := range clients {
  1658. c := clients[client_index].(map[string]any)
  1659. if c["email"] == clientEmail {
  1660. c["totalGB"] = totalGB * 1024 * 1024 * 1024
  1661. c["updated_at"] = time.Now().Unix() * 1000
  1662. newClients = append(newClients, any(c))
  1663. }
  1664. }
  1665. settings["clients"] = newClients
  1666. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1667. if err != nil {
  1668. return false, err
  1669. }
  1670. inbound.Settings = string(modifiedSettings)
  1671. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1672. return needRestart, err
  1673. }
  1674. func (s *InboundService) ResetClientTrafficByEmail(clientEmail string) error {
  1675. db := database.GetDB()
  1676. // Reset traffic stats in ClientTraffic table
  1677. result := db.Model(xray.ClientTraffic{}).
  1678. Where("email = ?", clientEmail).
  1679. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  1680. err := result.Error
  1681. if err != nil {
  1682. return err
  1683. }
  1684. return nil
  1685. }
  1686. func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (bool, error) {
  1687. needRestart := false
  1688. traffic, err := s.GetClientTrafficByEmail(clientEmail)
  1689. if err != nil {
  1690. return false, err
  1691. }
  1692. if !traffic.Enable {
  1693. inbound, err := s.GetInbound(id)
  1694. if err != nil {
  1695. return false, err
  1696. }
  1697. clients, err := s.GetClients(inbound)
  1698. if err != nil {
  1699. return false, err
  1700. }
  1701. for _, client := range clients {
  1702. if client.Email == clientEmail && client.Enable {
  1703. s.xrayApi.Init(p.GetAPIPort())
  1704. cipher := ""
  1705. if string(inbound.Protocol) == "shadowsocks" {
  1706. var oldSettings map[string]any
  1707. err = json.Unmarshal([]byte(inbound.Settings), &oldSettings)
  1708. if err != nil {
  1709. return false, err
  1710. }
  1711. cipher = oldSettings["method"].(string)
  1712. }
  1713. err1 := s.xrayApi.AddUser(string(inbound.Protocol), inbound.Tag, map[string]any{
  1714. "email": client.Email,
  1715. "id": client.ID,
  1716. "auth": client.Auth,
  1717. "security": client.Security,
  1718. "flow": client.Flow,
  1719. "password": client.Password,
  1720. "cipher": cipher,
  1721. })
  1722. if err1 == nil {
  1723. logger.Debug("Client enabled due to reset traffic:", clientEmail)
  1724. } else {
  1725. logger.Debug("Error in enabling client by api:", err1)
  1726. needRestart = true
  1727. }
  1728. s.xrayApi.Close()
  1729. break
  1730. }
  1731. }
  1732. }
  1733. traffic.Up = 0
  1734. traffic.Down = 0
  1735. traffic.Enable = true
  1736. db := database.GetDB()
  1737. err = db.Save(traffic).Error
  1738. if err != nil {
  1739. return false, err
  1740. }
  1741. return needRestart, nil
  1742. }
  1743. func (s *InboundService) ResetAllClientTraffics(id int) error {
  1744. db := database.GetDB()
  1745. now := time.Now().Unix() * 1000
  1746. return db.Transaction(func(tx *gorm.DB) error {
  1747. whereText := "inbound_id "
  1748. if id == -1 {
  1749. whereText += " > ?"
  1750. } else {
  1751. whereText += " = ?"
  1752. }
  1753. // Reset client traffics
  1754. result := tx.Model(xray.ClientTraffic{}).
  1755. Where(whereText, id).
  1756. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  1757. if result.Error != nil {
  1758. return result.Error
  1759. }
  1760. // Update lastTrafficResetTime for the inbound(s)
  1761. inboundWhereText := "id "
  1762. if id == -1 {
  1763. inboundWhereText += " > ?"
  1764. } else {
  1765. inboundWhereText += " = ?"
  1766. }
  1767. result = tx.Model(model.Inbound{}).
  1768. Where(inboundWhereText, id).
  1769. Update("last_traffic_reset_time", now)
  1770. return result.Error
  1771. })
  1772. }
  1773. func (s *InboundService) ResetAllTraffics() error {
  1774. db := database.GetDB()
  1775. result := db.Model(model.Inbound{}).
  1776. Where("user_id > ?", 0).
  1777. Updates(map[string]any{"up": 0, "down": 0})
  1778. err := result.Error
  1779. return err
  1780. }
  1781. func (s *InboundService) ResetInboundTraffic(id int) error {
  1782. db := database.GetDB()
  1783. result := db.Model(model.Inbound{}).
  1784. Where("id = ?", id).
  1785. Updates(map[string]any{"up": 0, "down": 0})
  1786. return result.Error
  1787. }
  1788. func (s *InboundService) DelDepletedClients(id int) (err error) {
  1789. db := database.GetDB()
  1790. tx := db.Begin()
  1791. defer func() {
  1792. if err == nil {
  1793. tx.Commit()
  1794. } else {
  1795. tx.Rollback()
  1796. }
  1797. }()
  1798. whereText := "reset = 0 and inbound_id "
  1799. if id < 0 {
  1800. whereText += "> ?"
  1801. } else {
  1802. whereText += "= ?"
  1803. }
  1804. // Only consider truly depleted clients: expired OR traffic exhausted
  1805. now := time.Now().Unix() * 1000
  1806. depletedClients := []xray.ClientTraffic{}
  1807. err = db.Model(xray.ClientTraffic{}).
  1808. Where(whereText+" and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))", id, now).
  1809. Select("inbound_id, GROUP_CONCAT(email) as email").
  1810. Group("inbound_id").
  1811. Find(&depletedClients).Error
  1812. if err != nil {
  1813. return err
  1814. }
  1815. for _, depletedClient := range depletedClients {
  1816. emails := strings.Split(depletedClient.Email, ",")
  1817. oldInbound, err := s.GetInbound(depletedClient.InboundId)
  1818. if err != nil {
  1819. return err
  1820. }
  1821. var oldSettings map[string]any
  1822. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1823. if err != nil {
  1824. return err
  1825. }
  1826. oldClients := oldSettings["clients"].([]any)
  1827. var newClients []any
  1828. for _, client := range oldClients {
  1829. deplete := false
  1830. c := client.(map[string]any)
  1831. for _, email := range emails {
  1832. if email == c["email"].(string) {
  1833. deplete = true
  1834. break
  1835. }
  1836. }
  1837. if !deplete {
  1838. newClients = append(newClients, client)
  1839. }
  1840. }
  1841. if len(newClients) > 0 {
  1842. oldSettings["clients"] = newClients
  1843. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  1844. if err != nil {
  1845. return err
  1846. }
  1847. oldInbound.Settings = string(newSettings)
  1848. err = tx.Save(oldInbound).Error
  1849. if err != nil {
  1850. return err
  1851. }
  1852. } else {
  1853. // Delete inbound if no client remains
  1854. s.DelInbound(depletedClient.InboundId)
  1855. }
  1856. }
  1857. // Delete stats only for truly depleted clients
  1858. err = tx.Where(whereText+" and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))", id, now).Delete(xray.ClientTraffic{}).Error
  1859. if err != nil {
  1860. return err
  1861. }
  1862. return nil
  1863. }
  1864. func (s *InboundService) GetClientTrafficTgBot(tgId int64) ([]*xray.ClientTraffic, error) {
  1865. db := database.GetDB()
  1866. var inbounds []*model.Inbound
  1867. // Retrieve inbounds where settings contain the given tgId
  1868. err := db.Model(model.Inbound{}).Where("settings LIKE ?", fmt.Sprintf(`%%"tgId": %d%%`, tgId)).Find(&inbounds).Error
  1869. if err != nil && err != gorm.ErrRecordNotFound {
  1870. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  1871. return nil, err
  1872. }
  1873. var emails []string
  1874. for _, inbound := range inbounds {
  1875. clients, err := s.GetClients(inbound)
  1876. if err != nil {
  1877. logger.Errorf("Error retrieving clients for inbound %d: %v", inbound.Id, err)
  1878. continue
  1879. }
  1880. for _, client := range clients {
  1881. if client.TgID == tgId {
  1882. emails = append(emails, client.Email)
  1883. }
  1884. }
  1885. }
  1886. var traffics []*xray.ClientTraffic
  1887. err = db.Model(xray.ClientTraffic{}).Where("email IN ?", emails).Find(&traffics).Error
  1888. if err != nil {
  1889. if err == gorm.ErrRecordNotFound {
  1890. logger.Warning("No ClientTraffic records found for emails:", emails)
  1891. return nil, nil
  1892. }
  1893. logger.Errorf("Error retrieving ClientTraffic for emails %v: %v", emails, err)
  1894. return nil, err
  1895. }
  1896. // Populate UUID and other client data for each traffic record
  1897. for i := range traffics {
  1898. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  1899. traffics[i].Enable = client.Enable
  1900. traffics[i].UUID = client.ID
  1901. traffics[i].SubId = client.SubID
  1902. }
  1903. }
  1904. return traffics, nil
  1905. }
  1906. func (s *InboundService) GetClientTrafficByEmail(email string) (traffic *xray.ClientTraffic, err error) {
  1907. // Prefer retrieving along with client to reflect actual enabled state from inbound settings
  1908. t, client, err := s.GetClientByEmail(email)
  1909. if err != nil {
  1910. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  1911. return nil, err
  1912. }
  1913. if t != nil && client != nil {
  1914. t.UUID = client.ID
  1915. t.SubId = client.SubID
  1916. return t, nil
  1917. }
  1918. return nil, nil
  1919. }
  1920. func (s *InboundService) UpdateClientTrafficByEmail(email string, upload int64, download int64) error {
  1921. db := database.GetDB()
  1922. result := db.Model(xray.ClientTraffic{}).
  1923. Where("email = ?", email).
  1924. Updates(map[string]any{"up": upload, "down": download})
  1925. err := result.Error
  1926. if err != nil {
  1927. logger.Warningf("Error updating ClientTraffic with email %s: %v", email, err)
  1928. return err
  1929. }
  1930. return nil
  1931. }
  1932. func (s *InboundService) GetClientTrafficByID(id string) ([]xray.ClientTraffic, error) {
  1933. db := database.GetDB()
  1934. var traffics []xray.ClientTraffic
  1935. err := db.Model(xray.ClientTraffic{}).Where(`email IN(
  1936. SELECT JSON_EXTRACT(client.value, '$.email') as email
  1937. FROM inbounds,
  1938. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  1939. WHERE
  1940. JSON_EXTRACT(client.value, '$.id') in (?)
  1941. )`, id).Find(&traffics).Error
  1942. if err != nil {
  1943. logger.Debug(err)
  1944. return nil, err
  1945. }
  1946. // Reconcile enable flag with client settings per email to avoid stale DB value
  1947. for i := range traffics {
  1948. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  1949. traffics[i].Enable = client.Enable
  1950. traffics[i].UUID = client.ID
  1951. traffics[i].SubId = client.SubID
  1952. }
  1953. }
  1954. return traffics, err
  1955. }
  1956. func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.ClientTraffic, err error) {
  1957. db := database.GetDB()
  1958. inbound := &model.Inbound{}
  1959. traffic = &xray.ClientTraffic{}
  1960. // Search for inbound settings that contain the query
  1961. err = db.Model(model.Inbound{}).Where("settings LIKE ?", "%\""+query+"\"%").First(inbound).Error
  1962. if err != nil {
  1963. if err == gorm.ErrRecordNotFound {
  1964. logger.Warningf("Inbound settings containing query %s not found: %v", query, err)
  1965. return nil, err
  1966. }
  1967. logger.Errorf("Error searching for inbound settings with query %s: %v", query, err)
  1968. return nil, err
  1969. }
  1970. traffic.InboundId = inbound.Id
  1971. // Unmarshal settings to get clients
  1972. settings := map[string][]model.Client{}
  1973. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1974. logger.Errorf("Error unmarshalling inbound settings for inbound ID %d: %v", inbound.Id, err)
  1975. return nil, err
  1976. }
  1977. clients := settings["clients"]
  1978. for _, client := range clients {
  1979. if (client.ID == query || client.Password == query) && client.Email != "" {
  1980. traffic.Email = client.Email
  1981. break
  1982. }
  1983. }
  1984. if traffic.Email == "" {
  1985. logger.Warningf("No client found with query %s in inbound ID %d", query, inbound.Id)
  1986. return nil, gorm.ErrRecordNotFound
  1987. }
  1988. // Retrieve ClientTraffic based on the found email
  1989. err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error
  1990. if err != nil {
  1991. if err == gorm.ErrRecordNotFound {
  1992. logger.Warningf("ClientTraffic for email %s not found: %v", traffic.Email, err)
  1993. return nil, err
  1994. }
  1995. logger.Errorf("Error retrieving ClientTraffic for email %s: %v", traffic.Email, err)
  1996. return nil, err
  1997. }
  1998. return traffic, nil
  1999. }
  2000. func (s *InboundService) GetInboundClientIps(clientEmail string) (string, error) {
  2001. db := database.GetDB()
  2002. InboundClientIps := &model.InboundClientIps{}
  2003. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  2004. if err != nil {
  2005. return "", err
  2006. }
  2007. if InboundClientIps.Ips == "" {
  2008. return "", nil
  2009. }
  2010. // Try to parse as new format (with timestamps)
  2011. type IPWithTimestamp struct {
  2012. IP string `json:"ip"`
  2013. Timestamp int64 `json:"timestamp"`
  2014. }
  2015. var ipsWithTime []IPWithTimestamp
  2016. err = json.Unmarshal([]byte(InboundClientIps.Ips), &ipsWithTime)
  2017. // If successfully parsed as new format, return with timestamps
  2018. if err == nil && len(ipsWithTime) > 0 {
  2019. return InboundClientIps.Ips, nil
  2020. }
  2021. // Otherwise, assume it's old format (simple string array)
  2022. // Try to parse as simple array and convert to new format
  2023. var oldIps []string
  2024. err = json.Unmarshal([]byte(InboundClientIps.Ips), &oldIps)
  2025. if err == nil && len(oldIps) > 0 {
  2026. // Convert old format to new format with current timestamp
  2027. newIpsWithTime := make([]IPWithTimestamp, len(oldIps))
  2028. for i, ip := range oldIps {
  2029. newIpsWithTime[i] = IPWithTimestamp{
  2030. IP: ip,
  2031. Timestamp: time.Now().Unix(),
  2032. }
  2033. }
  2034. result, _ := json.Marshal(newIpsWithTime)
  2035. return string(result), nil
  2036. }
  2037. // Return as-is if parsing fails
  2038. return InboundClientIps.Ips, nil
  2039. }
  2040. func (s *InboundService) ClearClientIps(clientEmail string) error {
  2041. db := database.GetDB()
  2042. result := db.Model(model.InboundClientIps{}).
  2043. Where("client_email = ?", clientEmail).
  2044. Update("ips", "")
  2045. err := result.Error
  2046. if err != nil {
  2047. return err
  2048. }
  2049. return nil
  2050. }
  2051. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  2052. db := database.GetDB()
  2053. var inbounds []*model.Inbound
  2054. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  2055. if err != nil && err != gorm.ErrRecordNotFound {
  2056. return nil, err
  2057. }
  2058. return inbounds, nil
  2059. }
  2060. func (s *InboundService) MigrationRequirements() {
  2061. db := database.GetDB()
  2062. tx := db.Begin()
  2063. var err error
  2064. defer func() {
  2065. if err == nil {
  2066. tx.Commit()
  2067. if dbErr := db.Exec(`VACUUM "main"`).Error; dbErr != nil {
  2068. logger.Warningf("VACUUM failed: %v", dbErr)
  2069. }
  2070. } else {
  2071. tx.Rollback()
  2072. }
  2073. }()
  2074. // Calculate and backfill all_time from up+down for inbounds and clients
  2075. err = tx.Exec(`
  2076. UPDATE inbounds
  2077. SET all_time = IFNULL(up, 0) + IFNULL(down, 0)
  2078. WHERE IFNULL(all_time, 0) = 0 AND (IFNULL(up, 0) + IFNULL(down, 0)) > 0
  2079. `).Error
  2080. if err != nil {
  2081. return
  2082. }
  2083. err = tx.Exec(`
  2084. UPDATE client_traffics
  2085. SET all_time = IFNULL(up, 0) + IFNULL(down, 0)
  2086. WHERE IFNULL(all_time, 0) = 0 AND (IFNULL(up, 0) + IFNULL(down, 0)) > 0
  2087. `).Error
  2088. if err != nil {
  2089. return
  2090. }
  2091. // Fix inbounds based problems
  2092. var inbounds []*model.Inbound
  2093. err = tx.Model(model.Inbound{}).Where("protocol IN (?)", []string{"vmess", "vless", "trojan"}).Find(&inbounds).Error
  2094. if err != nil && err != gorm.ErrRecordNotFound {
  2095. return
  2096. }
  2097. for inbound_index := range inbounds {
  2098. settings := map[string]any{}
  2099. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  2100. clients, ok := settings["clients"].([]any)
  2101. if ok {
  2102. // Fix Client configuration problems
  2103. var newClients []any
  2104. for client_index := range clients {
  2105. c := clients[client_index].(map[string]any)
  2106. // Add email='' if it is not exists
  2107. if _, ok := c["email"]; !ok {
  2108. c["email"] = ""
  2109. }
  2110. // Convert string tgId to int64
  2111. if _, ok := c["tgId"]; ok {
  2112. var tgId any = c["tgId"]
  2113. if tgIdStr, ok2 := tgId.(string); ok2 {
  2114. tgIdInt64, err := strconv.ParseInt(strings.ReplaceAll(tgIdStr, " ", ""), 10, 64)
  2115. if err == nil {
  2116. c["tgId"] = tgIdInt64
  2117. }
  2118. }
  2119. }
  2120. // Remove "flow": "xtls-rprx-direct"
  2121. if _, ok := c["flow"]; ok {
  2122. if c["flow"] == "xtls-rprx-direct" {
  2123. c["flow"] = ""
  2124. }
  2125. }
  2126. // Backfill created_at and updated_at
  2127. if _, ok := c["created_at"]; !ok {
  2128. c["created_at"] = time.Now().Unix() * 1000
  2129. }
  2130. c["updated_at"] = time.Now().Unix() * 1000
  2131. newClients = append(newClients, any(c))
  2132. }
  2133. settings["clients"] = newClients
  2134. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2135. if err != nil {
  2136. return
  2137. }
  2138. inbounds[inbound_index].Settings = string(modifiedSettings)
  2139. }
  2140. // Add client traffic row for all clients which has email
  2141. modelClients, err := s.GetClients(inbounds[inbound_index])
  2142. if err != nil {
  2143. return
  2144. }
  2145. for _, modelClient := range modelClients {
  2146. if len(modelClient.Email) > 0 {
  2147. var count int64
  2148. tx.Model(xray.ClientTraffic{}).Where("email = ?", modelClient.Email).Count(&count)
  2149. if count == 0 {
  2150. s.AddClientStat(tx, inbounds[inbound_index].Id, &modelClient)
  2151. }
  2152. }
  2153. }
  2154. }
  2155. tx.Save(inbounds)
  2156. // Remove orphaned traffics
  2157. tx.Where("inbound_id = 0").Delete(xray.ClientTraffic{})
  2158. // Migrate old MultiDomain to External Proxy
  2159. var externalProxy []struct {
  2160. Id int
  2161. Port int
  2162. StreamSettings []byte
  2163. }
  2164. err = tx.Raw(`select id, port, stream_settings
  2165. from inbounds
  2166. WHERE protocol in ('vmess','vless','trojan')
  2167. AND json_extract(stream_settings, '$.security') = 'tls'
  2168. AND json_extract(stream_settings, '$.tlsSettings.settings.domains') IS NOT NULL`).Scan(&externalProxy).Error
  2169. if err != nil || len(externalProxy) == 0 {
  2170. return
  2171. }
  2172. for _, ep := range externalProxy {
  2173. var reverses any
  2174. var stream map[string]any
  2175. json.Unmarshal(ep.StreamSettings, &stream)
  2176. if tlsSettings, ok := stream["tlsSettings"].(map[string]any); ok {
  2177. if settings, ok := tlsSettings["settings"].(map[string]any); ok {
  2178. if domains, ok := settings["domains"].([]any); ok {
  2179. for _, domain := range domains {
  2180. if domainMap, ok := domain.(map[string]any); ok {
  2181. domainMap["forceTls"] = "same"
  2182. domainMap["port"] = ep.Port
  2183. domainMap["dest"] = domainMap["domain"].(string)
  2184. delete(domainMap, "domain")
  2185. }
  2186. }
  2187. }
  2188. reverses = settings["domains"]
  2189. delete(settings, "domains")
  2190. }
  2191. }
  2192. stream["externalProxy"] = reverses
  2193. newStream, _ := json.MarshalIndent(stream, " ", " ")
  2194. tx.Model(model.Inbound{}).Where("id = ?", ep.Id).Update("stream_settings", newStream)
  2195. }
  2196. err = tx.Raw(`UPDATE inbounds
  2197. SET tag = REPLACE(tag, '0.0.0.0:', '')
  2198. WHERE INSTR(tag, '0.0.0.0:') > 0;`).Error
  2199. if err != nil {
  2200. return
  2201. }
  2202. }
  2203. func (s *InboundService) MigrateDB() {
  2204. s.MigrationRequirements()
  2205. s.MigrationRemoveOrphanedTraffics()
  2206. }
  2207. func (s *InboundService) GetOnlineClients() []string {
  2208. return p.GetOnlineClients()
  2209. }
  2210. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  2211. db := database.GetDB()
  2212. var rows []xray.ClientTraffic
  2213. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  2214. if err != nil && err != gorm.ErrRecordNotFound {
  2215. return nil, err
  2216. }
  2217. result := make(map[string]int64, len(rows))
  2218. for _, r := range rows {
  2219. result[r.Email] = r.LastOnline
  2220. }
  2221. return result, nil
  2222. }
  2223. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  2224. db := database.GetDB()
  2225. // Step 1: Get ClientTraffic records for emails in the input list
  2226. var clients []xray.ClientTraffic
  2227. err := db.Where("email IN ?", emails).Find(&clients).Error
  2228. if err != nil && err != gorm.ErrRecordNotFound {
  2229. return nil, nil, err
  2230. }
  2231. // Step 2: Sort clients by (Up + Down) descending
  2232. sort.Slice(clients, func(i, j int) bool {
  2233. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  2234. })
  2235. // Step 3: Extract sorted valid emails and track found ones
  2236. validEmails := make([]string, 0, len(clients))
  2237. found := make(map[string]bool)
  2238. for _, client := range clients {
  2239. validEmails = append(validEmails, client.Email)
  2240. found[client.Email] = true
  2241. }
  2242. // Step 4: Identify emails that were not found in the database
  2243. extraEmails := make([]string, 0)
  2244. for _, email := range emails {
  2245. if !found[email] {
  2246. extraEmails = append(extraEmails, email)
  2247. }
  2248. }
  2249. return validEmails, extraEmails, nil
  2250. }
  2251. func (s *InboundService) DelInboundClientByEmail(inboundId int, email string) (bool, error) {
  2252. oldInbound, err := s.GetInbound(inboundId)
  2253. if err != nil {
  2254. logger.Error("Load Old Data Error")
  2255. return false, err
  2256. }
  2257. var settings map[string]any
  2258. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  2259. return false, err
  2260. }
  2261. interfaceClients, ok := settings["clients"].([]any)
  2262. if !ok {
  2263. return false, common.NewError("invalid clients format in inbound settings")
  2264. }
  2265. var newClients []any
  2266. needApiDel := false
  2267. found := false
  2268. for _, client := range interfaceClients {
  2269. c, ok := client.(map[string]any)
  2270. if !ok {
  2271. continue
  2272. }
  2273. if cEmail, ok := c["email"].(string); ok && cEmail == email {
  2274. // matched client, drop it
  2275. found = true
  2276. needApiDel, _ = c["enable"].(bool)
  2277. } else {
  2278. newClients = append(newClients, client)
  2279. }
  2280. }
  2281. if !found {
  2282. return false, common.NewError(fmt.Sprintf("client with email %s not found", email))
  2283. }
  2284. if len(newClients) == 0 {
  2285. return false, common.NewError("no client remained in Inbound")
  2286. }
  2287. settings["clients"] = newClients
  2288. newSettings, err := json.MarshalIndent(settings, "", " ")
  2289. if err != nil {
  2290. return false, err
  2291. }
  2292. oldInbound.Settings = string(newSettings)
  2293. db := database.GetDB()
  2294. // remove IP bindings
  2295. if err := s.DelClientIPs(db, email); err != nil {
  2296. logger.Error("Error in delete client IPs")
  2297. return false, err
  2298. }
  2299. needRestart := false
  2300. // remove stats too
  2301. if len(email) > 0 {
  2302. traffic, err := s.GetClientTrafficByEmail(email)
  2303. if err != nil {
  2304. return false, err
  2305. }
  2306. if traffic != nil {
  2307. if err := s.DelClientStat(db, email); err != nil {
  2308. logger.Error("Delete stats Data Error")
  2309. return false, err
  2310. }
  2311. }
  2312. if needApiDel {
  2313. s.xrayApi.Init(p.GetAPIPort())
  2314. if err1 := s.xrayApi.RemoveUser(oldInbound.Tag, email); err1 == nil {
  2315. logger.Debug("Client deleted by api:", email)
  2316. needRestart = false
  2317. } else {
  2318. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  2319. logger.Debug("User is already deleted. Nothing to do more...")
  2320. } else {
  2321. logger.Debug("Error in deleting client by api:", err1)
  2322. needRestart = true
  2323. }
  2324. }
  2325. s.xrayApi.Close()
  2326. }
  2327. }
  2328. return needRestart, db.Save(oldInbound).Error
  2329. }