inbound.go 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062
  1. package service
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "sort"
  6. "strconv"
  7. "strings"
  8. "time"
  9. "x-ui/database"
  10. "x-ui/database/model"
  11. "x-ui/logger"
  12. "x-ui/util/common"
  13. "x-ui/xray"
  14. "gorm.io/gorm"
  15. )
  16. type InboundService struct {
  17. xrayApi xray.XrayAPI
  18. }
  19. func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) {
  20. db := database.GetDB()
  21. var inbounds []*model.Inbound
  22. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Find(&inbounds).Error
  23. if err != nil && err != gorm.ErrRecordNotFound {
  24. return nil, err
  25. }
  26. return inbounds, nil
  27. }
  28. func (s *InboundService) GetAllInbounds() ([]*model.Inbound, error) {
  29. db := database.GetDB()
  30. var inbounds []*model.Inbound
  31. err := db.Model(model.Inbound{}).Preload("ClientStats").Find(&inbounds).Error
  32. if err != nil && err != gorm.ErrRecordNotFound {
  33. return nil, err
  34. }
  35. return inbounds, nil
  36. }
  37. func (s *InboundService) checkPortExist(listen string, port int, ignoreId int) (bool, error) {
  38. db := database.GetDB()
  39. if listen == "" || listen == "0.0.0.0" || listen == "::" || listen == "::0" {
  40. db = db.Model(model.Inbound{}).Where("port = ?", port)
  41. } else {
  42. db = db.Model(model.Inbound{}).
  43. Where("port = ?", port).
  44. Where(
  45. db.Model(model.Inbound{}).Where(
  46. "listen = ?", listen,
  47. ).Or(
  48. "listen = \"\"",
  49. ).Or(
  50. "listen = \"0.0.0.0\"",
  51. ).Or(
  52. "listen = \"::\"",
  53. ).Or(
  54. "listen = \"::0\""))
  55. }
  56. if ignoreId > 0 {
  57. db = db.Where("id != ?", ignoreId)
  58. }
  59. var count int64
  60. err := db.Count(&count).Error
  61. if err != nil {
  62. return false, err
  63. }
  64. return count > 0, nil
  65. }
  66. func (s *InboundService) GetClients(inbound *model.Inbound) ([]model.Client, error) {
  67. settings := map[string][]model.Client{}
  68. json.Unmarshal([]byte(inbound.Settings), &settings)
  69. if settings == nil {
  70. return nil, fmt.Errorf("setting is null")
  71. }
  72. clients := settings["clients"]
  73. if clients == nil {
  74. return nil, nil
  75. }
  76. return clients, nil
  77. }
  78. func (s *InboundService) getAllEmails() ([]string, error) {
  79. db := database.GetDB()
  80. var emails []string
  81. err := db.Raw(`
  82. SELECT JSON_EXTRACT(client.value, '$.email')
  83. FROM inbounds,
  84. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  85. `).Scan(&emails).Error
  86. if err != nil {
  87. return nil, err
  88. }
  89. return emails, nil
  90. }
  91. func (s *InboundService) contains(slice []string, str string) bool {
  92. lowerStr := strings.ToLower(str)
  93. for _, s := range slice {
  94. if strings.ToLower(s) == lowerStr {
  95. return true
  96. }
  97. }
  98. return false
  99. }
  100. func (s *InboundService) checkEmailsExistForClients(clients []model.Client) (string, error) {
  101. allEmails, err := s.getAllEmails()
  102. if err != nil {
  103. return "", err
  104. }
  105. var emails []string
  106. for _, client := range clients {
  107. if client.Email != "" {
  108. if s.contains(emails, client.Email) {
  109. return client.Email, nil
  110. }
  111. if s.contains(allEmails, client.Email) {
  112. return client.Email, nil
  113. }
  114. emails = append(emails, client.Email)
  115. }
  116. }
  117. return "", nil
  118. }
  119. func (s *InboundService) checkEmailExistForInbound(inbound *model.Inbound) (string, error) {
  120. clients, err := s.GetClients(inbound)
  121. if err != nil {
  122. return "", err
  123. }
  124. allEmails, err := s.getAllEmails()
  125. if err != nil {
  126. return "", err
  127. }
  128. var emails []string
  129. for _, client := range clients {
  130. if client.Email != "" {
  131. if s.contains(emails, client.Email) {
  132. return client.Email, nil
  133. }
  134. if s.contains(allEmails, client.Email) {
  135. return client.Email, nil
  136. }
  137. emails = append(emails, client.Email)
  138. }
  139. }
  140. return "", nil
  141. }
  142. func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  143. exist, err := s.checkPortExist(inbound.Listen, inbound.Port, 0)
  144. if err != nil {
  145. return inbound, false, err
  146. }
  147. if exist {
  148. return inbound, false, common.NewError("Port already exists:", inbound.Port)
  149. }
  150. existEmail, err := s.checkEmailExistForInbound(inbound)
  151. if err != nil {
  152. return inbound, false, err
  153. }
  154. if existEmail != "" {
  155. return inbound, false, common.NewError("Duplicate email:", existEmail)
  156. }
  157. clients, err := s.GetClients(inbound)
  158. if err != nil {
  159. return inbound, false, err
  160. }
  161. // Secure client ID
  162. for _, client := range clients {
  163. if inbound.Protocol == "trojan" {
  164. if client.Password == "" {
  165. return inbound, false, common.NewError("empty client ID")
  166. }
  167. } else if inbound.Protocol == "shadowsocks" {
  168. if client.Email == "" {
  169. return inbound, false, common.NewError("empty client ID")
  170. }
  171. } else {
  172. if client.ID == "" {
  173. return inbound, false, common.NewError("empty client ID")
  174. }
  175. }
  176. }
  177. db := database.GetDB()
  178. tx := db.Begin()
  179. defer func() {
  180. if err == nil {
  181. tx.Commit()
  182. } else {
  183. tx.Rollback()
  184. }
  185. }()
  186. err = tx.Save(inbound).Error
  187. if err == nil {
  188. if len(inbound.ClientStats) == 0 {
  189. for _, client := range clients {
  190. s.AddClientStat(tx, inbound.Id, &client)
  191. }
  192. }
  193. } else {
  194. return inbound, false, err
  195. }
  196. needRestart := false
  197. if inbound.Enable {
  198. s.xrayApi.Init(p.GetAPIPort())
  199. inboundJson, err1 := json.MarshalIndent(inbound.GenXrayInboundConfig(), "", " ")
  200. if err1 != nil {
  201. logger.Debug("Unable to marshal inbound config:", err1)
  202. }
  203. err1 = s.xrayApi.AddInbound(inboundJson)
  204. if err1 == nil {
  205. logger.Debug("New inbound added by api:", inbound.Tag)
  206. } else {
  207. logger.Debug("Unable to add inbound by api:", err1)
  208. needRestart = true
  209. }
  210. s.xrayApi.Close()
  211. }
  212. return inbound, needRestart, err
  213. }
  214. func (s *InboundService) DelInbound(id int) (bool, error) {
  215. db := database.GetDB()
  216. var tag string
  217. needRestart := false
  218. result := db.Model(model.Inbound{}).Select("tag").Where("id = ? and enable = ?", id, true).First(&tag)
  219. if result.Error == nil {
  220. s.xrayApi.Init(p.GetAPIPort())
  221. err1 := s.xrayApi.DelInbound(tag)
  222. if err1 == nil {
  223. logger.Debug("Inbound deleted by api:", tag)
  224. } else {
  225. logger.Debug("Unable to delete inbound by api:", err1)
  226. needRestart = true
  227. }
  228. s.xrayApi.Close()
  229. } else {
  230. logger.Debug("No enabled inbound founded to removing by api", tag)
  231. }
  232. // Delete client traffics of inbounds
  233. err := db.Where("inbound_id = ?", id).Delete(xray.ClientTraffic{}).Error
  234. if err != nil {
  235. return false, err
  236. }
  237. inbound, err := s.GetInbound(id)
  238. if err != nil {
  239. return false, err
  240. }
  241. clients, err := s.GetClients(inbound)
  242. if err != nil {
  243. return false, err
  244. }
  245. for _, client := range clients {
  246. err := s.DelClientIPs(db, client.Email)
  247. if err != nil {
  248. return false, err
  249. }
  250. }
  251. return needRestart, db.Delete(model.Inbound{}, id).Error
  252. }
  253. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  254. db := database.GetDB()
  255. inbound := &model.Inbound{}
  256. err := db.Model(model.Inbound{}).First(inbound, id).Error
  257. if err != nil {
  258. return nil, err
  259. }
  260. return inbound, nil
  261. }
  262. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  263. exist, err := s.checkPortExist(inbound.Listen, inbound.Port, inbound.Id)
  264. if err != nil {
  265. return inbound, false, err
  266. }
  267. if exist {
  268. return inbound, false, common.NewError("Port already exists:", inbound.Port)
  269. }
  270. oldInbound, err := s.GetInbound(inbound.Id)
  271. if err != nil {
  272. return inbound, false, err
  273. }
  274. tag := oldInbound.Tag
  275. db := database.GetDB()
  276. tx := db.Begin()
  277. defer func() {
  278. if err != nil {
  279. tx.Rollback()
  280. } else {
  281. tx.Commit()
  282. }
  283. }()
  284. err = s.updateClientTraffics(tx, oldInbound, inbound)
  285. if err != nil {
  286. return inbound, false, err
  287. }
  288. oldInbound.Up = inbound.Up
  289. oldInbound.Down = inbound.Down
  290. oldInbound.Total = inbound.Total
  291. oldInbound.Remark = inbound.Remark
  292. oldInbound.Enable = inbound.Enable
  293. oldInbound.ExpiryTime = inbound.ExpiryTime
  294. oldInbound.Listen = inbound.Listen
  295. oldInbound.Port = inbound.Port
  296. oldInbound.Protocol = inbound.Protocol
  297. oldInbound.Settings = inbound.Settings
  298. oldInbound.StreamSettings = inbound.StreamSettings
  299. oldInbound.Sniffing = inbound.Sniffing
  300. oldInbound.Allocate = inbound.Allocate
  301. if inbound.Listen == "" || inbound.Listen == "0.0.0.0" || inbound.Listen == "::" || inbound.Listen == "::0" {
  302. oldInbound.Tag = fmt.Sprintf("inbound-%v", inbound.Port)
  303. } else {
  304. oldInbound.Tag = fmt.Sprintf("inbound-%v:%v", inbound.Listen, inbound.Port)
  305. }
  306. needRestart := false
  307. s.xrayApi.Init(p.GetAPIPort())
  308. if s.xrayApi.DelInbound(tag) == nil {
  309. logger.Debug("Old inbound deleted by api:", tag)
  310. }
  311. if inbound.Enable {
  312. inboundJson, err2 := json.MarshalIndent(oldInbound.GenXrayInboundConfig(), "", " ")
  313. if err2 != nil {
  314. logger.Debug("Unable to marshal updated inbound config:", err2)
  315. needRestart = true
  316. } else {
  317. err2 = s.xrayApi.AddInbound(inboundJson)
  318. if err2 == nil {
  319. logger.Debug("Updated inbound added by api:", oldInbound.Tag)
  320. } else {
  321. logger.Debug("Unable to update inbound by api:", err2)
  322. needRestart = true
  323. }
  324. }
  325. }
  326. s.xrayApi.Close()
  327. return inbound, needRestart, tx.Save(oldInbound).Error
  328. }
  329. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  330. oldClients, err := s.GetClients(oldInbound)
  331. if err != nil {
  332. return err
  333. }
  334. newClients, err := s.GetClients(newInbound)
  335. if err != nil {
  336. return err
  337. }
  338. var emailExists bool
  339. for _, oldClient := range oldClients {
  340. emailExists = false
  341. for _, newClient := range newClients {
  342. if oldClient.Email == newClient.Email {
  343. emailExists = true
  344. break
  345. }
  346. }
  347. if !emailExists {
  348. err = s.DelClientStat(tx, oldClient.Email)
  349. if err != nil {
  350. return err
  351. }
  352. }
  353. }
  354. for _, newClient := range newClients {
  355. emailExists = false
  356. for _, oldClient := range oldClients {
  357. if newClient.Email == oldClient.Email {
  358. emailExists = true
  359. break
  360. }
  361. }
  362. if !emailExists {
  363. err = s.AddClientStat(tx, oldInbound.Id, &newClient)
  364. if err != nil {
  365. return err
  366. }
  367. }
  368. }
  369. return nil
  370. }
  371. func (s *InboundService) AddInboundClient(data *model.Inbound) (bool, error) {
  372. clients, err := s.GetClients(data)
  373. if err != nil {
  374. return false, err
  375. }
  376. var settings map[string]any
  377. err = json.Unmarshal([]byte(data.Settings), &settings)
  378. if err != nil {
  379. return false, err
  380. }
  381. interfaceClients := settings["clients"].([]any)
  382. existEmail, err := s.checkEmailsExistForClients(clients)
  383. if err != nil {
  384. return false, err
  385. }
  386. if existEmail != "" {
  387. return false, common.NewError("Duplicate email:", existEmail)
  388. }
  389. oldInbound, err := s.GetInbound(data.Id)
  390. if err != nil {
  391. return false, err
  392. }
  393. // Secure client ID
  394. for _, client := range clients {
  395. if oldInbound.Protocol == "trojan" {
  396. if client.Password == "" {
  397. return false, common.NewError("empty client ID")
  398. }
  399. } else if oldInbound.Protocol == "shadowsocks" {
  400. if client.Email == "" {
  401. return false, common.NewError("empty client ID")
  402. }
  403. } else {
  404. if client.ID == "" {
  405. return false, common.NewError("empty client ID")
  406. }
  407. }
  408. }
  409. var oldSettings map[string]any
  410. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  411. if err != nil {
  412. return false, err
  413. }
  414. oldClients := oldSettings["clients"].([]any)
  415. oldClients = append(oldClients, interfaceClients...)
  416. oldSettings["clients"] = oldClients
  417. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  418. if err != nil {
  419. return false, err
  420. }
  421. oldInbound.Settings = string(newSettings)
  422. db := database.GetDB()
  423. tx := db.Begin()
  424. defer func() {
  425. if err != nil {
  426. tx.Rollback()
  427. } else {
  428. tx.Commit()
  429. }
  430. }()
  431. needRestart := false
  432. s.xrayApi.Init(p.GetAPIPort())
  433. for _, client := range clients {
  434. if len(client.Email) > 0 {
  435. s.AddClientStat(tx, data.Id, &client)
  436. if client.Enable {
  437. cipher := ""
  438. if oldInbound.Protocol == "shadowsocks" {
  439. cipher = oldSettings["method"].(string)
  440. }
  441. err1 := s.xrayApi.AddUser(string(oldInbound.Protocol), oldInbound.Tag, map[string]any{
  442. "email": client.Email,
  443. "id": client.ID,
  444. "security": client.Security,
  445. "flow": client.Flow,
  446. "password": client.Password,
  447. "cipher": cipher,
  448. })
  449. if err1 == nil {
  450. logger.Debug("Client added by api:", client.Email)
  451. } else {
  452. logger.Debug("Error in adding client by api:", err1)
  453. needRestart = true
  454. }
  455. }
  456. } else {
  457. needRestart = true
  458. }
  459. }
  460. s.xrayApi.Close()
  461. return needRestart, tx.Save(oldInbound).Error
  462. }
  463. func (s *InboundService) DelInboundClient(inboundId int, clientId string) (bool, error) {
  464. oldInbound, err := s.GetInbound(inboundId)
  465. if err != nil {
  466. logger.Error("Load Old Data Error")
  467. return false, err
  468. }
  469. var settings map[string]any
  470. err = json.Unmarshal([]byte(oldInbound.Settings), &settings)
  471. if err != nil {
  472. return false, err
  473. }
  474. email := ""
  475. client_key := "id"
  476. if oldInbound.Protocol == "trojan" {
  477. client_key = "password"
  478. }
  479. if oldInbound.Protocol == "shadowsocks" {
  480. client_key = "email"
  481. }
  482. interfaceClients := settings["clients"].([]any)
  483. var newClients []any
  484. needApiDel := false
  485. for _, client := range interfaceClients {
  486. c := client.(map[string]any)
  487. c_id := c[client_key].(string)
  488. if c_id == clientId {
  489. email, _ = c["email"].(string)
  490. needApiDel, _ = c["enable"].(bool)
  491. } else {
  492. newClients = append(newClients, client)
  493. }
  494. }
  495. if len(newClients) == 0 {
  496. return false, common.NewError("no client remained in Inbound")
  497. }
  498. settings["clients"] = newClients
  499. newSettings, err := json.MarshalIndent(settings, "", " ")
  500. if err != nil {
  501. return false, err
  502. }
  503. oldInbound.Settings = string(newSettings)
  504. db := database.GetDB()
  505. err = s.DelClientIPs(db, email)
  506. if err != nil {
  507. logger.Error("Error in delete client IPs")
  508. return false, err
  509. }
  510. needRestart := false
  511. if len(email) > 0 {
  512. notDepleted := true
  513. err = db.Model(xray.ClientTraffic{}).Select("enable").Where("email = ?", email).First(&notDepleted).Error
  514. if err != nil {
  515. logger.Error("Get stats error")
  516. return false, err
  517. }
  518. err = s.DelClientStat(db, email)
  519. if err != nil {
  520. logger.Error("Delete stats Data Error")
  521. return false, err
  522. }
  523. if needApiDel && notDepleted {
  524. s.xrayApi.Init(p.GetAPIPort())
  525. err1 := s.xrayApi.RemoveUser(oldInbound.Tag, email)
  526. if err1 == nil {
  527. logger.Debug("Client deleted by api:", email)
  528. needRestart = false
  529. } else {
  530. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  531. logger.Debug("User is already deleted. Nothing to do more...")
  532. } else {
  533. logger.Debug("Error in deleting client by api:", err1)
  534. needRestart = true
  535. }
  536. }
  537. s.xrayApi.Close()
  538. }
  539. }
  540. return needRestart, db.Save(oldInbound).Error
  541. }
  542. func (s *InboundService) UpdateInboundClient(data *model.Inbound, clientId string) (bool, error) {
  543. clients, err := s.GetClients(data)
  544. if err != nil {
  545. return false, err
  546. }
  547. var settings map[string]any
  548. err = json.Unmarshal([]byte(data.Settings), &settings)
  549. if err != nil {
  550. return false, err
  551. }
  552. interfaceClients := settings["clients"].([]any)
  553. oldInbound, err := s.GetInbound(data.Id)
  554. if err != nil {
  555. return false, err
  556. }
  557. oldClients, err := s.GetClients(oldInbound)
  558. if err != nil {
  559. return false, err
  560. }
  561. oldEmail := ""
  562. newClientId := ""
  563. clientIndex := -1
  564. for index, oldClient := range oldClients {
  565. oldClientId := ""
  566. if oldInbound.Protocol == "trojan" {
  567. oldClientId = oldClient.Password
  568. newClientId = clients[0].Password
  569. } else if oldInbound.Protocol == "shadowsocks" {
  570. oldClientId = oldClient.Email
  571. newClientId = clients[0].Email
  572. } else {
  573. oldClientId = oldClient.ID
  574. newClientId = clients[0].ID
  575. }
  576. if clientId == oldClientId {
  577. oldEmail = oldClient.Email
  578. clientIndex = index
  579. break
  580. }
  581. }
  582. // Validate new client ID
  583. if newClientId == "" || clientIndex == -1 {
  584. return false, common.NewError("empty client ID")
  585. }
  586. if len(clients[0].Email) > 0 && clients[0].Email != oldEmail {
  587. existEmail, err := s.checkEmailsExistForClients(clients)
  588. if err != nil {
  589. return false, err
  590. }
  591. if existEmail != "" {
  592. return false, common.NewError("Duplicate email:", existEmail)
  593. }
  594. }
  595. var oldSettings map[string]any
  596. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  597. if err != nil {
  598. return false, err
  599. }
  600. settingsClients := oldSettings["clients"].([]any)
  601. settingsClients[clientIndex] = interfaceClients[0]
  602. oldSettings["clients"] = settingsClients
  603. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  604. if err != nil {
  605. return false, err
  606. }
  607. oldInbound.Settings = string(newSettings)
  608. db := database.GetDB()
  609. tx := db.Begin()
  610. defer func() {
  611. if err != nil {
  612. tx.Rollback()
  613. } else {
  614. tx.Commit()
  615. }
  616. }()
  617. if len(clients[0].Email) > 0 {
  618. if len(oldEmail) > 0 {
  619. err = s.UpdateClientStat(tx, oldEmail, &clients[0])
  620. if err != nil {
  621. return false, err
  622. }
  623. err = s.UpdateClientIPs(tx, oldEmail, clients[0].Email)
  624. if err != nil {
  625. return false, err
  626. }
  627. } else {
  628. s.AddClientStat(tx, data.Id, &clients[0])
  629. }
  630. } else {
  631. err = s.DelClientStat(tx, oldEmail)
  632. if err != nil {
  633. return false, err
  634. }
  635. err = s.DelClientIPs(tx, oldEmail)
  636. if err != nil {
  637. return false, err
  638. }
  639. }
  640. needRestart := false
  641. if len(oldEmail) > 0 {
  642. s.xrayApi.Init(p.GetAPIPort())
  643. if oldClients[clientIndex].Enable {
  644. err1 := s.xrayApi.RemoveUser(oldInbound.Tag, oldEmail)
  645. if err1 == nil {
  646. logger.Debug("Old client deleted by api:", oldEmail)
  647. } else {
  648. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", oldEmail)) {
  649. logger.Debug("User is already deleted. Nothing to do more...")
  650. } else {
  651. logger.Debug("Error in deleting client by api:", err1)
  652. needRestart = true
  653. }
  654. }
  655. }
  656. if clients[0].Enable {
  657. cipher := ""
  658. if oldInbound.Protocol == "shadowsocks" {
  659. cipher = oldSettings["method"].(string)
  660. }
  661. err1 := s.xrayApi.AddUser(string(oldInbound.Protocol), oldInbound.Tag, map[string]any{
  662. "email": clients[0].Email,
  663. "id": clients[0].ID,
  664. "security": clients[0].Security,
  665. "flow": clients[0].Flow,
  666. "password": clients[0].Password,
  667. "cipher": cipher,
  668. })
  669. if err1 == nil {
  670. logger.Debug("Client edited by api:", clients[0].Email)
  671. } else {
  672. logger.Debug("Error in adding client by api:", err1)
  673. needRestart = true
  674. }
  675. }
  676. s.xrayApi.Close()
  677. } else {
  678. logger.Debug("Client old email not found")
  679. needRestart = true
  680. }
  681. return needRestart, tx.Save(oldInbound).Error
  682. }
  683. func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (error, bool) {
  684. var err error
  685. db := database.GetDB()
  686. tx := db.Begin()
  687. defer func() {
  688. if err != nil {
  689. tx.Rollback()
  690. } else {
  691. tx.Commit()
  692. }
  693. }()
  694. err = s.addInboundTraffic(tx, inboundTraffics)
  695. if err != nil {
  696. return err, false
  697. }
  698. err = s.addClientTraffic(tx, clientTraffics)
  699. if err != nil {
  700. return err, false
  701. }
  702. needRestart0, count, err := s.autoRenewClients(tx)
  703. if err != nil {
  704. logger.Warning("Error in renew clients:", err)
  705. } else if count > 0 {
  706. logger.Debugf("%v clients renewed", count)
  707. }
  708. needRestart1, count, err := s.disableInvalidClients(tx)
  709. if err != nil {
  710. logger.Warning("Error in disabling invalid clients:", err)
  711. } else if count > 0 {
  712. logger.Debugf("%v clients disabled", count)
  713. }
  714. needRestart2, count, err := s.disableInvalidInbounds(tx)
  715. if err != nil {
  716. logger.Warning("Error in disabling invalid inbounds:", err)
  717. } else if count > 0 {
  718. logger.Debugf("%v inbounds disabled", count)
  719. }
  720. return nil, (needRestart0 || needRestart1 || needRestart2)
  721. }
  722. func (s *InboundService) addInboundTraffic(tx *gorm.DB, traffics []*xray.Traffic) error {
  723. if len(traffics) == 0 {
  724. return nil
  725. }
  726. var err error
  727. for _, traffic := range traffics {
  728. if traffic.IsInbound {
  729. err = tx.Model(&model.Inbound{}).Where("tag = ?", traffic.Tag).
  730. Updates(map[string]any{
  731. "up": gorm.Expr("up + ?", traffic.Up),
  732. "down": gorm.Expr("down + ?", traffic.Down),
  733. }).Error
  734. if err != nil {
  735. return err
  736. }
  737. }
  738. }
  739. return nil
  740. }
  741. func (s *InboundService) addClientTraffic(tx *gorm.DB, traffics []*xray.ClientTraffic) (err error) {
  742. if len(traffics) == 0 {
  743. // Empty onlineUsers
  744. if p != nil {
  745. p.SetOnlineClients(nil)
  746. }
  747. return nil
  748. }
  749. var onlineClients []string
  750. emails := make([]string, 0, len(traffics))
  751. for _, traffic := range traffics {
  752. emails = append(emails, traffic.Email)
  753. }
  754. dbClientTraffics := make([]*xray.ClientTraffic, 0, len(traffics))
  755. err = tx.Model(xray.ClientTraffic{}).Where("email IN (?)", emails).Find(&dbClientTraffics).Error
  756. if err != nil {
  757. return err
  758. }
  759. // Avoid empty slice error
  760. if len(dbClientTraffics) == 0 {
  761. return nil
  762. }
  763. dbClientTraffics, err = s.adjustTraffics(tx, dbClientTraffics)
  764. if err != nil {
  765. return err
  766. }
  767. for dbTraffic_index := range dbClientTraffics {
  768. for traffic_index := range traffics {
  769. if dbClientTraffics[dbTraffic_index].Email == traffics[traffic_index].Email {
  770. dbClientTraffics[dbTraffic_index].Up += traffics[traffic_index].Up
  771. dbClientTraffics[dbTraffic_index].Down += traffics[traffic_index].Down
  772. // Add user in onlineUsers array on traffic
  773. if traffics[traffic_index].Up+traffics[traffic_index].Down > 0 {
  774. onlineClients = append(onlineClients, traffics[traffic_index].Email)
  775. }
  776. break
  777. }
  778. }
  779. }
  780. // Set onlineUsers
  781. p.SetOnlineClients(onlineClients)
  782. err = tx.Save(dbClientTraffics).Error
  783. if err != nil {
  784. logger.Warning("AddClientTraffic update data ", err)
  785. }
  786. return nil
  787. }
  788. func (s *InboundService) adjustTraffics(tx *gorm.DB, dbClientTraffics []*xray.ClientTraffic) ([]*xray.ClientTraffic, error) {
  789. inboundIds := make([]int, 0, len(dbClientTraffics))
  790. for _, dbClientTraffic := range dbClientTraffics {
  791. if dbClientTraffic.ExpiryTime < 0 {
  792. inboundIds = append(inboundIds, dbClientTraffic.InboundId)
  793. }
  794. }
  795. if len(inboundIds) > 0 {
  796. var inbounds []*model.Inbound
  797. err := tx.Model(model.Inbound{}).Where("id IN (?)", inboundIds).Find(&inbounds).Error
  798. if err != nil {
  799. return nil, err
  800. }
  801. for inbound_index := range inbounds {
  802. settings := map[string]any{}
  803. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  804. clients, ok := settings["clients"].([]any)
  805. if ok {
  806. var newClients []any
  807. for client_index := range clients {
  808. c := clients[client_index].(map[string]any)
  809. for traffic_index := range dbClientTraffics {
  810. if dbClientTraffics[traffic_index].ExpiryTime < 0 && c["email"] == dbClientTraffics[traffic_index].Email {
  811. oldExpiryTime := c["expiryTime"].(float64)
  812. newExpiryTime := (time.Now().Unix() * 1000) - int64(oldExpiryTime)
  813. c["expiryTime"] = newExpiryTime
  814. dbClientTraffics[traffic_index].ExpiryTime = newExpiryTime
  815. break
  816. }
  817. }
  818. newClients = append(newClients, any(c))
  819. }
  820. settings["clients"] = newClients
  821. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  822. if err != nil {
  823. return nil, err
  824. }
  825. inbounds[inbound_index].Settings = string(modifiedSettings)
  826. }
  827. }
  828. err = tx.Save(inbounds).Error
  829. if err != nil {
  830. logger.Warning("AddClientTraffic update inbounds ", err)
  831. logger.Error(inbounds)
  832. }
  833. }
  834. return dbClientTraffics, nil
  835. }
  836. func (s *InboundService) autoRenewClients(tx *gorm.DB) (bool, int64, error) {
  837. // check for time expired
  838. var traffics []*xray.ClientTraffic
  839. now := time.Now().Unix() * 1000
  840. var err, err1 error
  841. err = tx.Model(xray.ClientTraffic{}).Where("reset > 0 and expiry_time > 0 and expiry_time <= ?", now).Find(&traffics).Error
  842. if err != nil {
  843. return false, 0, err
  844. }
  845. // return if there is no client to renew
  846. if len(traffics) == 0 {
  847. return false, 0, nil
  848. }
  849. var inbound_ids []int
  850. var inbounds []*model.Inbound
  851. needRestart := false
  852. var clientsToAdd []struct {
  853. protocol string
  854. tag string
  855. client map[string]any
  856. }
  857. for _, traffic := range traffics {
  858. inbound_ids = append(inbound_ids, traffic.InboundId)
  859. }
  860. err = tx.Model(model.Inbound{}).Where("id IN ?", inbound_ids).Find(&inbounds).Error
  861. if err != nil {
  862. return false, 0, err
  863. }
  864. for inbound_index := range inbounds {
  865. settings := map[string]any{}
  866. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  867. clients := settings["clients"].([]any)
  868. for client_index := range clients {
  869. c := clients[client_index].(map[string]any)
  870. for traffic_index, traffic := range traffics {
  871. if traffic.Email == c["email"].(string) {
  872. newExpiryTime := traffic.ExpiryTime
  873. for newExpiryTime < now {
  874. newExpiryTime += (int64(traffic.Reset) * 86400000)
  875. }
  876. c["expiryTime"] = newExpiryTime
  877. traffics[traffic_index].ExpiryTime = newExpiryTime
  878. traffics[traffic_index].Down = 0
  879. traffics[traffic_index].Up = 0
  880. if !traffic.Enable {
  881. traffics[traffic_index].Enable = true
  882. clientsToAdd = append(clientsToAdd,
  883. struct {
  884. protocol string
  885. tag string
  886. client map[string]any
  887. }{
  888. protocol: string(inbounds[inbound_index].Protocol),
  889. tag: inbounds[inbound_index].Tag,
  890. client: c,
  891. })
  892. }
  893. clients[client_index] = any(c)
  894. break
  895. }
  896. }
  897. }
  898. settings["clients"] = clients
  899. newSettings, err := json.MarshalIndent(settings, "", " ")
  900. if err != nil {
  901. return false, 0, err
  902. }
  903. inbounds[inbound_index].Settings = string(newSettings)
  904. }
  905. err = tx.Save(inbounds).Error
  906. if err != nil {
  907. return false, 0, err
  908. }
  909. err = tx.Save(traffics).Error
  910. if err != nil {
  911. return false, 0, err
  912. }
  913. if p != nil {
  914. err1 = s.xrayApi.Init(p.GetAPIPort())
  915. if err1 != nil {
  916. return true, int64(len(traffics)), nil
  917. }
  918. for _, clientToAdd := range clientsToAdd {
  919. err1 = s.xrayApi.AddUser(clientToAdd.protocol, clientToAdd.tag, clientToAdd.client)
  920. if err1 != nil {
  921. needRestart = true
  922. }
  923. }
  924. s.xrayApi.Close()
  925. }
  926. return needRestart, int64(len(traffics)), nil
  927. }
  928. func (s *InboundService) disableInvalidInbounds(tx *gorm.DB) (bool, int64, error) {
  929. now := time.Now().Unix() * 1000
  930. needRestart := false
  931. if p != nil {
  932. var tags []string
  933. err := tx.Table("inbounds").
  934. Select("inbounds.tag").
  935. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  936. Scan(&tags).Error
  937. if err != nil {
  938. return false, 0, err
  939. }
  940. s.xrayApi.Init(p.GetAPIPort())
  941. for _, tag := range tags {
  942. err1 := s.xrayApi.DelInbound(tag)
  943. if err1 == nil {
  944. logger.Debug("Inbound disabled by api:", tag)
  945. } else {
  946. logger.Debug("Error in disabling inbound by api:", err1)
  947. needRestart = true
  948. }
  949. }
  950. s.xrayApi.Close()
  951. }
  952. result := tx.Model(model.Inbound{}).
  953. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  954. Update("enable", false)
  955. err := result.Error
  956. count := result.RowsAffected
  957. return needRestart, count, err
  958. }
  959. func (s *InboundService) disableInvalidClients(tx *gorm.DB) (bool, int64, error) {
  960. now := time.Now().Unix() * 1000
  961. needRestart := false
  962. if p != nil {
  963. var results []struct {
  964. Tag string
  965. Email string
  966. }
  967. err := tx.Table("inbounds").
  968. Select("inbounds.tag, client_traffics.email").
  969. Joins("JOIN client_traffics ON inbounds.id = client_traffics.inbound_id").
  970. 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).
  971. Scan(&results).Error
  972. if err != nil {
  973. return false, 0, err
  974. }
  975. s.xrayApi.Init(p.GetAPIPort())
  976. for _, result := range results {
  977. err1 := s.xrayApi.RemoveUser(result.Tag, result.Email)
  978. if err1 == nil {
  979. logger.Debug("Client disabled by api:", result.Email)
  980. } else {
  981. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", result.Email)) {
  982. logger.Debug("User is already disabled. Nothing to do more...")
  983. } else {
  984. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", result.Email)) {
  985. logger.Debug("User is already disabled. Nothing to do more...")
  986. } else {
  987. logger.Debug("Error in disabling client by api:", err1)
  988. needRestart = true
  989. }
  990. }
  991. }
  992. }
  993. s.xrayApi.Close()
  994. }
  995. result := tx.Model(xray.ClientTraffic{}).
  996. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  997. Update("enable", false)
  998. err := result.Error
  999. count := result.RowsAffected
  1000. return needRestart, count, err
  1001. }
  1002. func (s *InboundService) GetInboundTags() (string, error) {
  1003. db := database.GetDB()
  1004. var inboundTags []string
  1005. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  1006. if err != nil && err != gorm.ErrRecordNotFound {
  1007. return "", err
  1008. }
  1009. tags, _ := json.Marshal(inboundTags)
  1010. return string(tags), nil
  1011. }
  1012. func (s *InboundService) MigrationRemoveOrphanedTraffics() {
  1013. db := database.GetDB()
  1014. db.Exec(`
  1015. DELETE FROM client_traffics
  1016. WHERE email NOT IN (
  1017. SELECT JSON_EXTRACT(client.value, '$.email')
  1018. FROM inbounds,
  1019. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  1020. )
  1021. `)
  1022. }
  1023. func (s *InboundService) AddClientStat(tx *gorm.DB, inboundId int, client *model.Client) error {
  1024. clientTraffic := xray.ClientTraffic{}
  1025. clientTraffic.InboundId = inboundId
  1026. clientTraffic.Email = client.Email
  1027. clientTraffic.Total = client.TotalGB
  1028. clientTraffic.ExpiryTime = client.ExpiryTime
  1029. clientTraffic.Enable = true
  1030. clientTraffic.Up = 0
  1031. clientTraffic.Down = 0
  1032. clientTraffic.Reset = client.Reset
  1033. result := tx.Create(&clientTraffic)
  1034. err := result.Error
  1035. return err
  1036. }
  1037. func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *model.Client) error {
  1038. result := tx.Model(xray.ClientTraffic{}).
  1039. Where("email = ?", email).
  1040. Updates(map[string]any{
  1041. "enable": true,
  1042. "email": client.Email,
  1043. "total": client.TotalGB,
  1044. "expiry_time": client.ExpiryTime,
  1045. "reset": client.Reset,
  1046. })
  1047. err := result.Error
  1048. return err
  1049. }
  1050. func (s *InboundService) UpdateClientIPs(tx *gorm.DB, oldEmail string, newEmail string) error {
  1051. return tx.Model(model.InboundClientIps{}).Where("client_email = ?", oldEmail).Update("client_email", newEmail).Error
  1052. }
  1053. func (s *InboundService) DelClientStat(tx *gorm.DB, email string) error {
  1054. return tx.Where("email = ?", email).Delete(xray.ClientTraffic{}).Error
  1055. }
  1056. func (s *InboundService) DelClientIPs(tx *gorm.DB, email string) error {
  1057. return tx.Where("client_email = ?", email).Delete(model.InboundClientIps{}).Error
  1058. }
  1059. func (s *InboundService) GetClientInboundByTrafficID(trafficId int) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  1060. db := database.GetDB()
  1061. var traffics []*xray.ClientTraffic
  1062. err = db.Model(xray.ClientTraffic{}).Where("id = ?", trafficId).Find(&traffics).Error
  1063. if err != nil {
  1064. logger.Warningf("Error retrieving ClientTraffic with trafficId %d: %v", trafficId, err)
  1065. return nil, nil, err
  1066. }
  1067. if len(traffics) > 0 {
  1068. inbound, err = s.GetInbound(traffics[0].InboundId)
  1069. return traffics[0], inbound, err
  1070. }
  1071. return nil, nil, nil
  1072. }
  1073. func (s *InboundService) GetClientInboundByEmail(email string) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  1074. db := database.GetDB()
  1075. var traffics []*xray.ClientTraffic
  1076. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error
  1077. if err != nil {
  1078. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  1079. return nil, nil, err
  1080. }
  1081. if len(traffics) > 0 {
  1082. inbound, err = s.GetInbound(traffics[0].InboundId)
  1083. return traffics[0], inbound, err
  1084. }
  1085. return nil, nil, nil
  1086. }
  1087. func (s *InboundService) GetClientByEmail(clientEmail string) (*xray.ClientTraffic, *model.Client, error) {
  1088. traffic, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1089. if err != nil {
  1090. return nil, nil, err
  1091. }
  1092. if inbound == nil {
  1093. return nil, nil, common.NewError("Inbound Not Found For Email:", clientEmail)
  1094. }
  1095. clients, err := s.GetClients(inbound)
  1096. if err != nil {
  1097. return nil, nil, err
  1098. }
  1099. for _, client := range clients {
  1100. if client.Email == clientEmail {
  1101. return traffic, &client, nil
  1102. }
  1103. }
  1104. return nil, nil, common.NewError("Client Not Found In Inbound For Email:", clientEmail)
  1105. }
  1106. func (s *InboundService) SetClientTelegramUserID(trafficId int, tgId int64) (bool, error) {
  1107. traffic, inbound, err := s.GetClientInboundByTrafficID(trafficId)
  1108. if err != nil {
  1109. return false, err
  1110. }
  1111. if inbound == nil {
  1112. return false, common.NewError("Inbound Not Found For Traffic ID:", trafficId)
  1113. }
  1114. clientEmail := traffic.Email
  1115. oldClients, err := s.GetClients(inbound)
  1116. if err != nil {
  1117. return false, err
  1118. }
  1119. clientId := ""
  1120. for _, oldClient := range oldClients {
  1121. if oldClient.Email == clientEmail {
  1122. if inbound.Protocol == "trojan" {
  1123. clientId = oldClient.Password
  1124. } else if inbound.Protocol == "shadowsocks" {
  1125. clientId = oldClient.Email
  1126. } else {
  1127. clientId = oldClient.ID
  1128. }
  1129. break
  1130. }
  1131. }
  1132. if len(clientId) == 0 {
  1133. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1134. }
  1135. var settings map[string]any
  1136. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1137. if err != nil {
  1138. return false, err
  1139. }
  1140. clients := settings["clients"].([]any)
  1141. var newClients []any
  1142. for client_index := range clients {
  1143. c := clients[client_index].(map[string]any)
  1144. if c["email"] == clientEmail {
  1145. c["tgId"] = tgId
  1146. newClients = append(newClients, any(c))
  1147. }
  1148. }
  1149. settings["clients"] = newClients
  1150. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1151. if err != nil {
  1152. return false, err
  1153. }
  1154. inbound.Settings = string(modifiedSettings)
  1155. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1156. return needRestart, err
  1157. }
  1158. func (s *InboundService) checkIsEnabledByEmail(clientEmail string) (bool, error) {
  1159. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1160. if err != nil {
  1161. return false, err
  1162. }
  1163. if inbound == nil {
  1164. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1165. }
  1166. clients, err := s.GetClients(inbound)
  1167. if err != nil {
  1168. return false, err
  1169. }
  1170. isEnable := false
  1171. for _, client := range clients {
  1172. if client.Email == clientEmail {
  1173. isEnable = client.Enable
  1174. break
  1175. }
  1176. }
  1177. return isEnable, err
  1178. }
  1179. func (s *InboundService) ToggleClientEnableByEmail(clientEmail string) (bool, bool, error) {
  1180. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1181. if err != nil {
  1182. return false, false, err
  1183. }
  1184. if inbound == nil {
  1185. return false, false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1186. }
  1187. oldClients, err := s.GetClients(inbound)
  1188. if err != nil {
  1189. return false, false, err
  1190. }
  1191. clientId := ""
  1192. clientOldEnabled := false
  1193. for _, oldClient := range oldClients {
  1194. if oldClient.Email == clientEmail {
  1195. if inbound.Protocol == "trojan" {
  1196. clientId = oldClient.Password
  1197. } else if inbound.Protocol == "shadowsocks" {
  1198. clientId = oldClient.Email
  1199. } else {
  1200. clientId = oldClient.ID
  1201. }
  1202. clientOldEnabled = oldClient.Enable
  1203. break
  1204. }
  1205. }
  1206. if len(clientId) == 0 {
  1207. return false, false, common.NewError("Client Not Found For Email:", clientEmail)
  1208. }
  1209. var settings map[string]any
  1210. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1211. if err != nil {
  1212. return false, false, err
  1213. }
  1214. clients := settings["clients"].([]any)
  1215. var newClients []any
  1216. for client_index := range clients {
  1217. c := clients[client_index].(map[string]any)
  1218. if c["email"] == clientEmail {
  1219. c["enable"] = !clientOldEnabled
  1220. newClients = append(newClients, any(c))
  1221. }
  1222. }
  1223. settings["clients"] = newClients
  1224. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1225. if err != nil {
  1226. return false, false, err
  1227. }
  1228. inbound.Settings = string(modifiedSettings)
  1229. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1230. if err != nil {
  1231. return false, needRestart, err
  1232. }
  1233. return !clientOldEnabled, needRestart, nil
  1234. }
  1235. func (s *InboundService) ResetClientIpLimitByEmail(clientEmail string, count int) (bool, error) {
  1236. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1237. if err != nil {
  1238. return false, err
  1239. }
  1240. if inbound == nil {
  1241. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1242. }
  1243. oldClients, err := s.GetClients(inbound)
  1244. if err != nil {
  1245. return false, err
  1246. }
  1247. clientId := ""
  1248. for _, oldClient := range oldClients {
  1249. if oldClient.Email == clientEmail {
  1250. if inbound.Protocol == "trojan" {
  1251. clientId = oldClient.Password
  1252. } else if inbound.Protocol == "shadowsocks" {
  1253. clientId = oldClient.Email
  1254. } else {
  1255. clientId = oldClient.ID
  1256. }
  1257. break
  1258. }
  1259. }
  1260. if len(clientId) == 0 {
  1261. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1262. }
  1263. var settings map[string]any
  1264. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1265. if err != nil {
  1266. return false, err
  1267. }
  1268. clients := settings["clients"].([]any)
  1269. var newClients []any
  1270. for client_index := range clients {
  1271. c := clients[client_index].(map[string]any)
  1272. if c["email"] == clientEmail {
  1273. c["limitIp"] = count
  1274. newClients = append(newClients, any(c))
  1275. }
  1276. }
  1277. settings["clients"] = newClients
  1278. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1279. if err != nil {
  1280. return false, err
  1281. }
  1282. inbound.Settings = string(modifiedSettings)
  1283. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1284. return needRestart, err
  1285. }
  1286. func (s *InboundService) ResetClientExpiryTimeByEmail(clientEmail string, expiry_time int64) (bool, error) {
  1287. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1288. if err != nil {
  1289. return false, err
  1290. }
  1291. if inbound == nil {
  1292. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1293. }
  1294. oldClients, err := s.GetClients(inbound)
  1295. if err != nil {
  1296. return false, err
  1297. }
  1298. clientId := ""
  1299. for _, oldClient := range oldClients {
  1300. if oldClient.Email == clientEmail {
  1301. if inbound.Protocol == "trojan" {
  1302. clientId = oldClient.Password
  1303. } else if inbound.Protocol == "shadowsocks" {
  1304. clientId = oldClient.Email
  1305. } else {
  1306. clientId = oldClient.ID
  1307. }
  1308. break
  1309. }
  1310. }
  1311. if len(clientId) == 0 {
  1312. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1313. }
  1314. var settings map[string]any
  1315. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1316. if err != nil {
  1317. return false, err
  1318. }
  1319. clients := settings["clients"].([]any)
  1320. var newClients []any
  1321. for client_index := range clients {
  1322. c := clients[client_index].(map[string]any)
  1323. if c["email"] == clientEmail {
  1324. c["expiryTime"] = expiry_time
  1325. newClients = append(newClients, any(c))
  1326. }
  1327. }
  1328. settings["clients"] = newClients
  1329. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1330. if err != nil {
  1331. return false, err
  1332. }
  1333. inbound.Settings = string(modifiedSettings)
  1334. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1335. return needRestart, err
  1336. }
  1337. func (s *InboundService) ResetClientTrafficLimitByEmail(clientEmail string, totalGB int) (bool, error) {
  1338. if totalGB < 0 {
  1339. return false, common.NewError("totalGB must be >= 0")
  1340. }
  1341. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1342. if err != nil {
  1343. return false, err
  1344. }
  1345. if inbound == nil {
  1346. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1347. }
  1348. oldClients, err := s.GetClients(inbound)
  1349. if err != nil {
  1350. return false, err
  1351. }
  1352. clientId := ""
  1353. for _, oldClient := range oldClients {
  1354. if oldClient.Email == clientEmail {
  1355. if inbound.Protocol == "trojan" {
  1356. clientId = oldClient.Password
  1357. } else if inbound.Protocol == "shadowsocks" {
  1358. clientId = oldClient.Email
  1359. } else {
  1360. clientId = oldClient.ID
  1361. }
  1362. break
  1363. }
  1364. }
  1365. if len(clientId) == 0 {
  1366. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1367. }
  1368. var settings map[string]any
  1369. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1370. if err != nil {
  1371. return false, err
  1372. }
  1373. clients := settings["clients"].([]any)
  1374. var newClients []any
  1375. for client_index := range clients {
  1376. c := clients[client_index].(map[string]any)
  1377. if c["email"] == clientEmail {
  1378. c["totalGB"] = totalGB * 1024 * 1024 * 1024
  1379. newClients = append(newClients, any(c))
  1380. }
  1381. }
  1382. settings["clients"] = newClients
  1383. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1384. if err != nil {
  1385. return false, err
  1386. }
  1387. inbound.Settings = string(modifiedSettings)
  1388. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1389. return needRestart, err
  1390. }
  1391. func (s *InboundService) ResetClientTrafficByEmail(clientEmail string) error {
  1392. db := database.GetDB()
  1393. result := db.Model(xray.ClientTraffic{}).
  1394. Where("email = ?", clientEmail).
  1395. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  1396. err := result.Error
  1397. if err != nil {
  1398. return err
  1399. }
  1400. return nil
  1401. }
  1402. func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (bool, error) {
  1403. needRestart := false
  1404. traffic, err := s.GetClientTrafficByEmail(clientEmail)
  1405. if err != nil {
  1406. return false, err
  1407. }
  1408. if !traffic.Enable {
  1409. inbound, err := s.GetInbound(id)
  1410. if err != nil {
  1411. return false, err
  1412. }
  1413. clients, err := s.GetClients(inbound)
  1414. if err != nil {
  1415. return false, err
  1416. }
  1417. for _, client := range clients {
  1418. if client.Email == clientEmail && client.Enable {
  1419. s.xrayApi.Init(p.GetAPIPort())
  1420. cipher := ""
  1421. if string(inbound.Protocol) == "shadowsocks" {
  1422. var oldSettings map[string]any
  1423. err = json.Unmarshal([]byte(inbound.Settings), &oldSettings)
  1424. if err != nil {
  1425. return false, err
  1426. }
  1427. cipher = oldSettings["method"].(string)
  1428. }
  1429. err1 := s.xrayApi.AddUser(string(inbound.Protocol), inbound.Tag, map[string]any{
  1430. "email": client.Email,
  1431. "id": client.ID,
  1432. "security": client.Security,
  1433. "flow": client.Flow,
  1434. "password": client.Password,
  1435. "cipher": cipher,
  1436. })
  1437. if err1 == nil {
  1438. logger.Debug("Client enabled due to reset traffic:", clientEmail)
  1439. } else {
  1440. logger.Debug("Error in enabling client by api:", err1)
  1441. needRestart = true
  1442. }
  1443. s.xrayApi.Close()
  1444. break
  1445. }
  1446. }
  1447. }
  1448. traffic.Up = 0
  1449. traffic.Down = 0
  1450. traffic.Enable = true
  1451. db := database.GetDB()
  1452. err = db.Save(traffic).Error
  1453. if err != nil {
  1454. return false, err
  1455. }
  1456. return needRestart, nil
  1457. }
  1458. func (s *InboundService) ResetAllClientTraffics(id int) error {
  1459. db := database.GetDB()
  1460. whereText := "inbound_id "
  1461. if id == -1 {
  1462. whereText += " > ?"
  1463. } else {
  1464. whereText += " = ?"
  1465. }
  1466. result := db.Model(xray.ClientTraffic{}).
  1467. Where(whereText, id).
  1468. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  1469. err := result.Error
  1470. return err
  1471. }
  1472. func (s *InboundService) ResetAllTraffics() error {
  1473. db := database.GetDB()
  1474. result := db.Model(model.Inbound{}).
  1475. Where("user_id > ?", 0).
  1476. Updates(map[string]any{"up": 0, "down": 0})
  1477. err := result.Error
  1478. return err
  1479. }
  1480. func (s *InboundService) DelDepletedClients(id int) (err error) {
  1481. db := database.GetDB()
  1482. tx := db.Begin()
  1483. defer func() {
  1484. if err == nil {
  1485. tx.Commit()
  1486. } else {
  1487. tx.Rollback()
  1488. }
  1489. }()
  1490. whereText := "reset = 0 and inbound_id "
  1491. if id < 0 {
  1492. whereText += "> ?"
  1493. } else {
  1494. whereText += "= ?"
  1495. }
  1496. depletedClients := []xray.ClientTraffic{}
  1497. err = db.Model(xray.ClientTraffic{}).Where(whereText+" and enable = ?", id, false).Select("inbound_id, GROUP_CONCAT(email) as email").Group("inbound_id").Find(&depletedClients).Error
  1498. if err != nil {
  1499. return err
  1500. }
  1501. for _, depletedClient := range depletedClients {
  1502. emails := strings.Split(depletedClient.Email, ",")
  1503. oldInbound, err := s.GetInbound(depletedClient.InboundId)
  1504. if err != nil {
  1505. return err
  1506. }
  1507. var oldSettings map[string]any
  1508. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1509. if err != nil {
  1510. return err
  1511. }
  1512. oldClients := oldSettings["clients"].([]any)
  1513. var newClients []any
  1514. for _, client := range oldClients {
  1515. deplete := false
  1516. c := client.(map[string]any)
  1517. for _, email := range emails {
  1518. if email == c["email"].(string) {
  1519. deplete = true
  1520. break
  1521. }
  1522. }
  1523. if !deplete {
  1524. newClients = append(newClients, client)
  1525. }
  1526. }
  1527. if len(newClients) > 0 {
  1528. oldSettings["clients"] = newClients
  1529. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  1530. if err != nil {
  1531. return err
  1532. }
  1533. oldInbound.Settings = string(newSettings)
  1534. err = tx.Save(oldInbound).Error
  1535. if err != nil {
  1536. return err
  1537. }
  1538. } else {
  1539. // Delete inbound if no client remains
  1540. s.DelInbound(depletedClient.InboundId)
  1541. }
  1542. }
  1543. err = tx.Where(whereText+" and enable = ?", id, false).Delete(xray.ClientTraffic{}).Error
  1544. if err != nil {
  1545. return err
  1546. }
  1547. return nil
  1548. }
  1549. func (s *InboundService) GetClientTrafficTgBot(tgId int64) ([]*xray.ClientTraffic, error) {
  1550. db := database.GetDB()
  1551. var inbounds []*model.Inbound
  1552. // Retrieve inbounds where settings contain the given tgId
  1553. err := db.Model(model.Inbound{}).Where("settings LIKE ?", fmt.Sprintf(`%%"tgId": %d%%`, tgId)).Find(&inbounds).Error
  1554. if err != nil && err != gorm.ErrRecordNotFound {
  1555. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  1556. return nil, err
  1557. }
  1558. var emails []string
  1559. for _, inbound := range inbounds {
  1560. clients, err := s.GetClients(inbound)
  1561. if err != nil {
  1562. logger.Errorf("Error retrieving clients for inbound %d: %v", inbound.Id, err)
  1563. continue
  1564. }
  1565. for _, client := range clients {
  1566. if client.TgID == tgId {
  1567. emails = append(emails, client.Email)
  1568. }
  1569. }
  1570. }
  1571. var traffics []*xray.ClientTraffic
  1572. err = db.Model(xray.ClientTraffic{}).Where("email IN ?", emails).Find(&traffics).Error
  1573. if err != nil {
  1574. if err == gorm.ErrRecordNotFound {
  1575. logger.Warning("No ClientTraffic records found for emails:", emails)
  1576. return nil, nil
  1577. }
  1578. logger.Errorf("Error retrieving ClientTraffic for emails %v: %v", emails, err)
  1579. return nil, err
  1580. }
  1581. return traffics, nil
  1582. }
  1583. func (s *InboundService) GetClientTrafficByEmail(email string) (traffic *xray.ClientTraffic, err error) {
  1584. db := database.GetDB()
  1585. var traffics []*xray.ClientTraffic
  1586. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error
  1587. if err != nil {
  1588. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  1589. return nil, err
  1590. }
  1591. if len(traffics) > 0 {
  1592. return traffics[0], nil
  1593. }
  1594. return nil, nil
  1595. }
  1596. func (s *InboundService) GetClientTrafficByID(id string) ([]xray.ClientTraffic, error) {
  1597. db := database.GetDB()
  1598. var traffics []xray.ClientTraffic
  1599. err := db.Model(xray.ClientTraffic{}).Where(`email IN(
  1600. SELECT JSON_EXTRACT(client.value, '$.email') as email
  1601. FROM inbounds,
  1602. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  1603. WHERE
  1604. JSON_EXTRACT(client.value, '$.id') in (?)
  1605. )`, id).Find(&traffics).Error
  1606. if err != nil {
  1607. logger.Debug(err)
  1608. return nil, err
  1609. }
  1610. return traffics, err
  1611. }
  1612. func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.ClientTraffic, err error) {
  1613. db := database.GetDB()
  1614. inbound := &model.Inbound{}
  1615. traffic = &xray.ClientTraffic{}
  1616. // Search for inbound settings that contain the query
  1617. err = db.Model(model.Inbound{}).Where("settings LIKE ?", "%\""+query+"\"%").First(inbound).Error
  1618. if err != nil {
  1619. if err == gorm.ErrRecordNotFound {
  1620. logger.Warningf("Inbound settings containing query %s not found: %v", query, err)
  1621. return nil, err
  1622. }
  1623. logger.Errorf("Error searching for inbound settings with query %s: %v", query, err)
  1624. return nil, err
  1625. }
  1626. traffic.InboundId = inbound.Id
  1627. // Unmarshal settings to get clients
  1628. settings := map[string][]model.Client{}
  1629. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1630. logger.Errorf("Error unmarshalling inbound settings for inbound ID %d: %v", inbound.Id, err)
  1631. return nil, err
  1632. }
  1633. clients := settings["clients"]
  1634. for _, client := range clients {
  1635. if (client.ID == query || client.Password == query) && client.Email != "" {
  1636. traffic.Email = client.Email
  1637. break
  1638. }
  1639. }
  1640. if traffic.Email == "" {
  1641. logger.Warningf("No client found with query %s in inbound ID %d", query, inbound.Id)
  1642. return nil, gorm.ErrRecordNotFound
  1643. }
  1644. // Retrieve ClientTraffic based on the found email
  1645. err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error
  1646. if err != nil {
  1647. if err == gorm.ErrRecordNotFound {
  1648. logger.Warningf("ClientTraffic for email %s not found: %v", traffic.Email, err)
  1649. return nil, err
  1650. }
  1651. logger.Errorf("Error retrieving ClientTraffic for email %s: %v", traffic.Email, err)
  1652. return nil, err
  1653. }
  1654. return traffic, nil
  1655. }
  1656. func (s *InboundService) GetInboundClientIps(clientEmail string) (string, error) {
  1657. db := database.GetDB()
  1658. InboundClientIps := &model.InboundClientIps{}
  1659. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  1660. if err != nil {
  1661. return "", err
  1662. }
  1663. return InboundClientIps.Ips, nil
  1664. }
  1665. func (s *InboundService) ClearClientIps(clientEmail string) error {
  1666. db := database.GetDB()
  1667. result := db.Model(model.InboundClientIps{}).
  1668. Where("client_email = ?", clientEmail).
  1669. Update("ips", "")
  1670. err := result.Error
  1671. if err != nil {
  1672. return err
  1673. }
  1674. return nil
  1675. }
  1676. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  1677. db := database.GetDB()
  1678. var inbounds []*model.Inbound
  1679. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  1680. if err != nil && err != gorm.ErrRecordNotFound {
  1681. return nil, err
  1682. }
  1683. return inbounds, nil
  1684. }
  1685. func (s *InboundService) MigrationRequirements() {
  1686. db := database.GetDB()
  1687. tx := db.Begin()
  1688. var err error
  1689. defer func() {
  1690. if err == nil {
  1691. tx.Commit()
  1692. } else {
  1693. tx.Rollback()
  1694. }
  1695. }()
  1696. // Fix inbounds based problems
  1697. var inbounds []*model.Inbound
  1698. err = tx.Model(model.Inbound{}).Where("protocol IN (?)", []string{"vmess", "vless", "trojan"}).Find(&inbounds).Error
  1699. if err != nil && err != gorm.ErrRecordNotFound {
  1700. return
  1701. }
  1702. for inbound_index := range inbounds {
  1703. settings := map[string]any{}
  1704. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1705. clients, ok := settings["clients"].([]any)
  1706. if ok {
  1707. // Fix Client configuration problems
  1708. var newClients []any
  1709. for client_index := range clients {
  1710. c := clients[client_index].(map[string]any)
  1711. // Add email='' if it is not exists
  1712. if _, ok := c["email"]; !ok {
  1713. c["email"] = ""
  1714. }
  1715. // Convert string tgId to int64
  1716. if _, ok := c["tgId"]; ok {
  1717. var tgId any = c["tgId"]
  1718. if tgIdStr, ok2 := tgId.(string); ok2 {
  1719. tgIdInt64, err := strconv.ParseInt(strings.ReplaceAll(tgIdStr, " ", ""), 10, 64)
  1720. if err == nil {
  1721. c["tgId"] = tgIdInt64
  1722. }
  1723. }
  1724. }
  1725. // Remove "flow": "xtls-rprx-direct"
  1726. if _, ok := c["flow"]; ok {
  1727. if c["flow"] == "xtls-rprx-direct" {
  1728. c["flow"] = ""
  1729. }
  1730. }
  1731. newClients = append(newClients, any(c))
  1732. }
  1733. settings["clients"] = newClients
  1734. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1735. if err != nil {
  1736. return
  1737. }
  1738. inbounds[inbound_index].Settings = string(modifiedSettings)
  1739. }
  1740. // Add client traffic row for all clients which has email
  1741. modelClients, err := s.GetClients(inbounds[inbound_index])
  1742. if err != nil {
  1743. return
  1744. }
  1745. for _, modelClient := range modelClients {
  1746. if len(modelClient.Email) > 0 {
  1747. var count int64
  1748. tx.Model(xray.ClientTraffic{}).Where("email = ?", modelClient.Email).Count(&count)
  1749. if count == 0 {
  1750. s.AddClientStat(tx, inbounds[inbound_index].Id, &modelClient)
  1751. }
  1752. }
  1753. }
  1754. }
  1755. tx.Save(inbounds)
  1756. // Remove orphaned traffics
  1757. tx.Where("inbound_id = 0").Delete(xray.ClientTraffic{})
  1758. // Migrate old MultiDomain to External Proxy
  1759. var externalProxy []struct {
  1760. Id int
  1761. Port int
  1762. StreamSettings []byte
  1763. }
  1764. err = tx.Raw(`select id, port, stream_settings
  1765. from inbounds
  1766. WHERE protocol in ('vmess','vless','trojan')
  1767. AND json_extract(stream_settings, '$.security') = 'tls'
  1768. AND json_extract(stream_settings, '$.tlsSettings.settings.domains') IS NOT NULL`).Scan(&externalProxy).Error
  1769. if err != nil || len(externalProxy) == 0 {
  1770. return
  1771. }
  1772. for _, ep := range externalProxy {
  1773. var reverses any
  1774. var stream map[string]any
  1775. json.Unmarshal(ep.StreamSettings, &stream)
  1776. if tlsSettings, ok := stream["tlsSettings"].(map[string]any); ok {
  1777. if settings, ok := tlsSettings["settings"].(map[string]any); ok {
  1778. if domains, ok := settings["domains"].([]any); ok {
  1779. for _, domain := range domains {
  1780. if domainMap, ok := domain.(map[string]any); ok {
  1781. domainMap["forceTls"] = "same"
  1782. domainMap["port"] = ep.Port
  1783. domainMap["dest"] = domainMap["domain"].(string)
  1784. delete(domainMap, "domain")
  1785. }
  1786. }
  1787. }
  1788. reverses = settings["domains"]
  1789. delete(settings, "domains")
  1790. }
  1791. }
  1792. stream["externalProxy"] = reverses
  1793. newStream, _ := json.MarshalIndent(stream, " ", " ")
  1794. tx.Model(model.Inbound{}).Where("id = ?", ep.Id).Update("stream_settings", newStream)
  1795. }
  1796. err = tx.Raw(`UPDATE inbounds
  1797. SET tag = REPLACE(tag, '0.0.0.0:', '')
  1798. WHERE INSTR(tag, '0.0.0.0:') > 0;`).Error
  1799. if err != nil {
  1800. return
  1801. }
  1802. }
  1803. func (s *InboundService) MigrateDB() {
  1804. s.MigrationRequirements()
  1805. s.MigrationRemoveOrphanedTraffics()
  1806. }
  1807. func (s *InboundService) GetOnlineClients() []string {
  1808. return p.GetOnlineClients()
  1809. }
  1810. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  1811. db := database.GetDB()
  1812. // Step 1: Get ClientTraffic records for emails in the input list
  1813. var clients []xray.ClientTraffic
  1814. err := db.Where("email IN ?", emails).Find(&clients).Error
  1815. if err != nil && err != gorm.ErrRecordNotFound {
  1816. return nil, nil, err
  1817. }
  1818. // Step 2: Sort clients by (Up + Down) descending
  1819. sort.Slice(clients, func(i, j int) bool {
  1820. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  1821. })
  1822. // Step 3: Extract sorted valid emails and track found ones
  1823. validEmails := make([]string, 0, len(clients))
  1824. found := make(map[string]bool)
  1825. for _, client := range clients {
  1826. validEmails = append(validEmails, client.Email)
  1827. found[client.Email] = true
  1828. }
  1829. // Step 4: Identify emails that were not found in the database
  1830. extraEmails := make([]string, 0)
  1831. for _, email := range emails {
  1832. if !found[email] {
  1833. extraEmails = append(extraEmails, email)
  1834. }
  1835. }
  1836. return validEmails, extraEmails, nil
  1837. }