Compare commits

...

6 commits

22 changed files with 78 additions and 169 deletions

View file

@ -34,9 +34,9 @@ type Inbound struct {
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"`
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"`
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"`
@ -100,8 +100,6 @@ type Client struct {
LimitIP int `json:"limitIp"`
TotalGB int64 `json:"totalGB" form:"totalGB"`
ExpiryTime int64 `json:"expiryTime" form:"expiryTime"`
TrafficReset string `json:"trafficReset" form:"trafficReset" gorm:"default:never"`
LastTrafficResetTime int64 `json:"lastTrafficResetTime" form:"lastTrafficResetTime" gorm:"default:0"`
Enable bool `json:"enable" form:"enable"`
TgID int64 `json:"tgId" form:"tgId"`
SubID string `json:"subId" form:"subId"`

View file

@ -10,7 +10,8 @@ class DBInbound {
this.remark = "";
this.enable = true;
this.expiryTime = 0;
this.periodicTrafficReset = "never";
this.trafficReset = "never";
this.lastTrafficResetTime = 0;
this.listen = "";
this.port = 0;

View file

@ -49,12 +49,18 @@
<a-tooltip>
<template slot="title">
<span>{{ i18n "pages.inbounds.periodicTrafficResetDesc" }}</span>
<br v-if="dbInbound.lastTrafficResetTime && dbInbound.lastTrafficResetTime > 0">
<span v-if="dbInbound.lastTrafficResetTime && dbInbound.lastTrafficResetTime > 0">
<strong>{{ i18n "pages.inbounds.lastReset" }}:</strong>
<span v-if="datepicker == 'gregorian'">[[ moment(dbInbound.lastTrafficResetTime).format('YYYY-MM-DD HH:mm:ss') ]]</span>
<span v-else>[[ DateUtil.convertToJalalian(moment(dbInbound.lastTrafficResetTime)) ]]</span>
</span>
</template>
{{ i18n "pages.inbounds.periodicTrafficResetTitle" }}
<a-icon type="question-circle"></a-icon>
</a-tooltip>
</template>
<a-select v-model="dbInbound.periodicTrafficReset" :dropdown-class-name="themeSwitcher.currentTheme">
<a-select v-model="dbInbound.trafficReset" :dropdown-class-name="themeSwitcher.currentTheme">
<a-select-option value="never">{{ i18n "pages.inbounds.periodicTrafficReset.never" }}</a-select-option>
<a-select-option value="daily">{{ i18n "pages.inbounds.periodicTrafficReset.daily" }}</a-select-option>
<a-select-option value="weekly">{{ i18n "pages.inbounds.periodicTrafficReset.weekly" }}</a-select-option>

View file

@ -648,7 +648,7 @@
<tr>
<td>{{ i18n "pages.inbounds.periodicTrafficResetTitle" }}</td>
<td>
<a-tag color="blue">[[ i18n("pages.inbounds.periodicTrafficReset." + dbInbound.periodicTrafficReset) ]]</a-tag>
<a-tag color="blue">[[ i18n("pages.inbounds.periodicTrafficReset." + dbInbound.trafficReset) ]]</a-tag>
</td>
</tr>
</table>
@ -1097,7 +1097,8 @@
remark: dbInbound.remark + " - Cloned",
enable: dbInbound.enable,
expiryTime: dbInbound.expiryTime,
periodicTrafficReset: dbInbound.periodicTrafficReset,
trafficReset: dbInbound.trafficReset,
lastTrafficResetTime: dbInbound.lastTrafficResetTime,
listen: '',
port: RandomUtil.randomInteger(10000, 60000),
@ -1142,7 +1143,8 @@
remark: dbInbound.remark,
enable: dbInbound.enable,
expiryTime: dbInbound.expiryTime,
periodicTrafficReset: dbInbound.periodicTrafficReset,
trafficReset: dbInbound.trafficReset,
lastTrafficResetTime: dbInbound.lastTrafficResetTime,
listen: inbound.listen,
port: inbound.port,
@ -1166,7 +1168,8 @@
remark: dbInbound.remark,
enable: dbInbound.enable,
expiryTime: dbInbound.expiryTime,
periodicTrafficReset: dbInbound.periodicTrafficReset,
trafficReset: dbInbound.trafficReset,
lastTrafficResetTime: dbInbound.lastTrafficResetTime,
listen: inbound.listen,
port: inbound.port,

View file

@ -237,12 +237,6 @@
</a-tooltip>
</td>
</tr>
<tr v-if="infoModal.clientSettings.periodicTrafficReset">
<td>{{ i18n "pages.inbounds.periodicTrafficResetTitle" }}</td>
<td>
<a-tag color="blue">[[ i18n("pages.inbounds.periodicTrafficReset." + infoModal.clientSettings.periodicTrafficReset) ]]</a-tag>
</td>
</tr>
<tr v-if="app.ipLimitEnable">
<td>{{ i18n "pages.inbounds.IPLimit" }}</td>
<td>

View file

@ -1,42 +0,0 @@
package job
import (
"x-ui/logger"
"x-ui/web/service"
)
type PeriodicClientTrafficResetJob struct {
inboundService service.InboundService
period Period
}
func NewPeriodicClientTrafficResetJob(period Period) *PeriodicClientTrafficResetJob {
return &PeriodicClientTrafficResetJob{
period: period,
}
}
func (j *PeriodicClientTrafficResetJob) Run() {
clients, err := j.inboundService.GetClientsByTrafficReset(string(j.period))
logger.Infof("Running periodic client traffic reset job for period: %s", j.period)
if err != nil {
logger.Warning("Failed to get clients for traffic reset:", err)
return
}
resetCount := 0
for _, client := range clients {
if err := j.inboundService.ResetClientTrafficByEmail(client.Email); err != nil {
logger.Warning("Failed to reset traffic for client", client.Email, ":", err)
continue
}
resetCount++
logger.Infof("Reset traffic for client %s", client.Email)
}
if resetCount > 0 {
logger.Infof("Periodic client traffic reset completed: %d clients reset", resetCount)
}
}

View file

@ -39,6 +39,6 @@ func (j *PeriodicTrafficResetJob) Run() {
}
if resetCount > 0 {
logger.Infof("Periodic traffic reset completed: %d inbounds reset", resetCount)
logger.Infof("Periodic traffic reset completed: %d inbounds reseted", resetCount)
}
}

View file

@ -51,36 +51,6 @@ func (s *InboundService) GetInboundsByTrafficReset(period string) ([]*model.Inbo
return inbounds, nil
}
func (s *InboundService) GetClientsByTrafficReset(period string) ([]model.Client, error) {
db := database.GetDB()
var inbounds []*model.Inbound
// Get all inbounds first
err := db.Model(model.Inbound{}).Find(&inbounds).Error
if err != nil {
return nil, err
}
var clientsWithReset []model.Client
// Parse each inbound's settings to find clients with matching traffic reset period
for _, inbound := range inbounds {
clients, err := s.GetClients(inbound)
if err != nil {
logger.Warning("Failed to get clients for inbound", inbound.Id, ":", err)
continue
}
for _, client := range clients {
if client.TrafficReset == period {
clientsWithReset = append(clientsWithReset, client)
}
}
}
return clientsWithReset, 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" {
@ -1736,47 +1706,6 @@ func (s *InboundService) ResetClientTrafficByEmail(clientEmail string) error {
return err
}
// Update lastTrafficResetTime in client settings
_, inbound, err := s.GetClientInboundByEmail(clientEmail)
if err != nil {
logger.Warning("Failed to get inbound for client", clientEmail, ":", err)
return nil // Don't fail the reset if we can't update the timestamp
}
if inbound != nil {
var settings map[string]any
err = json.Unmarshal([]byte(inbound.Settings), &settings)
if err != nil {
logger.Warning("Failed to parse inbound settings:", err)
return nil
}
clientsSettings := settings["clients"].([]any)
now := time.Now().Unix() * 1000
for client_index := range clientsSettings {
c := clientsSettings[client_index].(map[string]any)
if c["email"] == clientEmail {
c["lastTrafficResetTime"] = now
c["updated_at"] = now
break
}
}
settings["clients"] = clientsSettings
modifiedSettings, err := json.MarshalIndent(settings, "", " ")
if err != nil {
logger.Warning("Failed to marshal inbound settings:", err)
return nil
}
inbound.Settings = string(modifiedSettings)
err = db.Save(inbound).Error
if err != nil {
logger.Warning("Failed to save inbound with updated client settings:", err)
}
}
return nil
}
@ -1844,7 +1773,9 @@ 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
return db.Transaction(func(tx *gorm.DB) error {
whereText := "inbound_id "
if id == -1 {
whereText += " > ?"
@ -1852,12 +1783,29 @@ func (s *InboundService) ResetAllClientTraffics(id int) error {
whereText += " = ?"
}
result := db.Model(xray.ClientTraffic{}).
// 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 {

View file

@ -230,6 +230,7 @@
"exportInbound" = "تصدير الإدخال"
"import" = "استيراد"
"importInbound" = "استيراد إدخال"
"lastReset" = "آخر إعادة تعيين"
[pages.client]
"add" = "أضف عميل"

View file

@ -232,6 +232,7 @@
"importInbound" = "Import an Inbound"
"periodicTrafficResetTitle" = "Traffic Reset"
"periodicTrafficResetDesc" = "Automatically reset traffic counter at specified intervals"
"lastReset" = "Last Reset"
[pages.client]
"add" = "Add Client"

View file

@ -230,6 +230,7 @@
"exportInbound" = "Exportación entrante"
"import" = "Importar"
"importInbound" = "Importar un entrante"
"lastReset" = "Último reinicio"
[pages.client]
"add" = "Agregar Cliente"

View file

@ -230,6 +230,7 @@
"exportInbound" = "استخراج ورودی"
"import" = "افزودن"
"importInbound" = "افزودن یک ورودی"
"lastReset" = "آخرین بازنشانی"
[pages.client]
"add" = "کاربر جدید"

View file

@ -230,6 +230,7 @@
"exportInbound" = "Ekspor Masuk"
"import" = "Impor"
"importInbound" = "Impor Masuk"
"lastReset" = "Reset Terakhir"
[pages.client]
"add" = "Tambah Klien"

View file

@ -230,6 +230,7 @@
"exportInbound" = "インバウンドルールをエクスポート"
"import" = "インポート"
"importInbound" = "インバウンドルールをインポート"
"lastReset" = "最後のリセット"
[pages.client]
"add" = "クライアント追加"

View file

@ -230,6 +230,7 @@
"exportInbound" = "Exportar Inbound"
"import" = "Importar"
"importInbound" = "Importar um Inbound"
"lastReset" = "Último Reset"
[pages.client]
"add" = "Adicionar Cliente"

View file

@ -250,6 +250,7 @@
"renewDesc" = "Автопродление после истечения срока действия. (0 = отключить)(единица: день)"
"periodicTrafficResetTitle" = "Сброс трафика"
"periodicTrafficResetDesc" = "Автоматический сброс счетчика трафика через указанные интервалы"
"lastReset" = "Последний сброс"
[pages.inbounds.periodicTrafficReset]
"never" = "Никогда"

View file

@ -230,6 +230,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"

View file

@ -230,6 +230,7 @@
"exportInbound" = "Експортувати вхідні"
"import" = "Імпорт"
"importInbound" = "Імпортувати вхідний"
"lastReset" = "Останнє скидання"
[pages.client]
"add" = "Додати клієнта"

View file

@ -230,6 +230,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"

View file

@ -230,6 +230,7 @@
"exportInbound" = "导出入站规则"
"import"="导入"
"importInbound" = "导入入站规则"
"lastReset" = "上次重置"
[pages.client]
"add" = "添加客户端"

View file

@ -230,6 +230,7 @@
"exportInbound" = "匯出入站規則"
"import"="匯入"
"importInbound" = "匯入入站規則"
"lastReset" = "上次重置"
[pages.client]
"add" = "新增客戶端"

View file

@ -271,24 +271,12 @@ func (s *Server) startTask() {
{
// Inbound traffic reset jobs
// Run once a day, midnight
// TODO: for testing, run every minute, change back to daily later
// s.cron.AddJob("@daily", job.NewPeriodicTrafficResetJob("daily"))
s.cron.AddJob("* * * * *", job.NewPeriodicTrafficResetJob("daily"))
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"))
// Client traffic reset jobs
logger.Info("Scheduling periodic client traffic reset jobs")
// Run once a day, midnight
// TODO: for testing, run every minute, change back to daily later
// s.cron.AddJob("@daily", job.NewPeriodicClientTrafficResetJob("daily"))
s.cron.AddJob("* * * * *", job.NewPeriodicClientTrafficResetJob("daily"))
// Run once a week, midnight between Sat/Sun
s.cron.AddJob("@weekly", job.NewPeriodicClientTrafficResetJob("weekly"))
// Run once a month, midnight, first of month
s.cron.AddJob("@monthly", job.NewPeriodicClientTrafficResetJob("monthly"))
}
// Make a traffic condition every day, 8:30