1
0

inbound.go 52 KB

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