1
0

inbound.go 52 KB

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