inbound.go 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809
  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": {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. clientFound := false
  890. for _, client := range interfaceClients {
  891. c := client.(map[string]any)
  892. c_id := c[client_key].(string)
  893. if c_id == clientId {
  894. clientFound = true
  895. email, _ = c["email"].(string)
  896. needApiDel, _ = c["enable"].(bool)
  897. } else {
  898. newClients = append(newClients, client)
  899. }
  900. }
  901. if !clientFound {
  902. return false, common.NewError("Client Not Found In Inbound For ID:", clientId)
  903. }
  904. if len(newClients) == 0 {
  905. return false, common.NewError("no client remained in Inbound")
  906. }
  907. settings["clients"] = newClients
  908. newSettings, err := json.MarshalIndent(settings, "", " ")
  909. if err != nil {
  910. return false, err
  911. }
  912. oldInbound.Settings = string(newSettings)
  913. db := database.GetDB()
  914. err = s.DelClientIPs(db, email)
  915. if err != nil {
  916. logger.Error("Error in delete client IPs")
  917. return false, err
  918. }
  919. needRestart := false
  920. if len(email) > 0 {
  921. notDepleted := true
  922. err = db.Model(xray.ClientTraffic{}).Select("enable").Where("email = ?", email).First(&notDepleted).Error
  923. if err != nil {
  924. logger.Error("Get stats error")
  925. return false, err
  926. }
  927. err = s.DelClientStat(db, email)
  928. if err != nil {
  929. logger.Error("Delete stats Data Error")
  930. return false, err
  931. }
  932. if needApiDel && notDepleted {
  933. s.xrayApi.Init(p.GetAPIPort())
  934. err1 := s.xrayApi.RemoveUser(oldInbound.Tag, email)
  935. if err1 == nil {
  936. logger.Debug("Client deleted by api:", email)
  937. needRestart = false
  938. } else {
  939. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  940. logger.Debug("User is already deleted. Nothing to do more...")
  941. } else {
  942. logger.Debug("Error in deleting client by api:", err1)
  943. needRestart = true
  944. }
  945. }
  946. s.xrayApi.Close()
  947. }
  948. }
  949. return needRestart, db.Save(oldInbound).Error
  950. }
  951. func (s *InboundService) UpdateInboundClient(data *model.Inbound, clientId string) (bool, error) {
  952. // TODO: check if TrafficReset field is updating
  953. clients, err := s.GetClients(data)
  954. if err != nil {
  955. return false, err
  956. }
  957. var settings map[string]any
  958. err = json.Unmarshal([]byte(data.Settings), &settings)
  959. if err != nil {
  960. return false, err
  961. }
  962. interfaceClients := settings["clients"].([]any)
  963. oldInbound, err := s.GetInbound(data.Id)
  964. if err != nil {
  965. return false, err
  966. }
  967. oldClients, err := s.GetClients(oldInbound)
  968. if err != nil {
  969. return false, err
  970. }
  971. oldEmail := ""
  972. newClientId := ""
  973. clientIndex := -1
  974. for index, oldClient := range oldClients {
  975. oldClientId := ""
  976. switch oldInbound.Protocol {
  977. case "trojan":
  978. oldClientId = oldClient.Password
  979. newClientId = clients[0].Password
  980. case "shadowsocks":
  981. oldClientId = oldClient.Email
  982. newClientId = clients[0].Email
  983. case "hysteria", "hysteria2":
  984. oldClientId = oldClient.Auth
  985. newClientId = clients[0].Auth
  986. default:
  987. oldClientId = oldClient.ID
  988. newClientId = clients[0].ID
  989. }
  990. if clientId == oldClientId {
  991. oldEmail = oldClient.Email
  992. clientIndex = index
  993. break
  994. }
  995. }
  996. // Validate new client ID
  997. if newClientId == "" || clientIndex == -1 {
  998. return false, common.NewError("empty client ID")
  999. }
  1000. if len(clients[0].Email) > 0 && clients[0].Email != oldEmail {
  1001. existEmail, err := s.checkEmailsExistForClients(clients)
  1002. if err != nil {
  1003. return false, err
  1004. }
  1005. if existEmail != "" {
  1006. return false, common.NewError("Duplicate email:", existEmail)
  1007. }
  1008. }
  1009. var oldSettings map[string]any
  1010. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1011. if err != nil {
  1012. return false, err
  1013. }
  1014. settingsClients := oldSettings["clients"].([]any)
  1015. // Preserve created_at and set updated_at for the replacing client
  1016. var preservedCreated any
  1017. if clientIndex >= 0 && clientIndex < len(settingsClients) {
  1018. if oldMap, ok := settingsClients[clientIndex].(map[string]any); ok {
  1019. if v, ok2 := oldMap["created_at"]; ok2 {
  1020. preservedCreated = v
  1021. }
  1022. }
  1023. }
  1024. if len(interfaceClients) > 0 {
  1025. if newMap, ok := interfaceClients[0].(map[string]any); ok {
  1026. if preservedCreated == nil {
  1027. preservedCreated = time.Now().Unix() * 1000
  1028. }
  1029. newMap["created_at"] = preservedCreated
  1030. newMap["updated_at"] = time.Now().Unix() * 1000
  1031. interfaceClients[0] = newMap
  1032. }
  1033. }
  1034. settingsClients[clientIndex] = interfaceClients[0]
  1035. oldSettings["clients"] = settingsClients
  1036. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  1037. if err != nil {
  1038. return false, err
  1039. }
  1040. oldInbound.Settings = string(newSettings)
  1041. db := database.GetDB()
  1042. tx := db.Begin()
  1043. defer func() {
  1044. if err != nil {
  1045. tx.Rollback()
  1046. } else {
  1047. tx.Commit()
  1048. }
  1049. }()
  1050. if len(clients[0].Email) > 0 {
  1051. if len(oldEmail) > 0 {
  1052. err = s.UpdateClientStat(tx, oldEmail, &clients[0])
  1053. if err != nil {
  1054. return false, err
  1055. }
  1056. err = s.UpdateClientIPs(tx, oldEmail, clients[0].Email)
  1057. if err != nil {
  1058. return false, err
  1059. }
  1060. } else {
  1061. s.AddClientStat(tx, data.Id, &clients[0])
  1062. }
  1063. } else {
  1064. err = s.DelClientStat(tx, oldEmail)
  1065. if err != nil {
  1066. return false, err
  1067. }
  1068. err = s.DelClientIPs(tx, oldEmail)
  1069. if err != nil {
  1070. return false, err
  1071. }
  1072. }
  1073. needRestart := false
  1074. if len(oldEmail) > 0 {
  1075. s.xrayApi.Init(p.GetAPIPort())
  1076. if oldClients[clientIndex].Enable {
  1077. err1 := s.xrayApi.RemoveUser(oldInbound.Tag, oldEmail)
  1078. if err1 == nil {
  1079. logger.Debug("Old client deleted by api:", oldEmail)
  1080. } else {
  1081. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", oldEmail)) {
  1082. logger.Debug("User is already deleted. Nothing to do more...")
  1083. } else {
  1084. logger.Debug("Error in deleting client by api:", err1)
  1085. needRestart = true
  1086. }
  1087. }
  1088. }
  1089. if clients[0].Enable {
  1090. cipher := ""
  1091. if oldInbound.Protocol == "shadowsocks" {
  1092. cipher = oldSettings["method"].(string)
  1093. }
  1094. err1 := s.xrayApi.AddUser(string(oldInbound.Protocol), oldInbound.Tag, map[string]any{
  1095. "email": clients[0].Email,
  1096. "id": clients[0].ID,
  1097. "security": clients[0].Security,
  1098. "flow": clients[0].Flow,
  1099. "auth": clients[0].Auth,
  1100. "password": clients[0].Password,
  1101. "cipher": cipher,
  1102. })
  1103. if err1 == nil {
  1104. logger.Debug("Client edited by api:", clients[0].Email)
  1105. } else {
  1106. logger.Debug("Error in adding client by api:", err1)
  1107. needRestart = true
  1108. }
  1109. }
  1110. s.xrayApi.Close()
  1111. } else {
  1112. logger.Debug("Client old email not found")
  1113. needRestart = true
  1114. }
  1115. return needRestart, tx.Save(oldInbound).Error
  1116. }
  1117. func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (error, bool) {
  1118. var err error
  1119. db := database.GetDB()
  1120. tx := db.Begin()
  1121. defer func() {
  1122. if err != nil {
  1123. tx.Rollback()
  1124. } else {
  1125. tx.Commit()
  1126. }
  1127. }()
  1128. err = s.addInboundTraffic(tx, inboundTraffics)
  1129. if err != nil {
  1130. return err, false
  1131. }
  1132. err = s.addClientTraffic(tx, clientTraffics)
  1133. if err != nil {
  1134. return err, false
  1135. }
  1136. needRestart0, count, err := s.autoRenewClients(tx)
  1137. if err != nil {
  1138. logger.Warning("Error in renew clients:", err)
  1139. } else if count > 0 {
  1140. logger.Debugf("%v clients renewed", count)
  1141. }
  1142. needRestart1, count, err := s.disableInvalidClients(tx)
  1143. if err != nil {
  1144. logger.Warning("Error in disabling invalid clients:", err)
  1145. } else if count > 0 {
  1146. logger.Debugf("%v clients disabled", count)
  1147. }
  1148. needRestart2, count, err := s.disableInvalidInbounds(tx)
  1149. if err != nil {
  1150. logger.Warning("Error in disabling invalid inbounds:", err)
  1151. } else if count > 0 {
  1152. logger.Debugf("%v inbounds disabled", count)
  1153. }
  1154. return nil, (needRestart0 || needRestart1 || needRestart2)
  1155. }
  1156. func (s *InboundService) addInboundTraffic(tx *gorm.DB, traffics []*xray.Traffic) error {
  1157. if len(traffics) == 0 {
  1158. return nil
  1159. }
  1160. var err error
  1161. for _, traffic := range traffics {
  1162. if traffic.IsInbound {
  1163. err = tx.Model(&model.Inbound{}).Where("tag = ?", traffic.Tag).
  1164. Updates(map[string]any{
  1165. "up": gorm.Expr("up + ?", traffic.Up),
  1166. "down": gorm.Expr("down + ?", traffic.Down),
  1167. "all_time": gorm.Expr("COALESCE(all_time, 0) + ?", traffic.Up+traffic.Down),
  1168. }).Error
  1169. if err != nil {
  1170. return err
  1171. }
  1172. }
  1173. }
  1174. return nil
  1175. }
  1176. func (s *InboundService) addClientTraffic(tx *gorm.DB, traffics []*xray.ClientTraffic) (err error) {
  1177. if len(traffics) == 0 {
  1178. // Empty onlineUsers
  1179. if p != nil {
  1180. p.SetOnlineClients(make([]string, 0))
  1181. }
  1182. return nil
  1183. }
  1184. onlineClients := make([]string, 0)
  1185. emails := make([]string, 0, len(traffics))
  1186. for _, traffic := range traffics {
  1187. emails = append(emails, traffic.Email)
  1188. }
  1189. dbClientTraffics := make([]*xray.ClientTraffic, 0, len(traffics))
  1190. err = tx.Model(xray.ClientTraffic{}).Where("email IN (?)", emails).Find(&dbClientTraffics).Error
  1191. if err != nil {
  1192. return err
  1193. }
  1194. // Avoid empty slice error
  1195. if len(dbClientTraffics) == 0 {
  1196. return nil
  1197. }
  1198. dbClientTraffics, err = s.adjustTraffics(tx, dbClientTraffics)
  1199. if err != nil {
  1200. return err
  1201. }
  1202. for dbTraffic_index := range dbClientTraffics {
  1203. for traffic_index := range traffics {
  1204. if dbClientTraffics[dbTraffic_index].Email == traffics[traffic_index].Email {
  1205. dbClientTraffics[dbTraffic_index].Up += traffics[traffic_index].Up
  1206. dbClientTraffics[dbTraffic_index].Down += traffics[traffic_index].Down
  1207. dbClientTraffics[dbTraffic_index].AllTime += (traffics[traffic_index].Up + traffics[traffic_index].Down)
  1208. // Add user in onlineUsers array on traffic
  1209. if traffics[traffic_index].Up+traffics[traffic_index].Down > 0 {
  1210. onlineClients = append(onlineClients, traffics[traffic_index].Email)
  1211. dbClientTraffics[dbTraffic_index].LastOnline = time.Now().UnixMilli()
  1212. }
  1213. break
  1214. }
  1215. }
  1216. }
  1217. // Set onlineUsers
  1218. p.SetOnlineClients(onlineClients)
  1219. err = tx.Save(dbClientTraffics).Error
  1220. if err != nil {
  1221. logger.Warning("AddClientTraffic update data ", err)
  1222. }
  1223. return nil
  1224. }
  1225. func (s *InboundService) adjustTraffics(tx *gorm.DB, dbClientTraffics []*xray.ClientTraffic) ([]*xray.ClientTraffic, error) {
  1226. inboundIds := make([]int, 0, len(dbClientTraffics))
  1227. for _, dbClientTraffic := range dbClientTraffics {
  1228. if dbClientTraffic.ExpiryTime < 0 {
  1229. inboundIds = append(inboundIds, dbClientTraffic.InboundId)
  1230. }
  1231. }
  1232. if len(inboundIds) > 0 {
  1233. var inbounds []*model.Inbound
  1234. err := tx.Model(model.Inbound{}).Where("id IN (?)", inboundIds).Find(&inbounds).Error
  1235. if err != nil {
  1236. return nil, err
  1237. }
  1238. for inbound_index := range inbounds {
  1239. settings := map[string]any{}
  1240. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1241. clients, ok := settings["clients"].([]any)
  1242. if ok {
  1243. var newClients []any
  1244. for client_index := range clients {
  1245. c := clients[client_index].(map[string]any)
  1246. for traffic_index := range dbClientTraffics {
  1247. if dbClientTraffics[traffic_index].ExpiryTime < 0 && c["email"] == dbClientTraffics[traffic_index].Email {
  1248. oldExpiryTime := c["expiryTime"].(float64)
  1249. newExpiryTime := (time.Now().Unix() * 1000) - int64(oldExpiryTime)
  1250. c["expiryTime"] = newExpiryTime
  1251. c["updated_at"] = time.Now().Unix() * 1000
  1252. dbClientTraffics[traffic_index].ExpiryTime = newExpiryTime
  1253. break
  1254. }
  1255. }
  1256. // Backfill created_at and updated_at
  1257. if _, ok := c["created_at"]; !ok {
  1258. c["created_at"] = time.Now().Unix() * 1000
  1259. }
  1260. c["updated_at"] = time.Now().Unix() * 1000
  1261. newClients = append(newClients, any(c))
  1262. }
  1263. settings["clients"] = newClients
  1264. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1265. if err != nil {
  1266. return nil, err
  1267. }
  1268. inbounds[inbound_index].Settings = string(modifiedSettings)
  1269. }
  1270. }
  1271. err = tx.Save(inbounds).Error
  1272. if err != nil {
  1273. logger.Warning("AddClientTraffic update inbounds ", err)
  1274. logger.Error(inbounds)
  1275. }
  1276. }
  1277. return dbClientTraffics, nil
  1278. }
  1279. func (s *InboundService) autoRenewClients(tx *gorm.DB) (bool, int64, error) {
  1280. // check for time expired
  1281. var traffics []*xray.ClientTraffic
  1282. now := time.Now().Unix() * 1000
  1283. var err, err1 error
  1284. err = tx.Model(xray.ClientTraffic{}).Where("reset > 0 and expiry_time > 0 and expiry_time <= ?", now).Find(&traffics).Error
  1285. if err != nil {
  1286. return false, 0, err
  1287. }
  1288. // return if there is no client to renew
  1289. if len(traffics) == 0 {
  1290. return false, 0, nil
  1291. }
  1292. var inbound_ids []int
  1293. var inbounds []*model.Inbound
  1294. needRestart := false
  1295. var clientsToAdd []struct {
  1296. protocol string
  1297. tag string
  1298. client map[string]any
  1299. }
  1300. for _, traffic := range traffics {
  1301. inbound_ids = append(inbound_ids, traffic.InboundId)
  1302. }
  1303. err = tx.Model(model.Inbound{}).Where("id IN ?", inbound_ids).Find(&inbounds).Error
  1304. if err != nil {
  1305. return false, 0, err
  1306. }
  1307. for inbound_index := range inbounds {
  1308. settings := map[string]any{}
  1309. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1310. clients := settings["clients"].([]any)
  1311. for client_index := range clients {
  1312. c := clients[client_index].(map[string]any)
  1313. for traffic_index, traffic := range traffics {
  1314. if traffic.Email == c["email"].(string) {
  1315. newExpiryTime := traffic.ExpiryTime
  1316. for newExpiryTime < now {
  1317. newExpiryTime += (int64(traffic.Reset) * 86400000)
  1318. }
  1319. c["expiryTime"] = newExpiryTime
  1320. traffics[traffic_index].ExpiryTime = newExpiryTime
  1321. traffics[traffic_index].Down = 0
  1322. traffics[traffic_index].Up = 0
  1323. if !traffic.Enable {
  1324. traffics[traffic_index].Enable = true
  1325. clientsToAdd = append(clientsToAdd,
  1326. struct {
  1327. protocol string
  1328. tag string
  1329. client map[string]any
  1330. }{
  1331. protocol: string(inbounds[inbound_index].Protocol),
  1332. tag: inbounds[inbound_index].Tag,
  1333. client: c,
  1334. })
  1335. }
  1336. clients[client_index] = any(c)
  1337. break
  1338. }
  1339. }
  1340. }
  1341. settings["clients"] = clients
  1342. newSettings, err := json.MarshalIndent(settings, "", " ")
  1343. if err != nil {
  1344. return false, 0, err
  1345. }
  1346. inbounds[inbound_index].Settings = string(newSettings)
  1347. }
  1348. err = tx.Save(inbounds).Error
  1349. if err != nil {
  1350. return false, 0, err
  1351. }
  1352. err = tx.Save(traffics).Error
  1353. if err != nil {
  1354. return false, 0, err
  1355. }
  1356. if p != nil {
  1357. err1 = s.xrayApi.Init(p.GetAPIPort())
  1358. if err1 != nil {
  1359. return true, int64(len(traffics)), nil
  1360. }
  1361. for _, clientToAdd := range clientsToAdd {
  1362. err1 = s.xrayApi.AddUser(clientToAdd.protocol, clientToAdd.tag, clientToAdd.client)
  1363. if err1 != nil {
  1364. needRestart = true
  1365. }
  1366. }
  1367. s.xrayApi.Close()
  1368. }
  1369. return needRestart, int64(len(traffics)), nil
  1370. }
  1371. func (s *InboundService) disableInvalidInbounds(tx *gorm.DB) (bool, int64, error) {
  1372. now := time.Now().Unix() * 1000
  1373. needRestart := false
  1374. if p != nil {
  1375. var tags []string
  1376. err := tx.Table("inbounds").
  1377. Select("inbounds.tag").
  1378. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  1379. Scan(&tags).Error
  1380. if err != nil {
  1381. return false, 0, err
  1382. }
  1383. s.xrayApi.Init(p.GetAPIPort())
  1384. for _, tag := range tags {
  1385. err1 := s.xrayApi.DelInbound(tag)
  1386. if err1 == nil {
  1387. logger.Debug("Inbound disabled by api:", tag)
  1388. } else {
  1389. logger.Debug("Error in disabling inbound by api:", err1)
  1390. needRestart = true
  1391. }
  1392. }
  1393. s.xrayApi.Close()
  1394. }
  1395. result := tx.Model(model.Inbound{}).
  1396. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  1397. Update("enable", false)
  1398. err := result.Error
  1399. count := result.RowsAffected
  1400. return needRestart, count, err
  1401. }
  1402. func (s *InboundService) disableInvalidClients(tx *gorm.DB) (bool, int64, error) {
  1403. now := time.Now().Unix() * 1000
  1404. needRestart := false
  1405. if p != nil {
  1406. var results []struct {
  1407. Tag string
  1408. Email string
  1409. }
  1410. err := tx.Table("inbounds").
  1411. Select("inbounds.tag, client_traffics.email").
  1412. Joins("JOIN client_traffics ON inbounds.id = client_traffics.inbound_id").
  1413. 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).
  1414. Scan(&results).Error
  1415. if err != nil {
  1416. return false, 0, err
  1417. }
  1418. s.xrayApi.Init(p.GetAPIPort())
  1419. for _, result := range results {
  1420. err1 := s.xrayApi.RemoveUser(result.Tag, result.Email)
  1421. if err1 == nil {
  1422. logger.Debug("Client disabled by api:", result.Email)
  1423. } else {
  1424. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", result.Email)) {
  1425. logger.Debug("User is already disabled. Nothing to do more...")
  1426. } else {
  1427. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", result.Email)) {
  1428. logger.Debug("User is already disabled. Nothing to do more...")
  1429. } else {
  1430. logger.Debug("Error in disabling client by api:", err1)
  1431. needRestart = true
  1432. }
  1433. }
  1434. }
  1435. }
  1436. s.xrayApi.Close()
  1437. }
  1438. result := tx.Model(xray.ClientTraffic{}).
  1439. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  1440. Update("enable", false)
  1441. err := result.Error
  1442. count := result.RowsAffected
  1443. return needRestart, count, err
  1444. }
  1445. func (s *InboundService) GetInboundTags() (string, error) {
  1446. db := database.GetDB()
  1447. var inboundTags []string
  1448. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  1449. if err != nil && err != gorm.ErrRecordNotFound {
  1450. return "", err
  1451. }
  1452. tags, _ := json.Marshal(inboundTags)
  1453. return string(tags), nil
  1454. }
  1455. func (s *InboundService) MigrationRemoveOrphanedTraffics() {
  1456. db := database.GetDB()
  1457. db.Exec(`
  1458. DELETE FROM client_traffics
  1459. WHERE email NOT IN (
  1460. SELECT JSON_EXTRACT(client.value, '$.email')
  1461. FROM inbounds,
  1462. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  1463. )
  1464. `)
  1465. }
  1466. func (s *InboundService) AddClientStat(tx *gorm.DB, inboundId int, client *model.Client) error {
  1467. clientTraffic := xray.ClientTraffic{}
  1468. clientTraffic.InboundId = inboundId
  1469. clientTraffic.Email = client.Email
  1470. clientTraffic.Total = client.TotalGB
  1471. clientTraffic.ExpiryTime = client.ExpiryTime
  1472. clientTraffic.Enable = client.Enable
  1473. clientTraffic.Up = 0
  1474. clientTraffic.Down = 0
  1475. clientTraffic.Reset = client.Reset
  1476. result := tx.Create(&clientTraffic)
  1477. err := result.Error
  1478. return err
  1479. }
  1480. func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *model.Client) error {
  1481. result := tx.Model(xray.ClientTraffic{}).
  1482. Where("email = ?", email).
  1483. Updates(map[string]any{
  1484. "enable": client.Enable,
  1485. "email": client.Email,
  1486. "total": client.TotalGB,
  1487. "expiry_time": client.ExpiryTime,
  1488. "reset": client.Reset,
  1489. })
  1490. err := result.Error
  1491. return err
  1492. }
  1493. func (s *InboundService) UpdateClientIPs(tx *gorm.DB, oldEmail string, newEmail string) error {
  1494. return tx.Model(model.InboundClientIps{}).Where("client_email = ?", oldEmail).Update("client_email", newEmail).Error
  1495. }
  1496. func (s *InboundService) DelClientStat(tx *gorm.DB, email string) error {
  1497. return tx.Where("email = ?", email).Delete(xray.ClientTraffic{}).Error
  1498. }
  1499. func (s *InboundService) DelClientIPs(tx *gorm.DB, email string) error {
  1500. return tx.Where("client_email = ?", email).Delete(model.InboundClientIps{}).Error
  1501. }
  1502. func (s *InboundService) GetClientInboundByTrafficID(trafficId int) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  1503. db := database.GetDB()
  1504. var traffics []*xray.ClientTraffic
  1505. err = db.Model(xray.ClientTraffic{}).Where("id = ?", trafficId).Find(&traffics).Error
  1506. if err != nil {
  1507. logger.Warningf("Error retrieving ClientTraffic with trafficId %d: %v", trafficId, err)
  1508. return nil, nil, err
  1509. }
  1510. if len(traffics) > 0 {
  1511. inbound, err = s.GetInbound(traffics[0].InboundId)
  1512. return traffics[0], inbound, err
  1513. }
  1514. return nil, nil, nil
  1515. }
  1516. func (s *InboundService) GetClientInboundByEmail(email string) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  1517. db := database.GetDB()
  1518. var traffics []*xray.ClientTraffic
  1519. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error
  1520. if err != nil {
  1521. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  1522. return nil, nil, err
  1523. }
  1524. if len(traffics) > 0 {
  1525. inbound, err = s.GetInbound(traffics[0].InboundId)
  1526. return traffics[0], inbound, err
  1527. }
  1528. return nil, nil, nil
  1529. }
  1530. func (s *InboundService) GetClientByEmail(clientEmail string) (*xray.ClientTraffic, *model.Client, error) {
  1531. traffic, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1532. if err != nil {
  1533. return nil, nil, err
  1534. }
  1535. if inbound == nil {
  1536. return nil, nil, common.NewError("Inbound Not Found For Email:", clientEmail)
  1537. }
  1538. clients, err := s.GetClients(inbound)
  1539. if err != nil {
  1540. return nil, nil, err
  1541. }
  1542. for _, client := range clients {
  1543. if client.Email == clientEmail {
  1544. return traffic, &client, nil
  1545. }
  1546. }
  1547. return nil, nil, common.NewError("Client Not Found In Inbound For Email:", clientEmail)
  1548. }
  1549. func (s *InboundService) SetClientTelegramUserID(trafficId int, tgId int64) (bool, error) {
  1550. traffic, inbound, err := s.GetClientInboundByTrafficID(trafficId)
  1551. if err != nil {
  1552. return false, err
  1553. }
  1554. if inbound == nil {
  1555. return false, common.NewError("Inbound Not Found For Traffic ID:", trafficId)
  1556. }
  1557. clientEmail := traffic.Email
  1558. oldClients, err := s.GetClients(inbound)
  1559. if err != nil {
  1560. return false, err
  1561. }
  1562. clientId := ""
  1563. for _, oldClient := range oldClients {
  1564. if oldClient.Email == clientEmail {
  1565. switch inbound.Protocol {
  1566. case "trojan":
  1567. clientId = oldClient.Password
  1568. case "shadowsocks":
  1569. clientId = oldClient.Email
  1570. default:
  1571. clientId = oldClient.ID
  1572. }
  1573. break
  1574. }
  1575. }
  1576. if len(clientId) == 0 {
  1577. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1578. }
  1579. var settings map[string]any
  1580. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1581. if err != nil {
  1582. return false, err
  1583. }
  1584. clients := settings["clients"].([]any)
  1585. var newClients []any
  1586. for client_index := range clients {
  1587. c := clients[client_index].(map[string]any)
  1588. if c["email"] == clientEmail {
  1589. c["tgId"] = tgId
  1590. c["updated_at"] = time.Now().Unix() * 1000
  1591. newClients = append(newClients, any(c))
  1592. }
  1593. }
  1594. settings["clients"] = newClients
  1595. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1596. if err != nil {
  1597. return false, err
  1598. }
  1599. inbound.Settings = string(modifiedSettings)
  1600. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1601. return needRestart, err
  1602. }
  1603. func (s *InboundService) checkIsEnabledByEmail(clientEmail string) (bool, error) {
  1604. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1605. if err != nil {
  1606. return false, err
  1607. }
  1608. if inbound == nil {
  1609. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1610. }
  1611. clients, err := s.GetClients(inbound)
  1612. if err != nil {
  1613. return false, err
  1614. }
  1615. isEnable := false
  1616. for _, client := range clients {
  1617. if client.Email == clientEmail {
  1618. isEnable = client.Enable
  1619. break
  1620. }
  1621. }
  1622. return isEnable, err
  1623. }
  1624. func (s *InboundService) ToggleClientEnableByEmail(clientEmail string) (bool, bool, error) {
  1625. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1626. if err != nil {
  1627. return false, false, err
  1628. }
  1629. if inbound == nil {
  1630. return false, false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1631. }
  1632. oldClients, err := s.GetClients(inbound)
  1633. if err != nil {
  1634. return false, false, err
  1635. }
  1636. clientId := ""
  1637. clientOldEnabled := false
  1638. for _, oldClient := range oldClients {
  1639. if oldClient.Email == clientEmail {
  1640. switch inbound.Protocol {
  1641. case "trojan":
  1642. clientId = oldClient.Password
  1643. case "shadowsocks":
  1644. clientId = oldClient.Email
  1645. default:
  1646. clientId = oldClient.ID
  1647. }
  1648. clientOldEnabled = oldClient.Enable
  1649. break
  1650. }
  1651. }
  1652. if len(clientId) == 0 {
  1653. return false, false, common.NewError("Client Not Found For Email:", clientEmail)
  1654. }
  1655. var settings map[string]any
  1656. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1657. if err != nil {
  1658. return false, false, err
  1659. }
  1660. clients := settings["clients"].([]any)
  1661. var newClients []any
  1662. for client_index := range clients {
  1663. c := clients[client_index].(map[string]any)
  1664. if c["email"] == clientEmail {
  1665. c["enable"] = !clientOldEnabled
  1666. c["updated_at"] = time.Now().Unix() * 1000
  1667. newClients = append(newClients, any(c))
  1668. }
  1669. }
  1670. settings["clients"] = newClients
  1671. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1672. if err != nil {
  1673. return false, false, err
  1674. }
  1675. inbound.Settings = string(modifiedSettings)
  1676. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1677. if err != nil {
  1678. return false, needRestart, err
  1679. }
  1680. return !clientOldEnabled, needRestart, nil
  1681. }
  1682. // SetClientEnableByEmail sets client enable state to desired value; returns (changed, needRestart, error)
  1683. func (s *InboundService) SetClientEnableByEmail(clientEmail string, enable bool) (bool, bool, error) {
  1684. current, err := s.checkIsEnabledByEmail(clientEmail)
  1685. if err != nil {
  1686. return false, false, err
  1687. }
  1688. if current == enable {
  1689. return false, false, nil
  1690. }
  1691. newEnabled, needRestart, err := s.ToggleClientEnableByEmail(clientEmail)
  1692. if err != nil {
  1693. return false, needRestart, err
  1694. }
  1695. return newEnabled == enable, needRestart, nil
  1696. }
  1697. func (s *InboundService) ResetClientIpLimitByEmail(clientEmail string, count int) (bool, error) {
  1698. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1699. if err != nil {
  1700. return false, err
  1701. }
  1702. if inbound == nil {
  1703. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1704. }
  1705. oldClients, err := s.GetClients(inbound)
  1706. if err != nil {
  1707. return false, err
  1708. }
  1709. clientId := ""
  1710. for _, oldClient := range oldClients {
  1711. if oldClient.Email == clientEmail {
  1712. switch inbound.Protocol {
  1713. case "trojan":
  1714. clientId = oldClient.Password
  1715. case "shadowsocks":
  1716. clientId = oldClient.Email
  1717. default:
  1718. clientId = oldClient.ID
  1719. }
  1720. break
  1721. }
  1722. }
  1723. if len(clientId) == 0 {
  1724. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1725. }
  1726. var settings map[string]any
  1727. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1728. if err != nil {
  1729. return false, err
  1730. }
  1731. clients := settings["clients"].([]any)
  1732. var newClients []any
  1733. for client_index := range clients {
  1734. c := clients[client_index].(map[string]any)
  1735. if c["email"] == clientEmail {
  1736. c["limitIp"] = count
  1737. c["updated_at"] = time.Now().Unix() * 1000
  1738. newClients = append(newClients, any(c))
  1739. }
  1740. }
  1741. settings["clients"] = newClients
  1742. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1743. if err != nil {
  1744. return false, err
  1745. }
  1746. inbound.Settings = string(modifiedSettings)
  1747. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1748. return needRestart, err
  1749. }
  1750. func (s *InboundService) ResetClientExpiryTimeByEmail(clientEmail string, expiry_time int64) (bool, error) {
  1751. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1752. if err != nil {
  1753. return false, err
  1754. }
  1755. if inbound == nil {
  1756. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1757. }
  1758. oldClients, err := s.GetClients(inbound)
  1759. if err != nil {
  1760. return false, err
  1761. }
  1762. clientId := ""
  1763. for _, oldClient := range oldClients {
  1764. if oldClient.Email == clientEmail {
  1765. switch inbound.Protocol {
  1766. case "trojan":
  1767. clientId = oldClient.Password
  1768. case "shadowsocks":
  1769. clientId = oldClient.Email
  1770. default:
  1771. clientId = oldClient.ID
  1772. }
  1773. break
  1774. }
  1775. }
  1776. if len(clientId) == 0 {
  1777. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1778. }
  1779. var settings map[string]any
  1780. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1781. if err != nil {
  1782. return false, err
  1783. }
  1784. clients := settings["clients"].([]any)
  1785. var newClients []any
  1786. for client_index := range clients {
  1787. c := clients[client_index].(map[string]any)
  1788. if c["email"] == clientEmail {
  1789. c["expiryTime"] = expiry_time
  1790. c["updated_at"] = time.Now().Unix() * 1000
  1791. newClients = append(newClients, any(c))
  1792. }
  1793. }
  1794. settings["clients"] = newClients
  1795. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1796. if err != nil {
  1797. return false, err
  1798. }
  1799. inbound.Settings = string(modifiedSettings)
  1800. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1801. return needRestart, err
  1802. }
  1803. func (s *InboundService) ResetClientTrafficLimitByEmail(clientEmail string, totalGB int) (bool, error) {
  1804. if totalGB < 0 {
  1805. return false, common.NewError("totalGB must be >= 0")
  1806. }
  1807. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1808. if err != nil {
  1809. return false, err
  1810. }
  1811. if inbound == nil {
  1812. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1813. }
  1814. oldClients, err := s.GetClients(inbound)
  1815. if err != nil {
  1816. return false, err
  1817. }
  1818. clientId := ""
  1819. for _, oldClient := range oldClients {
  1820. if oldClient.Email == clientEmail {
  1821. switch inbound.Protocol {
  1822. case "trojan":
  1823. clientId = oldClient.Password
  1824. case "shadowsocks":
  1825. clientId = oldClient.Email
  1826. default:
  1827. clientId = oldClient.ID
  1828. }
  1829. break
  1830. }
  1831. }
  1832. if len(clientId) == 0 {
  1833. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1834. }
  1835. var settings map[string]any
  1836. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1837. if err != nil {
  1838. return false, err
  1839. }
  1840. clients := settings["clients"].([]any)
  1841. var newClients []any
  1842. for client_index := range clients {
  1843. c := clients[client_index].(map[string]any)
  1844. if c["email"] == clientEmail {
  1845. c["totalGB"] = totalGB * 1024 * 1024 * 1024
  1846. c["updated_at"] = time.Now().Unix() * 1000
  1847. newClients = append(newClients, any(c))
  1848. }
  1849. }
  1850. settings["clients"] = newClients
  1851. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1852. if err != nil {
  1853. return false, err
  1854. }
  1855. inbound.Settings = string(modifiedSettings)
  1856. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1857. return needRestart, err
  1858. }
  1859. func (s *InboundService) ResetClientTrafficByEmail(clientEmail string) error {
  1860. db := database.GetDB()
  1861. // Reset traffic stats in ClientTraffic table
  1862. result := db.Model(xray.ClientTraffic{}).
  1863. Where("email = ?", clientEmail).
  1864. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  1865. err := result.Error
  1866. if err != nil {
  1867. return err
  1868. }
  1869. return nil
  1870. }
  1871. func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (bool, error) {
  1872. needRestart := false
  1873. traffic, err := s.GetClientTrafficByEmail(clientEmail)
  1874. if err != nil {
  1875. return false, err
  1876. }
  1877. if !traffic.Enable {
  1878. inbound, err := s.GetInbound(id)
  1879. if err != nil {
  1880. return false, err
  1881. }
  1882. clients, err := s.GetClients(inbound)
  1883. if err != nil {
  1884. return false, err
  1885. }
  1886. for _, client := range clients {
  1887. if client.Email == clientEmail && client.Enable {
  1888. s.xrayApi.Init(p.GetAPIPort())
  1889. cipher := ""
  1890. if string(inbound.Protocol) == "shadowsocks" {
  1891. var oldSettings map[string]any
  1892. err = json.Unmarshal([]byte(inbound.Settings), &oldSettings)
  1893. if err != nil {
  1894. return false, err
  1895. }
  1896. cipher = oldSettings["method"].(string)
  1897. }
  1898. err1 := s.xrayApi.AddUser(string(inbound.Protocol), inbound.Tag, map[string]any{
  1899. "email": client.Email,
  1900. "id": client.ID,
  1901. "auth": client.Auth,
  1902. "security": client.Security,
  1903. "flow": client.Flow,
  1904. "password": client.Password,
  1905. "cipher": cipher,
  1906. })
  1907. if err1 == nil {
  1908. logger.Debug("Client enabled due to reset traffic:", clientEmail)
  1909. } else {
  1910. logger.Debug("Error in enabling client by api:", err1)
  1911. needRestart = true
  1912. }
  1913. s.xrayApi.Close()
  1914. break
  1915. }
  1916. }
  1917. }
  1918. traffic.Up = 0
  1919. traffic.Down = 0
  1920. traffic.Enable = true
  1921. db := database.GetDB()
  1922. err = db.Save(traffic).Error
  1923. if err != nil {
  1924. return false, err
  1925. }
  1926. return needRestart, nil
  1927. }
  1928. func (s *InboundService) ResetAllClientTraffics(id int) error {
  1929. db := database.GetDB()
  1930. now := time.Now().Unix() * 1000
  1931. return db.Transaction(func(tx *gorm.DB) error {
  1932. whereText := "inbound_id "
  1933. if id == -1 {
  1934. whereText += " > ?"
  1935. } else {
  1936. whereText += " = ?"
  1937. }
  1938. // Reset client traffics
  1939. result := tx.Model(xray.ClientTraffic{}).
  1940. Where(whereText, id).
  1941. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  1942. if result.Error != nil {
  1943. return result.Error
  1944. }
  1945. // Update lastTrafficResetTime for the inbound(s)
  1946. inboundWhereText := "id "
  1947. if id == -1 {
  1948. inboundWhereText += " > ?"
  1949. } else {
  1950. inboundWhereText += " = ?"
  1951. }
  1952. result = tx.Model(model.Inbound{}).
  1953. Where(inboundWhereText, id).
  1954. Update("last_traffic_reset_time", now)
  1955. return result.Error
  1956. })
  1957. }
  1958. func (s *InboundService) ResetAllTraffics() error {
  1959. db := database.GetDB()
  1960. result := db.Model(model.Inbound{}).
  1961. Where("user_id > ?", 0).
  1962. Updates(map[string]any{"up": 0, "down": 0})
  1963. err := result.Error
  1964. return err
  1965. }
  1966. func (s *InboundService) ResetInboundTraffic(id int) error {
  1967. db := database.GetDB()
  1968. result := db.Model(model.Inbound{}).
  1969. Where("id = ?", id).
  1970. Updates(map[string]any{"up": 0, "down": 0})
  1971. return result.Error
  1972. }
  1973. func (s *InboundService) DelDepletedClients(id int) (err error) {
  1974. db := database.GetDB()
  1975. tx := db.Begin()
  1976. defer func() {
  1977. if err == nil {
  1978. tx.Commit()
  1979. } else {
  1980. tx.Rollback()
  1981. }
  1982. }()
  1983. whereText := "reset = 0 and inbound_id "
  1984. if id < 0 {
  1985. whereText += "> ?"
  1986. } else {
  1987. whereText += "= ?"
  1988. }
  1989. // Only consider truly depleted clients: expired OR traffic exhausted
  1990. now := time.Now().Unix() * 1000
  1991. depletedClients := []xray.ClientTraffic{}
  1992. err = db.Model(xray.ClientTraffic{}).
  1993. Where(whereText+" and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))", id, now).
  1994. Select("inbound_id, GROUP_CONCAT(email) as email").
  1995. Group("inbound_id").
  1996. Find(&depletedClients).Error
  1997. if err != nil {
  1998. return err
  1999. }
  2000. for _, depletedClient := range depletedClients {
  2001. emails := strings.Split(depletedClient.Email, ",")
  2002. oldInbound, err := s.GetInbound(depletedClient.InboundId)
  2003. if err != nil {
  2004. return err
  2005. }
  2006. var oldSettings map[string]any
  2007. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  2008. if err != nil {
  2009. return err
  2010. }
  2011. oldClients := oldSettings["clients"].([]any)
  2012. var newClients []any
  2013. for _, client := range oldClients {
  2014. deplete := false
  2015. c := client.(map[string]any)
  2016. for _, email := range emails {
  2017. if email == c["email"].(string) {
  2018. deplete = true
  2019. break
  2020. }
  2021. }
  2022. if !deplete {
  2023. newClients = append(newClients, client)
  2024. }
  2025. }
  2026. if len(newClients) > 0 {
  2027. oldSettings["clients"] = newClients
  2028. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  2029. if err != nil {
  2030. return err
  2031. }
  2032. oldInbound.Settings = string(newSettings)
  2033. err = tx.Save(oldInbound).Error
  2034. if err != nil {
  2035. return err
  2036. }
  2037. } else {
  2038. // Delete inbound if no client remains
  2039. s.DelInbound(depletedClient.InboundId)
  2040. }
  2041. }
  2042. // Delete stats only for truly depleted clients
  2043. err = tx.Where(whereText+" and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))", id, now).Delete(xray.ClientTraffic{}).Error
  2044. if err != nil {
  2045. return err
  2046. }
  2047. return nil
  2048. }
  2049. func (s *InboundService) GetClientTrafficTgBot(tgId int64) ([]*xray.ClientTraffic, error) {
  2050. db := database.GetDB()
  2051. var inbounds []*model.Inbound
  2052. // Retrieve inbounds where settings contain the given tgId
  2053. err := db.Model(model.Inbound{}).Where("settings LIKE ?", fmt.Sprintf(`%%"tgId": %d%%`, tgId)).Find(&inbounds).Error
  2054. if err != nil && err != gorm.ErrRecordNotFound {
  2055. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  2056. return nil, err
  2057. }
  2058. var emails []string
  2059. for _, inbound := range inbounds {
  2060. clients, err := s.GetClients(inbound)
  2061. if err != nil {
  2062. logger.Errorf("Error retrieving clients for inbound %d: %v", inbound.Id, err)
  2063. continue
  2064. }
  2065. for _, client := range clients {
  2066. if client.TgID == tgId {
  2067. emails = append(emails, client.Email)
  2068. }
  2069. }
  2070. }
  2071. var traffics []*xray.ClientTraffic
  2072. err = db.Model(xray.ClientTraffic{}).Where("email IN ?", emails).Find(&traffics).Error
  2073. if err != nil {
  2074. if err == gorm.ErrRecordNotFound {
  2075. logger.Warning("No ClientTraffic records found for emails:", emails)
  2076. return nil, nil
  2077. }
  2078. logger.Errorf("Error retrieving ClientTraffic for emails %v: %v", emails, err)
  2079. return nil, err
  2080. }
  2081. // Populate UUID and other client data for each traffic record
  2082. for i := range traffics {
  2083. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  2084. traffics[i].Enable = client.Enable
  2085. traffics[i].UUID = client.ID
  2086. traffics[i].SubId = client.SubID
  2087. }
  2088. }
  2089. return traffics, nil
  2090. }
  2091. func (s *InboundService) GetClientTrafficByEmail(email string) (traffic *xray.ClientTraffic, err error) {
  2092. // Prefer retrieving along with client to reflect actual enabled state from inbound settings
  2093. t, client, err := s.GetClientByEmail(email)
  2094. if err != nil {
  2095. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  2096. return nil, err
  2097. }
  2098. if t != nil && client != nil {
  2099. t.UUID = client.ID
  2100. t.SubId = client.SubID
  2101. return t, nil
  2102. }
  2103. return nil, nil
  2104. }
  2105. func (s *InboundService) UpdateClientTrafficByEmail(email string, upload int64, download int64) error {
  2106. db := database.GetDB()
  2107. result := db.Model(xray.ClientTraffic{}).
  2108. Where("email = ?", email).
  2109. Updates(map[string]any{"up": upload, "down": download})
  2110. err := result.Error
  2111. if err != nil {
  2112. logger.Warningf("Error updating ClientTraffic with email %s: %v", email, err)
  2113. return err
  2114. }
  2115. return nil
  2116. }
  2117. func (s *InboundService) GetClientTrafficByID(id string) ([]xray.ClientTraffic, error) {
  2118. db := database.GetDB()
  2119. var traffics []xray.ClientTraffic
  2120. err := db.Model(xray.ClientTraffic{}).Where(`email IN(
  2121. SELECT JSON_EXTRACT(client.value, '$.email') as email
  2122. FROM inbounds,
  2123. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  2124. WHERE
  2125. JSON_EXTRACT(client.value, '$.id') in (?)
  2126. )`, id).Find(&traffics).Error
  2127. if err != nil {
  2128. logger.Debug(err)
  2129. return nil, err
  2130. }
  2131. // Reconcile enable flag with client settings per email to avoid stale DB value
  2132. for i := range traffics {
  2133. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  2134. traffics[i].Enable = client.Enable
  2135. traffics[i].UUID = client.ID
  2136. traffics[i].SubId = client.SubID
  2137. }
  2138. }
  2139. return traffics, err
  2140. }
  2141. func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.ClientTraffic, err error) {
  2142. db := database.GetDB()
  2143. inbound := &model.Inbound{}
  2144. traffic = &xray.ClientTraffic{}
  2145. // Search for inbound settings that contain the query
  2146. err = db.Model(model.Inbound{}).Where("settings LIKE ?", "%\""+query+"\"%").First(inbound).Error
  2147. if err != nil {
  2148. if err == gorm.ErrRecordNotFound {
  2149. logger.Warningf("Inbound settings containing query %s not found: %v", query, err)
  2150. return nil, err
  2151. }
  2152. logger.Errorf("Error searching for inbound settings with query %s: %v", query, err)
  2153. return nil, err
  2154. }
  2155. traffic.InboundId = inbound.Id
  2156. // Unmarshal settings to get clients
  2157. settings := map[string][]model.Client{}
  2158. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  2159. logger.Errorf("Error unmarshalling inbound settings for inbound ID %d: %v", inbound.Id, err)
  2160. return nil, err
  2161. }
  2162. clients := settings["clients"]
  2163. for _, client := range clients {
  2164. if (client.ID == query || client.Password == query) && client.Email != "" {
  2165. traffic.Email = client.Email
  2166. break
  2167. }
  2168. }
  2169. if traffic.Email == "" {
  2170. logger.Warningf("No client found with query %s in inbound ID %d", query, inbound.Id)
  2171. return nil, gorm.ErrRecordNotFound
  2172. }
  2173. // Retrieve ClientTraffic based on the found email
  2174. err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error
  2175. if err != nil {
  2176. if err == gorm.ErrRecordNotFound {
  2177. logger.Warningf("ClientTraffic for email %s not found: %v", traffic.Email, err)
  2178. return nil, err
  2179. }
  2180. logger.Errorf("Error retrieving ClientTraffic for email %s: %v", traffic.Email, err)
  2181. return nil, err
  2182. }
  2183. return traffic, nil
  2184. }
  2185. func (s *InboundService) GetInboundClientIps(clientEmail string) (string, error) {
  2186. db := database.GetDB()
  2187. InboundClientIps := &model.InboundClientIps{}
  2188. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  2189. if err != nil {
  2190. return "", err
  2191. }
  2192. if InboundClientIps.Ips == "" {
  2193. return "", nil
  2194. }
  2195. // Try to parse as new format (with timestamps)
  2196. type IPWithTimestamp struct {
  2197. IP string `json:"ip"`
  2198. Timestamp int64 `json:"timestamp"`
  2199. }
  2200. var ipsWithTime []IPWithTimestamp
  2201. err = json.Unmarshal([]byte(InboundClientIps.Ips), &ipsWithTime)
  2202. // If successfully parsed as new format, return with timestamps
  2203. if err == nil && len(ipsWithTime) > 0 {
  2204. return InboundClientIps.Ips, nil
  2205. }
  2206. // Otherwise, assume it's old format (simple string array)
  2207. // Try to parse as simple array and convert to new format
  2208. var oldIps []string
  2209. err = json.Unmarshal([]byte(InboundClientIps.Ips), &oldIps)
  2210. if err == nil && len(oldIps) > 0 {
  2211. // Convert old format to new format with current timestamp
  2212. newIpsWithTime := make([]IPWithTimestamp, len(oldIps))
  2213. for i, ip := range oldIps {
  2214. newIpsWithTime[i] = IPWithTimestamp{
  2215. IP: ip,
  2216. Timestamp: time.Now().Unix(),
  2217. }
  2218. }
  2219. result, _ := json.Marshal(newIpsWithTime)
  2220. return string(result), nil
  2221. }
  2222. // Return as-is if parsing fails
  2223. return InboundClientIps.Ips, nil
  2224. }
  2225. func (s *InboundService) ClearClientIps(clientEmail string) error {
  2226. db := database.GetDB()
  2227. result := db.Model(model.InboundClientIps{}).
  2228. Where("client_email = ?", clientEmail).
  2229. Update("ips", "")
  2230. err := result.Error
  2231. if err != nil {
  2232. return err
  2233. }
  2234. return nil
  2235. }
  2236. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  2237. db := database.GetDB()
  2238. var inbounds []*model.Inbound
  2239. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  2240. if err != nil && err != gorm.ErrRecordNotFound {
  2241. return nil, err
  2242. }
  2243. return inbounds, nil
  2244. }
  2245. func (s *InboundService) MigrationRequirements() {
  2246. db := database.GetDB()
  2247. tx := db.Begin()
  2248. var err error
  2249. defer func() {
  2250. if err == nil {
  2251. tx.Commit()
  2252. if dbErr := db.Exec(`VACUUM "main"`).Error; dbErr != nil {
  2253. logger.Warningf("VACUUM failed: %v", dbErr)
  2254. }
  2255. } else {
  2256. tx.Rollback()
  2257. }
  2258. }()
  2259. // Calculate and backfill all_time from up+down for inbounds and clients
  2260. err = tx.Exec(`
  2261. UPDATE inbounds
  2262. SET all_time = IFNULL(up, 0) + IFNULL(down, 0)
  2263. WHERE IFNULL(all_time, 0) = 0 AND (IFNULL(up, 0) + IFNULL(down, 0)) > 0
  2264. `).Error
  2265. if err != nil {
  2266. return
  2267. }
  2268. err = tx.Exec(`
  2269. UPDATE client_traffics
  2270. SET all_time = IFNULL(up, 0) + IFNULL(down, 0)
  2271. WHERE IFNULL(all_time, 0) = 0 AND (IFNULL(up, 0) + IFNULL(down, 0)) > 0
  2272. `).Error
  2273. if err != nil {
  2274. return
  2275. }
  2276. // Fix inbounds based problems
  2277. var inbounds []*model.Inbound
  2278. err = tx.Model(model.Inbound{}).Where("protocol IN (?)", []string{"vmess", "vless", "trojan"}).Find(&inbounds).Error
  2279. if err != nil && err != gorm.ErrRecordNotFound {
  2280. return
  2281. }
  2282. for inbound_index := range inbounds {
  2283. settings := map[string]any{}
  2284. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  2285. clients, ok := settings["clients"].([]any)
  2286. if ok {
  2287. // Fix Client configuration problems
  2288. var newClients []any
  2289. for client_index := range clients {
  2290. c := clients[client_index].(map[string]any)
  2291. // Add email='' if it is not exists
  2292. if _, ok := c["email"]; !ok {
  2293. c["email"] = ""
  2294. }
  2295. // Convert string tgId to int64
  2296. if _, ok := c["tgId"]; ok {
  2297. var tgId any = c["tgId"]
  2298. if tgIdStr, ok2 := tgId.(string); ok2 {
  2299. tgIdInt64, err := strconv.ParseInt(strings.ReplaceAll(tgIdStr, " ", ""), 10, 64)
  2300. if err == nil {
  2301. c["tgId"] = tgIdInt64
  2302. }
  2303. }
  2304. }
  2305. // Remove "flow": "xtls-rprx-direct"
  2306. if _, ok := c["flow"]; ok {
  2307. if c["flow"] == "xtls-rprx-direct" {
  2308. c["flow"] = ""
  2309. }
  2310. }
  2311. // Backfill created_at and updated_at
  2312. if _, ok := c["created_at"]; !ok {
  2313. c["created_at"] = time.Now().Unix() * 1000
  2314. }
  2315. c["updated_at"] = time.Now().Unix() * 1000
  2316. newClients = append(newClients, any(c))
  2317. }
  2318. settings["clients"] = newClients
  2319. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2320. if err != nil {
  2321. return
  2322. }
  2323. inbounds[inbound_index].Settings = string(modifiedSettings)
  2324. }
  2325. // Add client traffic row for all clients which has email
  2326. modelClients, err := s.GetClients(inbounds[inbound_index])
  2327. if err != nil {
  2328. return
  2329. }
  2330. for _, modelClient := range modelClients {
  2331. if len(modelClient.Email) > 0 {
  2332. var count int64
  2333. tx.Model(xray.ClientTraffic{}).Where("email = ?", modelClient.Email).Count(&count)
  2334. if count == 0 {
  2335. s.AddClientStat(tx, inbounds[inbound_index].Id, &modelClient)
  2336. }
  2337. }
  2338. }
  2339. }
  2340. tx.Save(inbounds)
  2341. // Remove orphaned traffics
  2342. tx.Where("inbound_id = 0").Delete(xray.ClientTraffic{})
  2343. // Migrate old MultiDomain to External Proxy
  2344. var externalProxy []struct {
  2345. Id int
  2346. Port int
  2347. StreamSettings []byte
  2348. }
  2349. err = tx.Raw(`select id, port, stream_settings
  2350. from inbounds
  2351. WHERE protocol in ('vmess','vless','trojan')
  2352. AND json_extract(stream_settings, '$.security') = 'tls'
  2353. AND json_extract(stream_settings, '$.tlsSettings.settings.domains') IS NOT NULL`).Scan(&externalProxy).Error
  2354. if err != nil || len(externalProxy) == 0 {
  2355. return
  2356. }
  2357. for _, ep := range externalProxy {
  2358. var reverses any
  2359. var stream map[string]any
  2360. json.Unmarshal(ep.StreamSettings, &stream)
  2361. if tlsSettings, ok := stream["tlsSettings"].(map[string]any); ok {
  2362. if settings, ok := tlsSettings["settings"].(map[string]any); ok {
  2363. if domains, ok := settings["domains"].([]any); ok {
  2364. for _, domain := range domains {
  2365. if domainMap, ok := domain.(map[string]any); ok {
  2366. domainMap["forceTls"] = "same"
  2367. domainMap["port"] = ep.Port
  2368. domainMap["dest"] = domainMap["domain"].(string)
  2369. delete(domainMap, "domain")
  2370. }
  2371. }
  2372. }
  2373. reverses = settings["domains"]
  2374. delete(settings, "domains")
  2375. }
  2376. }
  2377. stream["externalProxy"] = reverses
  2378. newStream, _ := json.MarshalIndent(stream, " ", " ")
  2379. tx.Model(model.Inbound{}).Where("id = ?", ep.Id).Update("stream_settings", newStream)
  2380. }
  2381. err = tx.Raw(`UPDATE inbounds
  2382. SET tag = REPLACE(tag, '0.0.0.0:', '')
  2383. WHERE INSTR(tag, '0.0.0.0:') > 0;`).Error
  2384. if err != nil {
  2385. return
  2386. }
  2387. }
  2388. func (s *InboundService) MigrateDB() {
  2389. s.MigrationRequirements()
  2390. s.MigrationRemoveOrphanedTraffics()
  2391. }
  2392. func (s *InboundService) GetOnlineClients() []string {
  2393. return p.GetOnlineClients()
  2394. }
  2395. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  2396. db := database.GetDB()
  2397. var rows []xray.ClientTraffic
  2398. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  2399. if err != nil && err != gorm.ErrRecordNotFound {
  2400. return nil, err
  2401. }
  2402. result := make(map[string]int64, len(rows))
  2403. for _, r := range rows {
  2404. result[r.Email] = r.LastOnline
  2405. }
  2406. return result, nil
  2407. }
  2408. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  2409. db := database.GetDB()
  2410. // Step 1: Get ClientTraffic records for emails in the input list
  2411. var clients []xray.ClientTraffic
  2412. err := db.Where("email IN ?", emails).Find(&clients).Error
  2413. if err != nil && err != gorm.ErrRecordNotFound {
  2414. return nil, nil, err
  2415. }
  2416. // Step 2: Sort clients by (Up + Down) descending
  2417. sort.Slice(clients, func(i, j int) bool {
  2418. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  2419. })
  2420. // Step 3: Extract sorted valid emails and track found ones
  2421. validEmails := make([]string, 0, len(clients))
  2422. found := make(map[string]bool)
  2423. for _, client := range clients {
  2424. validEmails = append(validEmails, client.Email)
  2425. found[client.Email] = true
  2426. }
  2427. // Step 4: Identify emails that were not found in the database
  2428. extraEmails := make([]string, 0)
  2429. for _, email := range emails {
  2430. if !found[email] {
  2431. extraEmails = append(extraEmails, email)
  2432. }
  2433. }
  2434. return validEmails, extraEmails, nil
  2435. }
  2436. func (s *InboundService) DelInboundClientByEmail(inboundId int, email string) (bool, error) {
  2437. oldInbound, err := s.GetInbound(inboundId)
  2438. if err != nil {
  2439. logger.Error("Load Old Data Error")
  2440. return false, err
  2441. }
  2442. var settings map[string]any
  2443. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  2444. return false, err
  2445. }
  2446. interfaceClients, ok := settings["clients"].([]any)
  2447. if !ok {
  2448. return false, common.NewError("invalid clients format in inbound settings")
  2449. }
  2450. var newClients []any
  2451. needApiDel := false
  2452. found := false
  2453. for _, client := range interfaceClients {
  2454. c, ok := client.(map[string]any)
  2455. if !ok {
  2456. continue
  2457. }
  2458. if cEmail, ok := c["email"].(string); ok && cEmail == email {
  2459. // matched client, drop it
  2460. found = true
  2461. needApiDel, _ = c["enable"].(bool)
  2462. } else {
  2463. newClients = append(newClients, client)
  2464. }
  2465. }
  2466. if !found {
  2467. return false, common.NewError(fmt.Sprintf("client with email %s not found", email))
  2468. }
  2469. if len(newClients) == 0 {
  2470. return false, common.NewError("no client remained in Inbound")
  2471. }
  2472. settings["clients"] = newClients
  2473. newSettings, err := json.MarshalIndent(settings, "", " ")
  2474. if err != nil {
  2475. return false, err
  2476. }
  2477. oldInbound.Settings = string(newSettings)
  2478. db := database.GetDB()
  2479. // remove IP bindings
  2480. if err := s.DelClientIPs(db, email); err != nil {
  2481. logger.Error("Error in delete client IPs")
  2482. return false, err
  2483. }
  2484. needRestart := false
  2485. // remove stats too
  2486. if len(email) > 0 {
  2487. traffic, err := s.GetClientTrafficByEmail(email)
  2488. if err != nil {
  2489. return false, err
  2490. }
  2491. if traffic != nil {
  2492. if err := s.DelClientStat(db, email); err != nil {
  2493. logger.Error("Delete stats Data Error")
  2494. return false, err
  2495. }
  2496. }
  2497. if needApiDel {
  2498. s.xrayApi.Init(p.GetAPIPort())
  2499. if err1 := s.xrayApi.RemoveUser(oldInbound.Tag, email); err1 == nil {
  2500. logger.Debug("Client deleted by api:", email)
  2501. needRestart = false
  2502. } else {
  2503. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  2504. logger.Debug("User is already deleted. Nothing to do more...")
  2505. } else {
  2506. logger.Debug("Error in deleting client by api:", err1)
  2507. needRestart = true
  2508. }
  2509. }
  2510. s.xrayApi.Close()
  2511. }
  2512. }
  2513. return needRestart, db.Save(oldInbound).Error
  2514. }