inbound.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. package controller
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net"
  6. "strconv"
  7. "strings"
  8. "time"
  9. "github.com/mhsanaei/3x-ui/v3/database/model"
  10. "github.com/mhsanaei/3x-ui/v3/web/service"
  11. "github.com/mhsanaei/3x-ui/v3/web/session"
  12. "github.com/mhsanaei/3x-ui/v3/web/websocket"
  13. "github.com/gin-gonic/gin"
  14. )
  15. // InboundController handles HTTP requests related to Xray inbounds management.
  16. type InboundController struct {
  17. inboundService service.InboundService
  18. xrayService service.XrayService
  19. }
  20. // NewInboundController creates a new InboundController and sets up its routes.
  21. func NewInboundController(g *gin.RouterGroup) *InboundController {
  22. a := &InboundController{}
  23. a.initRouter(g)
  24. return a
  25. }
  26. // broadcastInboundsUpdateClientLimit is the threshold past which we skip the
  27. // full-list push over WebSocket and signal the frontend to re-fetch via REST.
  28. // Mirrors the same heuristic used by the periodic traffic job.
  29. const broadcastInboundsUpdateClientLimit = 5000
  30. // broadcastInboundsUpdate fetches and broadcasts the inbound list for userId.
  31. // At scale (10k+ clients) the marshaled JSON exceeds the WS payload ceiling,
  32. // so we send an invalidate signal instead — frontend re-fetches via REST.
  33. // Skipped entirely when no WebSocket clients are connected.
  34. func (a *InboundController) broadcastInboundsUpdate(userId int) {
  35. if !websocket.HasClients() {
  36. return
  37. }
  38. inbounds, err := a.inboundService.GetInbounds(userId)
  39. if err != nil {
  40. return
  41. }
  42. totalClients := 0
  43. for _, ib := range inbounds {
  44. totalClients += len(ib.ClientStats)
  45. }
  46. if totalClients > broadcastInboundsUpdateClientLimit {
  47. websocket.BroadcastInvalidate(websocket.MessageTypeInbounds)
  48. return
  49. }
  50. websocket.BroadcastInbounds(inbounds)
  51. }
  52. // initRouter initializes the routes for inbound-related operations.
  53. func (a *InboundController) initRouter(g *gin.RouterGroup) {
  54. g.GET("/list", a.getInbounds)
  55. g.GET("/get/:id", a.getInbound)
  56. g.GET("/getClientTraffics/:email", a.getClientTraffics)
  57. g.GET("/getClientTrafficsById/:id", a.getClientTrafficsById)
  58. g.GET("/getSubLinks/:subId", a.getSubLinks)
  59. g.GET("/getClientLinks/:id/:email", a.getClientLinks)
  60. g.POST("/add", a.addInbound)
  61. g.POST("/del/:id", a.delInbound)
  62. g.POST("/update/:id", a.updateInbound)
  63. g.POST("/setEnable/:id", a.setInboundEnable)
  64. g.POST("/clientIps/:email", a.getClientIps)
  65. g.POST("/clearClientIps/:email", a.clearClientIps)
  66. g.POST("/addClient", a.addInboundClient)
  67. g.POST("/:id/copyClients", a.copyInboundClients)
  68. g.POST("/:id/delClient/:clientId", a.delInboundClient)
  69. g.POST("/updateClient/:clientId", a.updateInboundClient)
  70. g.POST("/:id/resetTraffic", a.resetInboundTraffic)
  71. g.POST("/:id/resetClientTraffic/:email", a.resetClientTraffic)
  72. g.POST("/resetAllTraffics", a.resetAllTraffics)
  73. g.POST("/resetAllClientTraffics/:id", a.resetAllClientTraffics)
  74. g.POST("/delDepletedClients/:id", a.delDepletedClients)
  75. g.POST("/import", a.importInbound)
  76. g.POST("/onlines", a.onlines)
  77. g.POST("/lastOnline", a.lastOnline)
  78. g.POST("/updateClientTraffic/:email", a.updateClientTraffic)
  79. g.POST("/:id/delClientByEmail/:email", a.delInboundClientByEmail)
  80. }
  81. type CopyInboundClientsRequest struct {
  82. SourceInboundID int `form:"sourceInboundId" json:"sourceInboundId"`
  83. ClientEmails []string `form:"clientEmails" json:"clientEmails"`
  84. Flow string `form:"flow" json:"flow"`
  85. }
  86. // getInbounds retrieves the list of inbounds for the logged-in user.
  87. func (a *InboundController) getInbounds(c *gin.Context) {
  88. user := session.GetLoginUser(c)
  89. inbounds, err := a.inboundService.GetInbounds(user.Id)
  90. if err != nil {
  91. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
  92. return
  93. }
  94. jsonObj(c, inbounds, nil)
  95. }
  96. // getInbound retrieves a specific inbound by its ID.
  97. func (a *InboundController) getInbound(c *gin.Context) {
  98. id, err := strconv.Atoi(c.Param("id"))
  99. if err != nil {
  100. jsonMsg(c, I18nWeb(c, "get"), err)
  101. return
  102. }
  103. inbound, err := a.inboundService.GetInbound(id)
  104. if err != nil {
  105. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
  106. return
  107. }
  108. jsonObj(c, inbound, nil)
  109. }
  110. // getClientTraffics retrieves client traffic information by email.
  111. func (a *InboundController) getClientTraffics(c *gin.Context) {
  112. email := c.Param("email")
  113. clientTraffics, err := a.inboundService.GetClientTrafficByEmail(email)
  114. if err != nil {
  115. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.trafficGetError"), err)
  116. return
  117. }
  118. jsonObj(c, clientTraffics, nil)
  119. }
  120. // getClientTrafficsById retrieves client traffic information by inbound ID.
  121. func (a *InboundController) getClientTrafficsById(c *gin.Context) {
  122. id := c.Param("id")
  123. clientTraffics, err := a.inboundService.GetClientTrafficByID(id)
  124. if err != nil {
  125. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.trafficGetError"), err)
  126. return
  127. }
  128. jsonObj(c, clientTraffics, nil)
  129. }
  130. // addInbound creates a new inbound configuration.
  131. func (a *InboundController) addInbound(c *gin.Context) {
  132. inbound := &model.Inbound{}
  133. err := c.ShouldBind(inbound)
  134. if err != nil {
  135. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundCreateSuccess"), err)
  136. return
  137. }
  138. user := session.GetLoginUser(c)
  139. inbound.UserId = user.Id
  140. // Treat NodeID=0 as "no node" — gin's *int form binding can land on
  141. // 0 when the field is absent or empty, and 0 is never a valid Node
  142. // row id. Without this normalization the runtime layer would try to
  143. // load Node id=0 and surface "record not found".
  144. if inbound.NodeID != nil && *inbound.NodeID == 0 {
  145. inbound.NodeID = nil
  146. }
  147. // When the central panel deploys an inbound to a remote node, it sends
  148. // the Tag pre-computed (so both DBs agree on the identifier). Local
  149. // UI submits don't include a Tag — we compute one from listen+port
  150. // using the original collision-avoiding scheme.
  151. if inbound.Tag == "" {
  152. if inbound.Listen == "" || inbound.Listen == "0.0.0.0" || inbound.Listen == "::" || inbound.Listen == "::0" {
  153. inbound.Tag = fmt.Sprintf("inbound-%v", inbound.Port)
  154. } else {
  155. inbound.Tag = fmt.Sprintf("inbound-%v:%v", inbound.Listen, inbound.Port)
  156. }
  157. }
  158. inbound, needRestart, err := a.inboundService.AddInbound(inbound)
  159. if err != nil {
  160. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  161. return
  162. }
  163. jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundCreateSuccess"), inbound, nil)
  164. if needRestart {
  165. a.xrayService.SetToNeedRestart()
  166. }
  167. a.broadcastInboundsUpdate(user.Id)
  168. }
  169. // delInbound deletes an inbound configuration by its ID.
  170. func (a *InboundController) delInbound(c *gin.Context) {
  171. id, err := strconv.Atoi(c.Param("id"))
  172. if err != nil {
  173. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundDeleteSuccess"), err)
  174. return
  175. }
  176. needRestart, err := a.inboundService.DelInbound(id)
  177. if err != nil {
  178. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  179. return
  180. }
  181. jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundDeleteSuccess"), id, nil)
  182. if needRestart {
  183. a.xrayService.SetToNeedRestart()
  184. }
  185. user := session.GetLoginUser(c)
  186. a.broadcastInboundsUpdate(user.Id)
  187. }
  188. // updateInbound updates an existing inbound configuration.
  189. func (a *InboundController) updateInbound(c *gin.Context) {
  190. id, err := strconv.Atoi(c.Param("id"))
  191. if err != nil {
  192. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  193. return
  194. }
  195. inbound := &model.Inbound{
  196. Id: id,
  197. }
  198. err = c.ShouldBind(inbound)
  199. if err != nil {
  200. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  201. return
  202. }
  203. // Same NodeID=0 → nil normalisation as addInbound. UpdateInbound
  204. // loads the existing row's NodeID from DB anyway (Phase 1 doesn't
  205. // support migrating an inbound between nodes), but normalising here
  206. // keeps the wire shape consistent.
  207. if inbound.NodeID != nil && *inbound.NodeID == 0 {
  208. inbound.NodeID = nil
  209. }
  210. inbound, needRestart, err := a.inboundService.UpdateInbound(inbound)
  211. if err != nil {
  212. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  213. return
  214. }
  215. jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), inbound, nil)
  216. if needRestart {
  217. a.xrayService.SetToNeedRestart()
  218. }
  219. user := session.GetLoginUser(c)
  220. a.broadcastInboundsUpdate(user.Id)
  221. }
  222. // setInboundEnable flips only the enable flag of an inbound. This is a
  223. // dedicated endpoint because the regular update path serialises the entire
  224. // settings JSON (every client) — far too heavy for an interactive switch
  225. // on inbounds with thousands of clients. Frontend optimistically updates
  226. // the UI; we just persist + sync xray + nudge other open admin sessions.
  227. func (a *InboundController) setInboundEnable(c *gin.Context) {
  228. id, err := strconv.Atoi(c.Param("id"))
  229. if err != nil {
  230. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  231. return
  232. }
  233. type form struct {
  234. Enable bool `json:"enable" form:"enable"`
  235. }
  236. var f form
  237. if err := c.ShouldBind(&f); err != nil {
  238. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  239. return
  240. }
  241. needRestart, err := a.inboundService.SetInboundEnable(id, f.Enable)
  242. if err != nil {
  243. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  244. return
  245. }
  246. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), nil)
  247. if needRestart {
  248. a.xrayService.SetToNeedRestart()
  249. }
  250. // Cross-admin sync: lightweight invalidate signal (a few hundred bytes)
  251. // instead of fetching + serialising the whole inbound list. Other open
  252. // sessions re-fetch via REST. The toggling admin's own UI already
  253. // updated optimistically.
  254. websocket.BroadcastInvalidate(websocket.MessageTypeInbounds)
  255. }
  256. // getClientIps retrieves the IP addresses associated with a client by email.
  257. func (a *InboundController) getClientIps(c *gin.Context) {
  258. email := c.Param("email")
  259. ips, err := a.inboundService.GetInboundClientIps(email)
  260. if err != nil || ips == "" {
  261. jsonObj(c, "No IP Record", nil)
  262. return
  263. }
  264. // Prefer returning a normalized string list for consistent UI rendering
  265. type ipWithTimestamp struct {
  266. IP string `json:"ip"`
  267. Timestamp int64 `json:"timestamp"`
  268. }
  269. var ipsWithTime []ipWithTimestamp
  270. if err := json.Unmarshal([]byte(ips), &ipsWithTime); err == nil && len(ipsWithTime) > 0 {
  271. formatted := make([]string, 0, len(ipsWithTime))
  272. for _, item := range ipsWithTime {
  273. if item.IP == "" {
  274. continue
  275. }
  276. if item.Timestamp > 0 {
  277. ts := time.Unix(item.Timestamp, 0).Local().Format("2006-01-02 15:04:05")
  278. formatted = append(formatted, fmt.Sprintf("%s (%s)", item.IP, ts))
  279. continue
  280. }
  281. formatted = append(formatted, item.IP)
  282. }
  283. jsonObj(c, formatted, nil)
  284. return
  285. }
  286. var oldIps []string
  287. if err := json.Unmarshal([]byte(ips), &oldIps); err == nil && len(oldIps) > 0 {
  288. jsonObj(c, oldIps, nil)
  289. return
  290. }
  291. // If parsing fails, return as string
  292. jsonObj(c, ips, nil)
  293. }
  294. // clearClientIps clears the IP addresses for a client by email.
  295. func (a *InboundController) clearClientIps(c *gin.Context) {
  296. email := c.Param("email")
  297. err := a.inboundService.ClearClientIps(email)
  298. if err != nil {
  299. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.updateSuccess"), err)
  300. return
  301. }
  302. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.logCleanSuccess"), nil)
  303. }
  304. // addInboundClient adds a new client to an existing inbound.
  305. func (a *InboundController) addInboundClient(c *gin.Context) {
  306. data := &model.Inbound{}
  307. err := c.ShouldBind(data)
  308. if err != nil {
  309. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  310. return
  311. }
  312. needRestart, err := a.inboundService.AddInboundClient(data)
  313. if err != nil {
  314. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  315. return
  316. }
  317. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientAddSuccess"), nil)
  318. if needRestart {
  319. a.xrayService.SetToNeedRestart()
  320. }
  321. }
  322. // copyInboundClients copies clients from source inbound to target inbound.
  323. func (a *InboundController) copyInboundClients(c *gin.Context) {
  324. targetID, err := strconv.Atoi(c.Param("id"))
  325. if err != nil {
  326. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  327. return
  328. }
  329. req := &CopyInboundClientsRequest{}
  330. err = c.ShouldBind(req)
  331. if err != nil {
  332. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  333. return
  334. }
  335. if req.SourceInboundID <= 0 {
  336. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), fmt.Errorf("invalid source inbound id"))
  337. return
  338. }
  339. result, needRestart, err := a.inboundService.CopyInboundClients(targetID, req.SourceInboundID, req.ClientEmails, req.Flow)
  340. if err != nil {
  341. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  342. return
  343. }
  344. jsonObj(c, result, nil)
  345. if needRestart {
  346. a.xrayService.SetToNeedRestart()
  347. }
  348. }
  349. // delInboundClient deletes a client from an inbound by inbound ID and client ID.
  350. func (a *InboundController) delInboundClient(c *gin.Context) {
  351. id, err := strconv.Atoi(c.Param("id"))
  352. if err != nil {
  353. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  354. return
  355. }
  356. clientId := c.Param("clientId")
  357. needRestart, err := a.inboundService.DelInboundClient(id, clientId)
  358. if err != nil {
  359. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  360. return
  361. }
  362. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientDeleteSuccess"), nil)
  363. if needRestart {
  364. a.xrayService.SetToNeedRestart()
  365. }
  366. }
  367. // updateInboundClient updates a client's configuration in an inbound.
  368. func (a *InboundController) updateInboundClient(c *gin.Context) {
  369. clientId := c.Param("clientId")
  370. inbound := &model.Inbound{}
  371. err := c.ShouldBind(inbound)
  372. if err != nil {
  373. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  374. return
  375. }
  376. needRestart, err := a.inboundService.UpdateInboundClient(inbound, clientId)
  377. if err != nil {
  378. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  379. return
  380. }
  381. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientUpdateSuccess"), nil)
  382. if needRestart {
  383. a.xrayService.SetToNeedRestart()
  384. }
  385. }
  386. // resetClientTraffic resets the traffic counter for a specific client in an inbound.
  387. func (a *InboundController) resetClientTraffic(c *gin.Context) {
  388. id, err := strconv.Atoi(c.Param("id"))
  389. if err != nil {
  390. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  391. return
  392. }
  393. email := c.Param("email")
  394. needRestart, err := a.inboundService.ResetClientTraffic(id, email)
  395. if err != nil {
  396. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  397. return
  398. }
  399. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.resetInboundClientTrafficSuccess"), nil)
  400. if needRestart {
  401. a.xrayService.SetToNeedRestart()
  402. }
  403. }
  404. // resetInboundTraffic resets traffic counters for a specific inbound.
  405. func (a *InboundController) resetInboundTraffic(c *gin.Context) {
  406. id, err := strconv.Atoi(c.Param("id"))
  407. if err != nil {
  408. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  409. return
  410. }
  411. err = a.inboundService.ResetInboundTraffic(id)
  412. if err != nil {
  413. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  414. return
  415. } else {
  416. a.xrayService.SetToNeedRestart()
  417. }
  418. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.resetInboundTrafficSuccess"), nil)
  419. }
  420. // resetAllTraffics resets all traffic counters across all inbounds.
  421. func (a *InboundController) resetAllTraffics(c *gin.Context) {
  422. err := a.inboundService.ResetAllTraffics()
  423. if err != nil {
  424. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  425. return
  426. } else {
  427. a.xrayService.SetToNeedRestart()
  428. }
  429. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.resetAllTrafficSuccess"), nil)
  430. }
  431. // resetAllClientTraffics resets traffic counters for all clients in a specific inbound.
  432. func (a *InboundController) resetAllClientTraffics(c *gin.Context) {
  433. id, err := strconv.Atoi(c.Param("id"))
  434. if err != nil {
  435. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  436. return
  437. }
  438. err = a.inboundService.ResetAllClientTraffics(id)
  439. if err != nil {
  440. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  441. return
  442. } else {
  443. a.xrayService.SetToNeedRestart()
  444. }
  445. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.resetAllClientTrafficSuccess"), nil)
  446. }
  447. // importInbound imports an inbound configuration from provided data.
  448. func (a *InboundController) importInbound(c *gin.Context) {
  449. inbound := &model.Inbound{}
  450. err := json.Unmarshal([]byte(c.PostForm("data")), inbound)
  451. if err != nil {
  452. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  453. return
  454. }
  455. user := session.GetLoginUser(c)
  456. inbound.Id = 0
  457. inbound.UserId = user.Id
  458. if inbound.Tag == "" {
  459. if inbound.Listen == "" || inbound.Listen == "0.0.0.0" || inbound.Listen == "::" || inbound.Listen == "::0" {
  460. inbound.Tag = fmt.Sprintf("inbound-%v", inbound.Port)
  461. } else {
  462. inbound.Tag = fmt.Sprintf("inbound-%v:%v", inbound.Listen, inbound.Port)
  463. }
  464. }
  465. for index := range inbound.ClientStats {
  466. inbound.ClientStats[index].Id = 0
  467. inbound.ClientStats[index].Enable = true
  468. }
  469. needRestart := false
  470. inbound, needRestart, err = a.inboundService.AddInbound(inbound)
  471. jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundCreateSuccess"), inbound, err)
  472. if err == nil && needRestart {
  473. a.xrayService.SetToNeedRestart()
  474. }
  475. }
  476. // delDepletedClients deletes clients in an inbound who have exhausted their traffic limits.
  477. func (a *InboundController) delDepletedClients(c *gin.Context) {
  478. id, err := strconv.Atoi(c.Param("id"))
  479. if err != nil {
  480. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  481. return
  482. }
  483. err = a.inboundService.DelDepletedClients(id)
  484. if err != nil {
  485. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  486. return
  487. }
  488. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.delDepletedClientsSuccess"), nil)
  489. }
  490. // onlines retrieves the list of currently online clients.
  491. func (a *InboundController) onlines(c *gin.Context) {
  492. jsonObj(c, a.inboundService.GetOnlineClients(), nil)
  493. }
  494. // lastOnline retrieves the last online timestamps for clients.
  495. func (a *InboundController) lastOnline(c *gin.Context) {
  496. data, err := a.inboundService.GetClientsLastOnline()
  497. jsonObj(c, data, err)
  498. }
  499. // updateClientTraffic updates the traffic statistics for a client by email.
  500. func (a *InboundController) updateClientTraffic(c *gin.Context) {
  501. email := c.Param("email")
  502. // Define the request structure for traffic update
  503. type TrafficUpdateRequest struct {
  504. Upload int64 `json:"upload"`
  505. Download int64 `json:"download"`
  506. }
  507. var request TrafficUpdateRequest
  508. err := c.ShouldBindJSON(&request)
  509. if err != nil {
  510. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  511. return
  512. }
  513. err = a.inboundService.UpdateClientTrafficByEmail(email, request.Upload, request.Download)
  514. if err != nil {
  515. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  516. return
  517. }
  518. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientUpdateSuccess"), nil)
  519. }
  520. // delInboundClientByEmail deletes a client from an inbound by email address.
  521. func (a *InboundController) delInboundClientByEmail(c *gin.Context) {
  522. inboundId, err := strconv.Atoi(c.Param("id"))
  523. if err != nil {
  524. jsonMsg(c, "Invalid inbound ID", err)
  525. return
  526. }
  527. email := c.Param("email")
  528. needRestart, err := a.inboundService.DelInboundClientByEmail(inboundId, email)
  529. if err != nil {
  530. jsonMsg(c, "Failed to delete client by email", err)
  531. return
  532. }
  533. jsonMsg(c, "Client deleted successfully", nil)
  534. if needRestart {
  535. a.xrayService.SetToNeedRestart()
  536. }
  537. }
  538. // resolveHost mirrors what sub.SubService.ResolveRequest does for the host
  539. // field: prefers X-Forwarded-Host (first entry of any list, port stripped),
  540. // then X-Real-IP, then the host portion of c.Request.Host. Keeping it in the
  541. // controller layer means the service interface stays HTTP-agnostic — service
  542. // methods receive a plain host string instead of a *gin.Context.
  543. func resolveHost(c *gin.Context) string {
  544. if isTrustedForwardedRequest(c) {
  545. if h := strings.TrimSpace(c.GetHeader("X-Forwarded-Host")); h != "" {
  546. if i := strings.Index(h, ","); i >= 0 {
  547. h = strings.TrimSpace(h[:i])
  548. }
  549. if hp, _, err := net.SplitHostPort(h); err == nil {
  550. return hp
  551. }
  552. return h
  553. }
  554. if h := c.GetHeader("X-Real-IP"); h != "" {
  555. return h
  556. }
  557. }
  558. if h, _, err := net.SplitHostPort(c.Request.Host); err == nil {
  559. return h
  560. }
  561. return c.Request.Host
  562. }
  563. // getSubLinks returns every protocol URL produced for the given subscription
  564. // ID — the JSON-array equivalent of /sub/<subId> (no base64 wrap).
  565. func (a *InboundController) getSubLinks(c *gin.Context) {
  566. links, err := a.inboundService.GetSubLinks(resolveHost(c), c.Param("subId"))
  567. if err != nil {
  568. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
  569. return
  570. }
  571. jsonObj(c, links, nil)
  572. }
  573. // getClientLinks returns the URL(s) for one client on one inbound — the same
  574. // string the Copy URL button copies in the panel UI. Empty array when the
  575. // protocol has no URL form, or when the email isn't found on the inbound.
  576. func (a *InboundController) getClientLinks(c *gin.Context) {
  577. id, err := strconv.Atoi(c.Param("id"))
  578. if err != nil {
  579. jsonMsg(c, I18nWeb(c, "get"), err)
  580. return
  581. }
  582. links, err := a.inboundService.GetClientLinks(resolveHost(c), id, c.Param("email"))
  583. if err != nil {
  584. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
  585. return
  586. }
  587. jsonObj(c, links, nil)
  588. }