1
0

outbound.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package service
  2. import (
  3. "x-ui/database"
  4. "x-ui/database/model"
  5. "x-ui/logger"
  6. "x-ui/xray"
  7. "gorm.io/gorm"
  8. )
  9. type OutboundService struct{}
  10. func (s *OutboundService) AddTraffic(traffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (error, bool) {
  11. var err error
  12. db := database.GetDB()
  13. tx := db.Begin()
  14. defer func() {
  15. if err != nil {
  16. tx.Rollback()
  17. } else {
  18. tx.Commit()
  19. }
  20. }()
  21. err = s.addOutboundTraffic(tx, traffics)
  22. if err != nil {
  23. return err, false
  24. }
  25. return nil, false
  26. }
  27. func (s *OutboundService) addOutboundTraffic(tx *gorm.DB, traffics []*xray.Traffic) error {
  28. if len(traffics) == 0 {
  29. return nil
  30. }
  31. var err error
  32. for _, traffic := range traffics {
  33. if traffic.IsOutbound {
  34. var outbound model.OutboundTraffics
  35. err = tx.Model(&model.OutboundTraffics{}).Where("tag = ?", traffic.Tag).
  36. FirstOrCreate(&outbound).Error
  37. if err != nil {
  38. return err
  39. }
  40. outbound.Tag = traffic.Tag
  41. outbound.Up = outbound.Up + traffic.Up
  42. outbound.Down = outbound.Down + traffic.Down
  43. outbound.Total = outbound.Up + outbound.Down
  44. err = tx.Save(&outbound).Error
  45. if err != nil {
  46. return err
  47. }
  48. }
  49. }
  50. return nil
  51. }
  52. func (s *OutboundService) GetOutboundsTraffic() ([]*model.OutboundTraffics, error) {
  53. db := database.GetDB()
  54. var traffics []*model.OutboundTraffics
  55. err := db.Model(model.OutboundTraffics{}).Find(&traffics).Error
  56. if err != nil {
  57. logger.Warning("Error retrieving OutboundTraffics: ", err)
  58. return nil, err
  59. }
  60. return traffics, nil
  61. }
  62. func (s *OutboundService) ResetOutboundTraffic(tag string) error {
  63. db := database.GetDB()
  64. whereText := "tag "
  65. if tag == "-alltags-" {
  66. whereText += " <> ?"
  67. } else {
  68. whereText += " = ?"
  69. }
  70. result := db.Model(model.OutboundTraffics{}).
  71. Where(whereText, tag).
  72. Updates(map[string]interface{}{"up": 0, "down": 0, "total": 0})
  73. err := result.Error
  74. if err != nil {
  75. return err
  76. }
  77. return nil
  78. }