inbound.go 74 KB

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