inbound.go 57 KB

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