1
0

client.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. package controller
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strconv"
  6. "strings"
  7. "time"
  8. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  9. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  10. "github.com/mhsanaei/3x-ui/v3/internal/web/websocket"
  11. "github.com/gin-gonic/gin"
  12. )
  13. func notifyClientsChanged() {
  14. websocket.BroadcastInvalidate(websocket.MessageTypeClients)
  15. }
  16. func parseInboundIdsQuery(raw string) []int {
  17. raw = strings.TrimSpace(raw)
  18. if raw == "" {
  19. return nil
  20. }
  21. parts := strings.Split(raw, ",")
  22. ids := make([]int, 0, len(parts))
  23. for _, p := range parts {
  24. if id, err := strconv.Atoi(strings.TrimSpace(p)); err == nil {
  25. ids = append(ids, id)
  26. }
  27. }
  28. return ids
  29. }
  30. type ClientController struct {
  31. clientService service.ClientService
  32. inboundService service.InboundService
  33. xrayService service.XrayService
  34. settingService service.SettingService
  35. }
  36. func NewClientController(g *gin.RouterGroup) *ClientController {
  37. a := &ClientController{}
  38. a.initRouter(g)
  39. return a
  40. }
  41. func (a *ClientController) initRouter(g *gin.RouterGroup) {
  42. g.GET("/list", a.list)
  43. g.GET("/list/paged", a.listPaged)
  44. g.GET("/get/:email", a.get)
  45. g.GET("/traffic/:email", a.getTrafficByEmail)
  46. g.GET("/subLinks/:subId", a.getSubLinks)
  47. g.GET("/links/:email", a.getClientLinks)
  48. g.POST("/add", a.create)
  49. g.POST("/update/:email", a.update)
  50. g.POST("/del/:email", a.delete)
  51. g.POST("/:email/attach", a.attach)
  52. g.POST("/:email/detach", a.detach)
  53. g.POST("/resetAllTraffics", a.resetAllTraffics)
  54. g.POST("/delDepleted", a.delDepleted)
  55. g.POST("/bulkAdjust", a.bulkAdjust)
  56. g.POST("/bulkDel", a.bulkDelete)
  57. g.POST("/bulkCreate", a.bulkCreate)
  58. g.POST("/bulkAttach", a.bulkAttach)
  59. g.POST("/bulkDetach", a.bulkDetach)
  60. g.POST("/bulkResetTraffic", a.bulkResetTraffic)
  61. g.POST("/resetTraffic/:email", a.resetTrafficByEmail)
  62. g.POST("/updateTraffic/:email", a.updateTrafficByEmail)
  63. g.POST("/ips/:email", a.getIps)
  64. g.POST("/clearIps/:email", a.clearIps)
  65. g.POST("/onlines", a.onlines)
  66. g.POST("/onlinesByGuid", a.onlinesByGuid)
  67. g.POST("/activeInbounds", a.activeInbounds)
  68. g.POST("/lastOnline", a.lastOnline)
  69. }
  70. func (a *ClientController) list(c *gin.Context) {
  71. rows, err := a.clientService.List()
  72. if err != nil {
  73. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
  74. return
  75. }
  76. jsonObj(c, rows, nil)
  77. }
  78. func (a *ClientController) listPaged(c *gin.Context) {
  79. var params service.ClientPageParams
  80. if err := c.ShouldBindQuery(&params); err != nil {
  81. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
  82. return
  83. }
  84. resp, err := a.clientService.ListPaged(&a.inboundService, &a.settingService, params)
  85. if err != nil {
  86. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
  87. return
  88. }
  89. jsonObj(c, resp, nil)
  90. }
  91. func (a *ClientController) get(c *gin.Context) {
  92. email := c.Param("email")
  93. rec, err := a.clientService.GetRecordByEmail(nil, email)
  94. if err != nil {
  95. jsonMsg(c, I18nWeb(c, "get"), err)
  96. return
  97. }
  98. inboundIds, err := a.clientService.GetInboundIdsForRecord(rec.Id)
  99. if err != nil {
  100. jsonMsg(c, I18nWeb(c, "get"), err)
  101. return
  102. }
  103. flow, err := a.clientService.EffectiveFlow(nil, rec.Id)
  104. if err != nil {
  105. jsonMsg(c, I18nWeb(c, "get"), err)
  106. return
  107. }
  108. rec.Flow = flow
  109. // Consumed bytes (up+down, including cross-node global overlay) so API
  110. // consumers can pair usage with the client's totalGB quota (#4973).
  111. // Best-effort: a traffic lookup failure must not break the client fetch.
  112. var usedTraffic int64
  113. if t, tErr := a.inboundService.GetClientTrafficByEmail(email); tErr == nil && t != nil {
  114. usedTraffic = t.Up + t.Down
  115. }
  116. jsonObj(c, gin.H{"client": rec, "inboundIds": inboundIds, "usedTraffic": usedTraffic}, nil)
  117. }
  118. func (a *ClientController) create(c *gin.Context) {
  119. var payload service.ClientCreatePayload
  120. if err := c.ShouldBindJSON(&payload); err != nil {
  121. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  122. return
  123. }
  124. needRestart, err := a.clientService.Create(&a.inboundService, &payload)
  125. if err != nil {
  126. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  127. return
  128. }
  129. jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientAddSuccess"), pendingNodeObj(a.inboundService.AnyNodePending(payload.InboundIds)), nil)
  130. if needRestart {
  131. a.xrayService.SetToNeedRestart()
  132. }
  133. notifyClientsChanged()
  134. }
  135. func (a *ClientController) update(c *gin.Context) {
  136. email := c.Param("email")
  137. var updated model.Client
  138. if err := c.ShouldBindJSON(&updated); err != nil {
  139. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  140. return
  141. }
  142. inboundFilter := parseInboundIdsQuery(c.Query("inboundIds"))
  143. needRestart, err := a.clientService.UpdateByEmail(&a.inboundService, email, updated, inboundFilter...)
  144. if err != nil {
  145. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  146. return
  147. }
  148. jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientUpdateSuccess"), pendingNodeObj(a.clientService.HasPendingNode(&a.inboundService, email)), nil)
  149. if needRestart {
  150. a.xrayService.SetToNeedRestart()
  151. }
  152. notifyClientsChanged()
  153. }
  154. func (a *ClientController) delete(c *gin.Context) {
  155. email := c.Param("email")
  156. keepTraffic := c.Query("keepTraffic") == "1"
  157. needRestart, err := a.clientService.DeleteByEmail(&a.inboundService, email, keepTraffic)
  158. if err != nil {
  159. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  160. return
  161. }
  162. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientDeleteSuccess"), nil)
  163. if needRestart {
  164. a.xrayService.SetToNeedRestart()
  165. }
  166. notifyClientsChanged()
  167. }
  168. type attachDetachBody struct {
  169. InboundIds []int `json:"inboundIds"`
  170. }
  171. func (a *ClientController) attach(c *gin.Context) {
  172. email := c.Param("email")
  173. var body attachDetachBody
  174. if err := c.ShouldBindJSON(&body); err != nil {
  175. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  176. return
  177. }
  178. needRestart, err := a.clientService.AttachByEmail(&a.inboundService, email, body.InboundIds)
  179. if err != nil {
  180. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  181. return
  182. }
  183. jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientAddSuccess"), pendingNodeObj(a.inboundService.AnyNodePending(body.InboundIds)), nil)
  184. if needRestart {
  185. a.xrayService.SetToNeedRestart()
  186. }
  187. notifyClientsChanged()
  188. }
  189. func (a *ClientController) resetAllTraffics(c *gin.Context) {
  190. needRestart, err := a.clientService.ResetAllTraffics()
  191. if err != nil {
  192. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  193. return
  194. }
  195. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.resetAllClientTrafficSuccess"), nil)
  196. if needRestart {
  197. a.xrayService.SetToNeedRestart()
  198. }
  199. notifyClientsChanged()
  200. }
  201. type bulkAdjustRequest struct {
  202. Emails []string `json:"emails"`
  203. AddDays int `json:"addDays"`
  204. AddBytes int64 `json:"addBytes"`
  205. }
  206. func (a *ClientController) bulkAdjust(c *gin.Context) {
  207. var req bulkAdjustRequest
  208. if err := c.ShouldBindJSON(&req); err != nil {
  209. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  210. return
  211. }
  212. result, needRestart, err := a.clientService.BulkAdjust(&a.inboundService, req.Emails, req.AddDays, req.AddBytes)
  213. if err != nil {
  214. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  215. return
  216. }
  217. jsonObj(c, result, nil)
  218. if needRestart {
  219. a.xrayService.SetToNeedRestart()
  220. }
  221. notifyClientsChanged()
  222. }
  223. type bulkDeleteRequest struct {
  224. Emails []string `json:"emails"`
  225. KeepTraffic bool `json:"keepTraffic"`
  226. }
  227. type bulkAttachRequest struct {
  228. Emails []string `json:"emails"`
  229. InboundIds []int `json:"inboundIds"`
  230. }
  231. func (a *ClientController) bulkAttach(c *gin.Context) {
  232. var req bulkAttachRequest
  233. if err := c.ShouldBindJSON(&req); err != nil {
  234. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  235. return
  236. }
  237. result, needRestart, err := a.clientService.BulkAttach(&a.inboundService, req.Emails, req.InboundIds)
  238. if err != nil {
  239. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  240. return
  241. }
  242. jsonObj(c, result, nil)
  243. if needRestart {
  244. a.xrayService.SetToNeedRestart()
  245. }
  246. notifyClientsChanged()
  247. }
  248. type bulkDetachRequest struct {
  249. Emails []string `json:"emails"`
  250. InboundIds []int `json:"inboundIds"`
  251. }
  252. func (a *ClientController) bulkDetach(c *gin.Context) {
  253. var req bulkDetachRequest
  254. if err := c.ShouldBindJSON(&req); err != nil {
  255. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  256. return
  257. }
  258. result, needRestart, err := a.clientService.BulkDetach(&a.inboundService, req.Emails, req.InboundIds)
  259. if err != nil {
  260. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  261. return
  262. }
  263. jsonObj(c, result, nil)
  264. if needRestart {
  265. a.xrayService.SetToNeedRestart()
  266. }
  267. notifyClientsChanged()
  268. }
  269. func (a *ClientController) bulkDelete(c *gin.Context) {
  270. var req bulkDeleteRequest
  271. if err := c.ShouldBindJSON(&req); err != nil {
  272. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  273. return
  274. }
  275. result, needRestart, err := a.clientService.BulkDelete(&a.inboundService, req.Emails, req.KeepTraffic)
  276. if err != nil {
  277. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  278. return
  279. }
  280. jsonObj(c, result, nil)
  281. if needRestart {
  282. a.xrayService.SetToNeedRestart()
  283. }
  284. notifyClientsChanged()
  285. }
  286. func (a *ClientController) bulkCreate(c *gin.Context) {
  287. var payloads []service.ClientCreatePayload
  288. if err := c.ShouldBindJSON(&payloads); err != nil {
  289. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  290. return
  291. }
  292. result, needRestart, err := a.clientService.BulkCreate(&a.inboundService, payloads)
  293. if err != nil {
  294. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  295. return
  296. }
  297. jsonObj(c, result, nil)
  298. if needRestart {
  299. a.xrayService.SetToNeedRestart()
  300. }
  301. notifyClientsChanged()
  302. }
  303. func (a *ClientController) delDepleted(c *gin.Context) {
  304. deleted, needRestart, err := a.clientService.DelDepleted(&a.inboundService)
  305. if err != nil {
  306. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  307. return
  308. }
  309. jsonObj(c, gin.H{"deleted": deleted}, nil)
  310. if needRestart {
  311. a.xrayService.SetToNeedRestart()
  312. }
  313. notifyClientsChanged()
  314. }
  315. func (a *ClientController) resetTrafficByEmail(c *gin.Context) {
  316. email := c.Param("email")
  317. needRestart, err := a.clientService.ResetTrafficByEmail(&a.inboundService, email)
  318. if err != nil {
  319. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  320. return
  321. }
  322. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.resetInboundClientTrafficSuccess"), nil)
  323. if needRestart {
  324. a.xrayService.SetToNeedRestart()
  325. }
  326. notifyClientsChanged()
  327. }
  328. type trafficUpdateRequest struct {
  329. Upload int64 `json:"upload"`
  330. Download int64 `json:"download"`
  331. }
  332. func (a *ClientController) updateTrafficByEmail(c *gin.Context) {
  333. email := c.Param("email")
  334. var req trafficUpdateRequest
  335. if err := c.ShouldBindJSON(&req); err != nil {
  336. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  337. return
  338. }
  339. if err := a.inboundService.UpdateClientTrafficByEmail(email, req.Upload, req.Download); err != nil {
  340. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  341. return
  342. }
  343. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientUpdateSuccess"), nil)
  344. notifyClientsChanged()
  345. }
  346. func (a *ClientController) getIps(c *gin.Context) {
  347. email := c.Param("email")
  348. ips, err := a.inboundService.GetInboundClientIps(email)
  349. if err != nil || ips == "" {
  350. jsonObj(c, "No IP Record", nil)
  351. return
  352. }
  353. type ipWithTimestamp struct {
  354. IP string `json:"ip"`
  355. Timestamp int64 `json:"timestamp"`
  356. }
  357. var ipsWithTime []ipWithTimestamp
  358. if err := json.Unmarshal([]byte(ips), &ipsWithTime); err == nil && len(ipsWithTime) > 0 {
  359. formatted := make([]string, 0, len(ipsWithTime))
  360. for _, item := range ipsWithTime {
  361. if item.IP == "" {
  362. continue
  363. }
  364. if item.Timestamp > 0 {
  365. ts := time.Unix(item.Timestamp, 0).Local().Format("2006-01-02 15:04:05")
  366. formatted = append(formatted, fmt.Sprintf("%s (%s)", item.IP, ts))
  367. continue
  368. }
  369. formatted = append(formatted, item.IP)
  370. }
  371. jsonObj(c, formatted, nil)
  372. return
  373. }
  374. var oldIps []string
  375. if err := json.Unmarshal([]byte(ips), &oldIps); err == nil && len(oldIps) > 0 {
  376. jsonObj(c, oldIps, nil)
  377. return
  378. }
  379. jsonObj(c, ips, nil)
  380. }
  381. func (a *ClientController) clearIps(c *gin.Context) {
  382. email := c.Param("email")
  383. if err := a.inboundService.ClearClientIps(email); err != nil {
  384. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.updateSuccess"), err)
  385. return
  386. }
  387. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.logCleanSuccess"), nil)
  388. }
  389. func (a *ClientController) onlines(c *gin.Context) {
  390. jsonObj(c, a.inboundService.GetOnlineClients(), nil)
  391. }
  392. func (a *ClientController) onlinesByGuid(c *gin.Context) {
  393. jsonObj(c, a.inboundService.GetOnlineClientsByGuid(), nil)
  394. }
  395. func (a *ClientController) activeInbounds(c *gin.Context) {
  396. jsonObj(c, a.inboundService.GetActiveInboundsByGuid(), nil)
  397. }
  398. func (a *ClientController) lastOnline(c *gin.Context) {
  399. data, err := a.inboundService.GetClientsLastOnline()
  400. jsonObj(c, data, err)
  401. }
  402. func (a *ClientController) getTrafficByEmail(c *gin.Context) {
  403. email := c.Param("email")
  404. traffic, err := a.inboundService.GetClientTrafficByEmail(email)
  405. if err != nil {
  406. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.trafficGetError"), err)
  407. return
  408. }
  409. jsonObj(c, traffic, nil)
  410. }
  411. func (a *ClientController) getSubLinks(c *gin.Context) {
  412. links, err := a.inboundService.GetSubLinks(resolveHost(c), c.Param("subId"))
  413. if err != nil {
  414. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
  415. return
  416. }
  417. jsonObj(c, links, nil)
  418. }
  419. func (a *ClientController) getClientLinks(c *gin.Context) {
  420. links, err := a.inboundService.GetAllClientLinks(resolveHost(c), c.Param("email"))
  421. if err != nil {
  422. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
  423. return
  424. }
  425. jsonObj(c, links, nil)
  426. }
  427. func (a *ClientController) detach(c *gin.Context) {
  428. email := c.Param("email")
  429. var body attachDetachBody
  430. if err := c.ShouldBindJSON(&body); err != nil {
  431. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  432. return
  433. }
  434. needRestart, err := a.clientService.DetachByEmailMany(&a.inboundService, email, body.InboundIds)
  435. if err != nil {
  436. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  437. return
  438. }
  439. jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientDeleteSuccess"), pendingNodeObj(a.inboundService.AnyNodePending(body.InboundIds)), nil)
  440. if needRestart {
  441. a.xrayService.SetToNeedRestart()
  442. }
  443. notifyClientsChanged()
  444. }
  445. type bulkResetRequest struct {
  446. Emails []string `json:"emails"`
  447. }
  448. func (a *ClientController) bulkResetTraffic(c *gin.Context) {
  449. var req bulkResetRequest
  450. if err := c.ShouldBindJSON(&req); err != nil {
  451. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  452. return
  453. }
  454. affected, err := a.clientService.BulkResetTraffic(&a.inboundService, req.Emails)
  455. if err != nil {
  456. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  457. return
  458. }
  459. jsonObj(c, gin.H{"affected": affected}, nil)
  460. a.xrayService.SetToNeedRestart()
  461. notifyClientsChanged()
  462. }