inbound.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. package controller
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strconv"
  6. "time"
  7. "github.com/mhsanaei/3x-ui/v2/database/model"
  8. "github.com/mhsanaei/3x-ui/v2/web/service"
  9. "github.com/mhsanaei/3x-ui/v2/web/session"
  10. "github.com/mhsanaei/3x-ui/v2/web/websocket"
  11. "github.com/gin-gonic/gin"
  12. )
  13. // InboundController handles HTTP requests related to Xray inbounds management.
  14. type InboundController struct {
  15. inboundService service.InboundService
  16. xrayService service.XrayService
  17. }
  18. // NewInboundController creates a new InboundController and sets up its routes.
  19. func NewInboundController(g *gin.RouterGroup) *InboundController {
  20. a := &InboundController{}
  21. a.initRouter(g)
  22. return a
  23. }
  24. // initRouter initializes the routes for inbound-related operations.
  25. func (a *InboundController) initRouter(g *gin.RouterGroup) {
  26. g.GET("/list", a.getInbounds)
  27. g.GET("/get/:id", a.getInbound)
  28. g.GET("/getClientTraffics/:email", a.getClientTraffics)
  29. g.GET("/getClientTrafficsById/:id", a.getClientTrafficsById)
  30. g.POST("/add", a.addInbound)
  31. g.POST("/del/:id", a.delInbound)
  32. g.POST("/update/:id", a.updateInbound)
  33. g.POST("/clientIps/:email", a.getClientIps)
  34. g.POST("/clearClientIps/:email", a.clearClientIps)
  35. g.POST("/addClient", a.addInboundClient)
  36. g.POST("/:id/copyClients", a.copyInboundClients)
  37. g.POST("/:id/delClient/:clientId", a.delInboundClient)
  38. g.POST("/updateClient/:clientId", a.updateInboundClient)
  39. g.POST("/:id/resetClientTraffic/:email", a.resetClientTraffic)
  40. g.POST("/resetAllTraffics", a.resetAllTraffics)
  41. g.POST("/resetAllClientTraffics/:id", a.resetAllClientTraffics)
  42. g.POST("/delDepletedClients/:id", a.delDepletedClients)
  43. g.POST("/import", a.importInbound)
  44. g.POST("/onlines", a.onlines)
  45. g.POST("/lastOnline", a.lastOnline)
  46. g.POST("/updateClientTraffic/:email", a.updateClientTraffic)
  47. g.POST("/:id/delClientByEmail/:email", a.delInboundClientByEmail)
  48. }
  49. type CopyInboundClientsRequest struct {
  50. SourceInboundID int `form:"sourceInboundId" json:"sourceInboundId"`
  51. ClientEmails []string `form:"clientEmails" json:"clientEmails"`
  52. Flow string `form:"flow" json:"flow"`
  53. }
  54. // getInbounds retrieves the list of inbounds for the logged-in user.
  55. func (a *InboundController) getInbounds(c *gin.Context) {
  56. user := session.GetLoginUser(c)
  57. inbounds, err := a.inboundService.GetInbounds(user.Id)
  58. if err != nil {
  59. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
  60. return
  61. }
  62. jsonObj(c, inbounds, nil)
  63. }
  64. // getInbound retrieves a specific inbound by its ID.
  65. func (a *InboundController) getInbound(c *gin.Context) {
  66. id, err := strconv.Atoi(c.Param("id"))
  67. if err != nil {
  68. jsonMsg(c, I18nWeb(c, "get"), err)
  69. return
  70. }
  71. inbound, err := a.inboundService.GetInbound(id)
  72. if err != nil {
  73. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
  74. return
  75. }
  76. jsonObj(c, inbound, nil)
  77. }
  78. // getClientTraffics retrieves client traffic information by email.
  79. func (a *InboundController) getClientTraffics(c *gin.Context) {
  80. email := c.Param("email")
  81. clientTraffics, err := a.inboundService.GetClientTrafficByEmail(email)
  82. if err != nil {
  83. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.trafficGetError"), err)
  84. return
  85. }
  86. jsonObj(c, clientTraffics, nil)
  87. }
  88. // getClientTrafficsById retrieves client traffic information by inbound ID.
  89. func (a *InboundController) getClientTrafficsById(c *gin.Context) {
  90. id := c.Param("id")
  91. clientTraffics, err := a.inboundService.GetClientTrafficByID(id)
  92. if err != nil {
  93. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.trafficGetError"), err)
  94. return
  95. }
  96. jsonObj(c, clientTraffics, nil)
  97. }
  98. // addInbound creates a new inbound configuration.
  99. func (a *InboundController) addInbound(c *gin.Context) {
  100. inbound := &model.Inbound{}
  101. err := c.ShouldBind(inbound)
  102. if err != nil {
  103. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundCreateSuccess"), err)
  104. return
  105. }
  106. user := session.GetLoginUser(c)
  107. inbound.UserId = user.Id
  108. if inbound.Listen == "" || inbound.Listen == "0.0.0.0" || inbound.Listen == "::" || inbound.Listen == "::0" {
  109. inbound.Tag = fmt.Sprintf("inbound-%v", inbound.Port)
  110. } else {
  111. inbound.Tag = fmt.Sprintf("inbound-%v:%v", inbound.Listen, inbound.Port)
  112. }
  113. inbound, needRestart, err := a.inboundService.AddInbound(inbound)
  114. if err != nil {
  115. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  116. return
  117. }
  118. jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundCreateSuccess"), inbound, nil)
  119. if needRestart {
  120. a.xrayService.SetToNeedRestart()
  121. }
  122. // Broadcast inbounds update via WebSocket
  123. inbounds, _ := a.inboundService.GetInbounds(user.Id)
  124. websocket.BroadcastInbounds(inbounds)
  125. }
  126. // delInbound deletes an inbound configuration by its ID.
  127. func (a *InboundController) delInbound(c *gin.Context) {
  128. id, err := strconv.Atoi(c.Param("id"))
  129. if err != nil {
  130. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundDeleteSuccess"), err)
  131. return
  132. }
  133. needRestart, err := a.inboundService.DelInbound(id)
  134. if err != nil {
  135. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  136. return
  137. }
  138. jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundDeleteSuccess"), id, nil)
  139. if needRestart {
  140. a.xrayService.SetToNeedRestart()
  141. }
  142. // Broadcast inbounds update via WebSocket
  143. user := session.GetLoginUser(c)
  144. inbounds, _ := a.inboundService.GetInbounds(user.Id)
  145. websocket.BroadcastInbounds(inbounds)
  146. }
  147. // updateInbound updates an existing inbound configuration.
  148. func (a *InboundController) updateInbound(c *gin.Context) {
  149. id, err := strconv.Atoi(c.Param("id"))
  150. if err != nil {
  151. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  152. return
  153. }
  154. inbound := &model.Inbound{
  155. Id: id,
  156. }
  157. err = c.ShouldBind(inbound)
  158. if err != nil {
  159. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  160. return
  161. }
  162. inbound, needRestart, err := a.inboundService.UpdateInbound(inbound)
  163. if err != nil {
  164. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  165. return
  166. }
  167. jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), inbound, nil)
  168. if needRestart {
  169. a.xrayService.SetToNeedRestart()
  170. }
  171. // Broadcast inbounds update via WebSocket
  172. user := session.GetLoginUser(c)
  173. inbounds, _ := a.inboundService.GetInbounds(user.Id)
  174. websocket.BroadcastInbounds(inbounds)
  175. }
  176. // getClientIps retrieves the IP addresses associated with a client by email.
  177. func (a *InboundController) getClientIps(c *gin.Context) {
  178. email := c.Param("email")
  179. ips, err := a.inboundService.GetInboundClientIps(email)
  180. if err != nil || ips == "" {
  181. jsonObj(c, "No IP Record", nil)
  182. return
  183. }
  184. // Prefer returning a normalized string list for consistent UI rendering
  185. type ipWithTimestamp struct {
  186. IP string `json:"ip"`
  187. Timestamp int64 `json:"timestamp"`
  188. }
  189. var ipsWithTime []ipWithTimestamp
  190. if err := json.Unmarshal([]byte(ips), &ipsWithTime); err == nil && len(ipsWithTime) > 0 {
  191. formatted := make([]string, 0, len(ipsWithTime))
  192. for _, item := range ipsWithTime {
  193. if item.IP == "" {
  194. continue
  195. }
  196. if item.Timestamp > 0 {
  197. ts := time.Unix(item.Timestamp, 0).Local().Format("2006-01-02 15:04:05")
  198. formatted = append(formatted, fmt.Sprintf("%s (%s)", item.IP, ts))
  199. continue
  200. }
  201. formatted = append(formatted, item.IP)
  202. }
  203. jsonObj(c, formatted, nil)
  204. return
  205. }
  206. var oldIps []string
  207. if err := json.Unmarshal([]byte(ips), &oldIps); err == nil && len(oldIps) > 0 {
  208. jsonObj(c, oldIps, nil)
  209. return
  210. }
  211. // If parsing fails, return as string
  212. jsonObj(c, ips, nil)
  213. }
  214. // clearClientIps clears the IP addresses for a client by email.
  215. func (a *InboundController) clearClientIps(c *gin.Context) {
  216. email := c.Param("email")
  217. err := a.inboundService.ClearClientIps(email)
  218. if err != nil {
  219. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.updateSuccess"), err)
  220. return
  221. }
  222. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.logCleanSuccess"), nil)
  223. }
  224. // addInboundClient adds a new client to an existing inbound.
  225. func (a *InboundController) addInboundClient(c *gin.Context) {
  226. data := &model.Inbound{}
  227. err := c.ShouldBind(data)
  228. if err != nil {
  229. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  230. return
  231. }
  232. needRestart, err := a.inboundService.AddInboundClient(data)
  233. if err != nil {
  234. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  235. return
  236. }
  237. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientAddSuccess"), nil)
  238. if needRestart {
  239. a.xrayService.SetToNeedRestart()
  240. }
  241. }
  242. // copyInboundClients copies clients from source inbound to target inbound.
  243. func (a *InboundController) copyInboundClients(c *gin.Context) {
  244. targetID, err := strconv.Atoi(c.Param("id"))
  245. if err != nil {
  246. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  247. return
  248. }
  249. req := &CopyInboundClientsRequest{}
  250. err = c.ShouldBind(req)
  251. if err != nil {
  252. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  253. return
  254. }
  255. if req.SourceInboundID <= 0 {
  256. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), fmt.Errorf("invalid source inbound id"))
  257. return
  258. }
  259. result, needRestart, err := a.inboundService.CopyInboundClients(targetID, req.SourceInboundID, req.ClientEmails, req.Flow)
  260. if err != nil {
  261. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  262. return
  263. }
  264. jsonObj(c, result, nil)
  265. if needRestart {
  266. a.xrayService.SetToNeedRestart()
  267. }
  268. }
  269. // delInboundClient deletes a client from an inbound by inbound ID and client ID.
  270. func (a *InboundController) delInboundClient(c *gin.Context) {
  271. id, err := strconv.Atoi(c.Param("id"))
  272. if err != nil {
  273. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  274. return
  275. }
  276. clientId := c.Param("clientId")
  277. needRestart, err := a.inboundService.DelInboundClient(id, clientId)
  278. if err != nil {
  279. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  280. return
  281. }
  282. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientDeleteSuccess"), nil)
  283. if needRestart {
  284. a.xrayService.SetToNeedRestart()
  285. }
  286. }
  287. // updateInboundClient updates a client's configuration in an inbound.
  288. func (a *InboundController) updateInboundClient(c *gin.Context) {
  289. clientId := c.Param("clientId")
  290. inbound := &model.Inbound{}
  291. err := c.ShouldBind(inbound)
  292. if err != nil {
  293. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  294. return
  295. }
  296. needRestart, err := a.inboundService.UpdateInboundClient(inbound, clientId)
  297. if err != nil {
  298. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  299. return
  300. }
  301. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientUpdateSuccess"), nil)
  302. if needRestart {
  303. a.xrayService.SetToNeedRestart()
  304. }
  305. }
  306. // resetClientTraffic resets the traffic counter for a specific client in an inbound.
  307. func (a *InboundController) resetClientTraffic(c *gin.Context) {
  308. id, err := strconv.Atoi(c.Param("id"))
  309. if err != nil {
  310. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  311. return
  312. }
  313. email := c.Param("email")
  314. needRestart, err := a.inboundService.ResetClientTraffic(id, email)
  315. if err != nil {
  316. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  317. return
  318. }
  319. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.resetInboundClientTrafficSuccess"), nil)
  320. if needRestart {
  321. a.xrayService.SetToNeedRestart()
  322. }
  323. }
  324. // resetAllTraffics resets all traffic counters across all inbounds.
  325. func (a *InboundController) resetAllTraffics(c *gin.Context) {
  326. err := a.inboundService.ResetAllTraffics()
  327. if err != nil {
  328. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  329. return
  330. } else {
  331. a.xrayService.SetToNeedRestart()
  332. }
  333. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.resetAllTrafficSuccess"), nil)
  334. }
  335. // resetAllClientTraffics resets traffic counters for all clients in a specific inbound.
  336. func (a *InboundController) resetAllClientTraffics(c *gin.Context) {
  337. id, err := strconv.Atoi(c.Param("id"))
  338. if err != nil {
  339. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  340. return
  341. }
  342. err = a.inboundService.ResetAllClientTraffics(id)
  343. if err != nil {
  344. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  345. return
  346. } else {
  347. a.xrayService.SetToNeedRestart()
  348. }
  349. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.resetAllClientTrafficSuccess"), nil)
  350. }
  351. // importInbound imports an inbound configuration from provided data.
  352. func (a *InboundController) importInbound(c *gin.Context) {
  353. inbound := &model.Inbound{}
  354. err := json.Unmarshal([]byte(c.PostForm("data")), inbound)
  355. if err != nil {
  356. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  357. return
  358. }
  359. user := session.GetLoginUser(c)
  360. inbound.Id = 0
  361. inbound.UserId = user.Id
  362. if inbound.Listen == "" || inbound.Listen == "0.0.0.0" || inbound.Listen == "::" || inbound.Listen == "::0" {
  363. inbound.Tag = fmt.Sprintf("inbound-%v", inbound.Port)
  364. } else {
  365. inbound.Tag = fmt.Sprintf("inbound-%v:%v", inbound.Listen, inbound.Port)
  366. }
  367. for index := range inbound.ClientStats {
  368. inbound.ClientStats[index].Id = 0
  369. inbound.ClientStats[index].Enable = true
  370. }
  371. needRestart := false
  372. inbound, needRestart, err = a.inboundService.AddInbound(inbound)
  373. jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundCreateSuccess"), inbound, err)
  374. if err == nil && needRestart {
  375. a.xrayService.SetToNeedRestart()
  376. }
  377. }
  378. // delDepletedClients deletes clients in an inbound who have exhausted their traffic limits.
  379. func (a *InboundController) delDepletedClients(c *gin.Context) {
  380. id, err := strconv.Atoi(c.Param("id"))
  381. if err != nil {
  382. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  383. return
  384. }
  385. err = a.inboundService.DelDepletedClients(id)
  386. if err != nil {
  387. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  388. return
  389. }
  390. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.delDepletedClientsSuccess"), nil)
  391. }
  392. // onlines retrieves the list of currently online clients.
  393. func (a *InboundController) onlines(c *gin.Context) {
  394. jsonObj(c, a.inboundService.GetOnlineClients(), nil)
  395. }
  396. // lastOnline retrieves the last online timestamps for clients.
  397. func (a *InboundController) lastOnline(c *gin.Context) {
  398. data, err := a.inboundService.GetClientsLastOnline()
  399. jsonObj(c, data, err)
  400. }
  401. // updateClientTraffic updates the traffic statistics for a client by email.
  402. func (a *InboundController) updateClientTraffic(c *gin.Context) {
  403. email := c.Param("email")
  404. // Define the request structure for traffic update
  405. type TrafficUpdateRequest struct {
  406. Upload int64 `json:"upload"`
  407. Download int64 `json:"download"`
  408. }
  409. var request TrafficUpdateRequest
  410. err := c.ShouldBindJSON(&request)
  411. if err != nil {
  412. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  413. return
  414. }
  415. err = a.inboundService.UpdateClientTrafficByEmail(email, request.Upload, request.Download)
  416. if err != nil {
  417. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  418. return
  419. }
  420. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientUpdateSuccess"), nil)
  421. }
  422. // delInboundClientByEmail deletes a client from an inbound by email address.
  423. func (a *InboundController) delInboundClientByEmail(c *gin.Context) {
  424. inboundId, err := strconv.Atoi(c.Param("id"))
  425. if err != nil {
  426. jsonMsg(c, "Invalid inbound ID", err)
  427. return
  428. }
  429. email := c.Param("email")
  430. needRestart, err := a.inboundService.DelInboundClientByEmail(inboundId, email)
  431. if err != nil {
  432. jsonMsg(c, "Failed to delete client by email", err)
  433. return
  434. }
  435. jsonMsg(c, "Client deleted successfully", nil)
  436. if needRestart {
  437. a.xrayService.SetToNeedRestart()
  438. }
  439. }