inbound.go 61 KB

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