diff --git a/database/model/model.go b/database/model/model.go index 856f66df..dcb795c7 100644 --- a/database/model/model.go +++ b/database/model/model.go @@ -27,16 +27,18 @@ type User struct { } type Inbound struct { - Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"` - UserId int `json:"-"` - Up int64 `json:"up" form:"up"` - Down int64 `json:"down" form:"down"` - Total int64 `json:"total" form:"total"` - AllTime int64 `json:"allTime" form:"allTime" gorm:"default:0"` - Remark string `json:"remark" form:"remark"` - Enable bool `json:"enable" form:"enable"` - ExpiryTime int64 `json:"expiryTime" form:"expiryTime"` - ClientStats []xray.ClientTraffic `gorm:"foreignKey:InboundId;references:Id" json:"clientStats" form:"clientStats"` + Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"` + UserId int `json:"-"` + Up int64 `json:"up" form:"up"` + Down int64 `json:"down" form:"down"` + Total int64 `json:"total" form:"total"` + AllTime int64 `json:"allTime" form:"allTime" gorm:"default:0"` + Remark string `json:"remark" form:"remark"` + Enable bool `json:"enable" form:"enable" gorm:"index:idx_enable_traffic_reset,priority:1"` + ExpiryTime int64 `json:"expiryTime" form:"expiryTime"` + TrafficReset string `json:"trafficReset" form:"trafficReset" gorm:"default:never;index:idx_enable_traffic_reset,priority:2"` + LastTrafficResetTime int64 `json:"lastTrafficResetTime" form:"lastTrafficResetTime" gorm:"default:0"` + ClientStats []xray.ClientTraffic `gorm:"foreignKey:InboundId;references:Id" json:"clientStats" form:"clientStats"` // config part Listen string `json:"listen" form:"listen"` diff --git a/web/assets/js/model/dbinbound.js b/web/assets/js/model/dbinbound.js index 1added25..befc618e 100644 --- a/web/assets/js/model/dbinbound.js +++ b/web/assets/js/model/dbinbound.js @@ -10,6 +10,8 @@ class DBInbound { this.remark = ""; this.enable = true; this.expiryTime = 0; + this.trafficReset = "never"; + this.lastTrafficResetTime = 0; this.listen = ""; this.port = 0; diff --git a/web/html/form/inbound.html b/web/html/form/inbound.html index 69f5fbb3..ca4dc66a 100644 --- a/web/html/form/inbound.html +++ b/web/html/form/inbound.html @@ -44,6 +44,30 @@ + + + + {{ i18n "pages.inbounds.periodicTrafficReset.never" }} + {{ i18n "pages.inbounds.periodicTrafficReset.daily" }} + {{ i18n "pages.inbounds.periodicTrafficReset.weekly" }} + {{ i18n "pages.inbounds.periodicTrafficReset.monthly" }} + + + @@ -951,6 +957,8 @@ remark: dbInbound.remark + " - Cloned", enable: dbInbound.enable, expiryTime: dbInbound.expiryTime, + trafficReset: dbInbound.trafficReset, + lastTrafficResetTime: dbInbound.lastTrafficResetTime, listen: '', port: RandomUtil.randomInteger(10000, 60000), @@ -995,6 +1003,8 @@ remark: dbInbound.remark, enable: dbInbound.enable, expiryTime: dbInbound.expiryTime, + trafficReset: dbInbound.trafficReset, + lastTrafficResetTime: dbInbound.lastTrafficResetTime, listen: inbound.listen, port: inbound.port, @@ -1018,6 +1028,8 @@ remark: dbInbound.remark, enable: dbInbound.enable, expiryTime: dbInbound.expiryTime, + trafficReset: dbInbound.trafficReset, + lastTrafficResetTime: dbInbound.lastTrafficResetTime, listen: inbound.listen, port: inbound.port, diff --git a/web/job/periodic_traffic_reset_job.go b/web/job/periodic_traffic_reset_job.go new file mode 100644 index 00000000..5d3cd178 --- /dev/null +++ b/web/job/periodic_traffic_reset_job.go @@ -0,0 +1,44 @@ +package job + +import ( + "x-ui/logger" + "x-ui/web/service" +) + +type Period string + +type PeriodicTrafficResetJob struct { + inboundService service.InboundService + period Period +} + +func NewPeriodicTrafficResetJob(period Period) *PeriodicTrafficResetJob { + return &PeriodicTrafficResetJob{ + period: period, + } +} + +func (j *PeriodicTrafficResetJob) Run() { + inbounds, err := j.inboundService.GetInboundsByTrafficReset(string(j.period)) + logger.Infof("Running periodic traffic reset job for period: %s", j.period) + if err != nil { + logger.Warning("Failed to get inbounds for traffic reset:", err) + return + } + + resetCount := 0 + + for _, inbound := range inbounds { + if err := j.inboundService.ResetAllClientTraffics(inbound.Id); err != nil { + logger.Warning("Failed to reset traffic for inbound", inbound.Id, ":", err) + continue + } + + resetCount++ + logger.Infof("Reset traffic for inbound %d (%s)", inbound.Id, inbound.Remark) + } + + if resetCount > 0 { + logger.Infof("Periodic traffic reset completed: %d inbounds reseted", resetCount) + } +} diff --git a/web/service/inbound.go b/web/service/inbound.go index 2646b1e7..9d2e09dd 100644 --- a/web/service/inbound.go +++ b/web/service/inbound.go @@ -41,6 +41,16 @@ func (s *InboundService) GetAllInbounds() ([]*model.Inbound, error) { return inbounds, nil } +func (s *InboundService) GetInboundsByTrafficReset(period string) ([]*model.Inbound, error) { + db := database.GetDB() + var inbounds []*model.Inbound + err := db.Model(model.Inbound{}).Where("traffic_reset = ?", period).Find(&inbounds).Error + if err != nil && err != gorm.ErrRecordNotFound { + return nil, err + } + return inbounds, nil +} + func (s *InboundService) checkPortExist(listen string, port int, ignoreId int) (bool, error) { db := database.GetDB() if listen == "" || listen == "0.0.0.0" || listen == "::" || listen == "::0" { @@ -409,6 +419,7 @@ func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, oldInbound.Remark = inbound.Remark oldInbound.Enable = inbound.Enable oldInbound.ExpiryTime = inbound.ExpiryTime + oldInbound.TrafficReset = inbound.TrafficReset oldInbound.Listen = inbound.Listen oldInbound.Port = inbound.Port oldInbound.Protocol = inbound.Protocol @@ -698,6 +709,7 @@ func (s *InboundService) DelInboundClient(inboundId int, clientId string) (bool, } func (s *InboundService) UpdateInboundClient(data *model.Inbound, clientId string) (bool, error) { + // TODO: check if TrafficReset field is updating clients, err := s.GetClients(data) if err != nil { return false, err @@ -1684,6 +1696,7 @@ func (s *InboundService) ResetClientTrafficLimitByEmail(clientEmail string, tota func (s *InboundService) ResetClientTrafficByEmail(clientEmail string) error { db := database.GetDB() + // Reset traffic stats in ClientTraffic table result := db.Model(xray.ClientTraffic{}). Where("email = ?", clientEmail). Updates(map[string]any{"enable": true, "up": 0, "down": 0}) @@ -1692,6 +1705,7 @@ func (s *InboundService) ResetClientTrafficByEmail(clientEmail string) error { if err != nil { return err } + return nil } @@ -1759,20 +1773,39 @@ func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (bool, e func (s *InboundService) ResetAllClientTraffics(id int) error { db := database.GetDB() + now := time.Now().Unix() * 1000 - whereText := "inbound_id " - if id == -1 { - whereText += " > ?" - } else { - whereText += " = ?" - } + return db.Transaction(func(tx *gorm.DB) error { + whereText := "inbound_id " + if id == -1 { + whereText += " > ?" + } else { + whereText += " = ?" + } - result := db.Model(xray.ClientTraffic{}). - Where(whereText, id). - Updates(map[string]any{"enable": true, "up": 0, "down": 0}) + // Reset client traffics + result := tx.Model(xray.ClientTraffic{}). + Where(whereText, id). + Updates(map[string]any{"enable": true, "up": 0, "down": 0}) - err := result.Error - return err + if result.Error != nil { + return result.Error + } + + // Update lastTrafficResetTime for the inbound(s) + inboundWhereText := "id " + if id == -1 { + inboundWhereText += " > ?" + } else { + inboundWhereText += " = ?" + } + + result = tx.Model(model.Inbound{}). + Where(inboundWhereText, id). + Update("last_traffic_reset_time", now) + + return result.Error + }) } func (s *InboundService) ResetAllTraffics() error { diff --git a/web/translation/translate.ar_EG.toml b/web/translation/translate.ar_EG.toml index 036fbeb9..17728ca1 100644 --- a/web/translation/translate.ar_EG.toml +++ b/web/translation/translate.ar_EG.toml @@ -244,6 +244,7 @@ "exportInbound" = "تصدير الإدخال" "import" = "استيراد" "importInbound" = "استيراد إدخال" +"lastReset" = "آخر إعادة تعيين" [pages.client] "add" = "أضف عميل" @@ -262,6 +263,14 @@ "days" = "يوم/أيام" "renew" = "تجديد تلقائي" "renewDesc" = "تجديد تلقائي بعد انتهاء الصلاحية. (0 = تعطيل)(الوحدة: يوم)" +"periodicTrafficResetTitle" = "إعادة تعيين حركة المرور" +"periodicTrafficResetDesc" = "إعادة تعيين عداد حركة المرور تلقائيًا في فترات محددة" + +[pages.inbounds.periodicTrafficReset] +"never" = "أبداً" +"daily" = "يومياً" +"weekly" = "أسبوعياً" +"monthly" = "شهرياً" [pages.inbounds.toasts] "obtain" = "تم الحصول عليه" diff --git a/web/translation/translate.en_US.toml b/web/translation/translate.en_US.toml index 19ac810c..5a3735dd 100644 --- a/web/translation/translate.en_US.toml +++ b/web/translation/translate.en_US.toml @@ -244,6 +244,9 @@ "exportInbound" = "Export Inbound" "import" = "Import" "importInbound" = "Import an Inbound" +"periodicTrafficResetTitle" = "Traffic Reset" +"periodicTrafficResetDesc" = "Automatically reset traffic counter at specified intervals" +"lastReset" = "Last Reset" [pages.client] "add" = "Add Client" @@ -263,6 +266,12 @@ "renew" = "Auto Renew" "renewDesc" = "Auto-renewal after expiration. (0 = disable)(unit: day)" +[pages.inbounds.periodicTrafficReset] +"never" = "Never" +"daily" = "Daily" +"weekly" = "Weekly" +"monthly" = "Monthly" + [pages.inbounds.toasts] "obtain" = "Obtain" "updateSuccess" = "The update was successful." diff --git a/web/translation/translate.es_ES.toml b/web/translation/translate.es_ES.toml index 89226b32..37f3d680 100644 --- a/web/translation/translate.es_ES.toml +++ b/web/translation/translate.es_ES.toml @@ -244,6 +244,7 @@ "exportInbound" = "Exportación entrante" "import" = "Importar" "importInbound" = "Importar un entrante" +"lastReset" = "Último reinicio" [pages.client] "add" = "Agregar Cliente" @@ -262,6 +263,14 @@ "days" = "Día(s)" "renew" = "Renovación automática" "renewDesc" = "Renovación automática después de la expiración. (0 = desactivar) (unidad: día)" +"periodicTrafficResetTitle" = "Reset de Tráfico" +"periodicTrafficResetDesc" = "Reiniciar automáticamente el contador de tráfico en intervalos especificados" + +[pages.inbounds.periodicTrafficReset] +"never" = "Nunca" +"daily" = "Diariamente" +"weekly" = "Semanalmente" +"monthly" = "Mensualmente" [pages.inbounds.toasts] "obtain" = "Recibir" diff --git a/web/translation/translate.fa_IR.toml b/web/translation/translate.fa_IR.toml index 2bbcb39e..0ad48ae4 100644 --- a/web/translation/translate.fa_IR.toml +++ b/web/translation/translate.fa_IR.toml @@ -244,6 +244,7 @@ "exportInbound" = "استخراج ورودی" "import" = "افزودن" "importInbound" = "افزودن یک ورودی" +"lastReset" = "آخرین بازنشانی" [pages.client] "add" = "کاربر جدید" @@ -261,7 +262,15 @@ "expireDays" = "مدت زمان" "days" = "(روز)" "renew" = "تمدید خودکار" -"renewDesc" = "(تمدید خودکار پس‌از ‌انقضا. (0 = غیرفعال)(واحد: روز" +"renewDesc" = "تمدید خودکار پس‌از ‌انقضا. (0 = غیرفعال)(واحد: روز)" +"periodicTrafficResetTitle" = "بازنشانی ترافیک" +"periodicTrafficResetDesc" = "بازنشانی خودکار شمارنده ترافیک در فواصل زمانی مشخص" + +[pages.inbounds.periodicTrafficReset] +"never" = "هرگز" +"daily" = "روزانه" +"weekly" = "هفتگی" +"monthly" = "ماهانه" [pages.inbounds.toasts] "obtain" = "فراهم‌سازی" diff --git a/web/translation/translate.id_ID.toml b/web/translation/translate.id_ID.toml index 0977c6e6..ebaee48b 100644 --- a/web/translation/translate.id_ID.toml +++ b/web/translation/translate.id_ID.toml @@ -244,6 +244,7 @@ "exportInbound" = "Ekspor Masuk" "import" = "Impor" "importInbound" = "Impor Masuk" +"lastReset" = "Reset Terakhir" [pages.client] "add" = "Tambah Klien" @@ -262,6 +263,14 @@ "days" = "Hari" "renew" = "Perpanjang Otomatis" "renewDesc" = "Perpanjangan otomatis setelah kedaluwarsa. (0 = nonaktif)(unit: hari)" +"periodicTrafficResetTitle" = "Reset Trafik Berkala" +"periodicTrafficResetDesc" = "Reset otomatis penghitung trafik pada interval tertentu" + +[pages.inbounds.periodicTrafficReset] +"never" = "Tidak Pernah" +"daily" = "Harian" +"weekly" = "Mingguan" +"monthly" = "Bulanan" [pages.inbounds.toasts] "obtain" = "Dapatkan" diff --git a/web/translation/translate.ja_JP.toml b/web/translation/translate.ja_JP.toml index e807ee03..037fb9a1 100644 --- a/web/translation/translate.ja_JP.toml +++ b/web/translation/translate.ja_JP.toml @@ -244,6 +244,7 @@ "exportInbound" = "インバウンドルールをエクスポート" "import" = "インポート" "importInbound" = "インバウンドルールをインポート" +"lastReset" = "最後のリセット" [pages.client] "add" = "クライアント追加" @@ -262,6 +263,14 @@ "days" = "日" "renew" = "自動更新" "renewDesc" = "期限が切れた後に自動更新。(0 = 無効)(単位:日)" +"periodicTrafficResetTitle" = "トラフィックリセット" +"periodicTrafficResetDesc" = "指定された間隔でトラフィックカウンタを自動的にリセット" + +[pages.inbounds.periodicTrafficReset] +"never" = "なし" +"daily" = "毎日" +"weekly" = "毎週" +"monthly" = "毎月" [pages.inbounds.toasts] "obtain" = "取得" diff --git a/web/translation/translate.pt_BR.toml b/web/translation/translate.pt_BR.toml index 5640f4ff..77105d34 100644 --- a/web/translation/translate.pt_BR.toml +++ b/web/translation/translate.pt_BR.toml @@ -244,6 +244,7 @@ "exportInbound" = "Exportar Inbound" "import" = "Importar" "importInbound" = "Importar um Inbound" +"lastReset" = "Último Reset" [pages.client] "add" = "Adicionar Cliente" @@ -262,6 +263,14 @@ "days" = "Dia(s)" "renew" = "Renovação Automática" "renewDesc" = "Renovação automática após expiração. (0 = desativado)(unidade: dia)" +"periodicTrafficResetTitle" = "Reset de Tráfego" +"periodicTrafficResetDesc" = "Reinicia automaticamente o contador de tráfego em intervalos especificados" + +[pages.inbounds.periodicTrafficReset] +"never" = "Nunca" +"daily" = "Diariamente" +"weekly" = "Semanalmente" +"monthly" = "Mensalmente" [pages.inbounds.toasts] "obtain" = "Obter" diff --git a/web/translation/translate.ru_RU.toml b/web/translation/translate.ru_RU.toml index c3f0579e..dcfb9991 100644 --- a/web/translation/translate.ru_RU.toml +++ b/web/translation/translate.ru_RU.toml @@ -262,6 +262,15 @@ "days" = "дней" "renew" = "Автопродление" "renewDesc" = "Автопродление после истечения срока действия. (0 = отключить)(единица: день)" +"periodicTrafficResetTitle" = "Сброс трафика" +"periodicTrafficResetDesc" = "Автоматический сброс счетчика трафика через указанные интервалы" +"lastReset" = "Последний сброс" + +[pages.inbounds.periodicTrafficReset] +"never" = "Никогда" +"daily" = "Ежедневно" +"weekly" = "Еженедельно" +"monthly" = "Ежемесячно" [pages.inbounds.toasts] "obtain" = "Получить" diff --git a/web/translation/translate.tr_TR.toml b/web/translation/translate.tr_TR.toml index 452e4b7d..ed5fcea7 100644 --- a/web/translation/translate.tr_TR.toml +++ b/web/translation/translate.tr_TR.toml @@ -244,6 +244,7 @@ "exportInbound" = "Geleni Dışa Aktar" "import" = "İçe Aktar" "importInbound" = "Bir Gelen İçe Aktar" +"lastReset" = "Son Sıfırlama" [pages.client] "add" = "Müşteri Ekle" @@ -262,6 +263,14 @@ "days" = "Gün" "renew" = "Otomatik Yenile" "renewDesc" = "Süresi dolduktan sonra otomatik yenileme. (0 = devre dışı)(birim: gün)" +"periodicTrafficResetTitle" = "Trafik Sıfırlama" +"periodicTrafficResetDesc" = "Belirtilen aralıklarla trafik sayacını otomatik olarak sıfırla" + +[pages.inbounds.periodicTrafficReset] +"never" = "Asla" +"daily" = "Günlük" +"weekly" = "Haftalık" +"monthly" = "Aylık" [pages.inbounds.toasts] "obtain" = "Elde Et" diff --git a/web/translation/translate.uk_UA.toml b/web/translation/translate.uk_UA.toml index 826ced0d..3eae3e34 100644 --- a/web/translation/translate.uk_UA.toml +++ b/web/translation/translate.uk_UA.toml @@ -244,6 +244,7 @@ "exportInbound" = "Експортувати вхідні" "import" = "Імпорт" "importInbound" = "Імпортувати вхідний" +"lastReset" = "Останнє скидання" [pages.client] "add" = "Додати клієнта" @@ -262,6 +263,14 @@ "days" = "Дні(в)" "renew" = "Автоматичне оновлення" "renewDesc" = "Автоматичне поновлення після закінчення терміну дії. (0 = вимкнено)(одиниця: день)" +"periodicTrafficResetTitle" = "Скидання трафіку" +"periodicTrafficResetDesc" = "Автоматично скидати лічильник трафіку через певні проміжки часу" + +[pages.inbounds.periodicTrafficReset] +"never" = "Ніколи" +"daily" = "Щодня" +"weekly" = "Щотижня" +"monthly" = "Щомісяця" [pages.inbounds.toasts] "obtain" = "Отримати" diff --git a/web/translation/translate.vi_VN.toml b/web/translation/translate.vi_VN.toml index 7e3869a0..5dd826aa 100644 --- a/web/translation/translate.vi_VN.toml +++ b/web/translation/translate.vi_VN.toml @@ -244,6 +244,7 @@ "exportInbound" = "Xuất nhập khẩu" "import" = "Nhập" "importInbound" = "Nhập inbound" +"lastReset" = "Đặt lại lần cuối" [pages.client] "add" = "Thêm người dùng" @@ -262,6 +263,14 @@ "days" = "ngày" "renew" = "Tự động gia hạn" "renewDesc" = "Tự động gia hạn sau khi hết hạn. (0 = tắt)(đơn vị: ngày)" +"periodicTrafficResetTitle" = "Đặt lại lưu lượng" +"periodicTrafficResetDesc" = "Tự động đặt lại bộ đếm lưu lượng theo khoảng thời gian xác định" + +[pages.inbounds.periodicTrafficReset] +"never" = "Không bao giờ" +"daily" = "Hàng ngày" +"weekly" = "Hàng tuần" +"monthly" = "Hàng tháng" [pages.inbounds.toasts] "obtain" = "Nhận" diff --git a/web/translation/translate.zh_CN.toml b/web/translation/translate.zh_CN.toml index 18a8c97c..5ea23807 100644 --- a/web/translation/translate.zh_CN.toml +++ b/web/translation/translate.zh_CN.toml @@ -244,6 +244,7 @@ "exportInbound" = "导出入站规则" "import"="导入" "importInbound" = "导入入站规则" +"lastReset" = "上次重置" [pages.client] "add" = "添加客户端" @@ -262,6 +263,14 @@ "days" = "天" "renew" = "自动续订" "renewDesc" = "到期后自动续订。(0 = 禁用)(单位: 天)" +"periodicTrafficResetTitle" = "流量重置" +"periodicTrafficResetDesc" = "按指定间隔自动重置流量计数器" + +[pages.inbounds.periodicTrafficReset] +"never" = "从不" +"daily" = "每日" +"weekly" = "每周" +"monthly" = "每月" [pages.inbounds.toasts] "obtain" = "获取" diff --git a/web/translation/translate.zh_TW.toml b/web/translation/translate.zh_TW.toml index 758781e7..91ecb286 100644 --- a/web/translation/translate.zh_TW.toml +++ b/web/translation/translate.zh_TW.toml @@ -244,6 +244,7 @@ "exportInbound" = "匯出入站規則" "import"="匯入" "importInbound" = "匯入入站規則" +"lastReset" = "上次重置" [pages.client] "add" = "新增客戶端" @@ -262,6 +263,14 @@ "days" = "天" "renew" = "自動續訂" "renewDesc" = "到期後自動續訂。(0 = 禁用)(單位: 天)" +"periodicTrafficResetTitle" = "流量重置" +"periodicTrafficResetDesc" = "按指定間隔自動重置流量計數器" + +[pages.inbounds.periodicTrafficReset] +"never" = "從不" +"daily" = "每日" +"weekly" = "每週" +"monthly" = "每月" [pages.inbounds.toasts] "obtain" = "獲取" diff --git a/web/web.go b/web/web.go index cfd4de5f..d381539d 100644 --- a/web/web.go +++ b/web/web.go @@ -289,6 +289,19 @@ func (s *Server) startTask() { // check client ips from log file every day s.cron.AddJob("@daily", job.NewClearLogsJob()) + // Periodic traffic resets + logger.Info("Scheduling periodic traffic reset jobs") + { + // Inbound traffic reset jobs + // Run once a day, midnight + s.cron.AddJob("@daily", job.NewPeriodicTrafficResetJob("daily")) + // Run once a week, midnight between Sat/Sun + s.cron.AddJob("@weekly", job.NewPeriodicTrafficResetJob("weekly")) + // Run once a month, midnight, first of month + s.cron.AddJob("@monthly", job.NewPeriodicTrafficResetJob("monthly")) + + } + // Make a traffic condition every day, 8:30 var entry cron.EntryID isTgbotenabled, err := s.settingService.GetTgbotEnabled()