Files
x-ui/web/service/inbound.go
sprov 214b217f12 0.0.2
- 增加设置总流量功能,流量超出后自动禁用
 - 优化部分 ui 细节
 - 修复监听 ip 不为空导致无法启动 xray 的问题
 - 修复二维码链接没有包含 address 的问题
2021-06-12 11:26:35 +08:00

114 lines
2.7 KiB
Go

package service
import (
"fmt"
"gorm.io/gorm"
"x-ui/database"
"x-ui/database/model"
"x-ui/xray"
)
type InboundService struct {
}
func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) {
db := database.GetDB()
var inbounds []*model.Inbound
err := db.Model(model.Inbound{}).Where("user_id = ?", userId).Find(&inbounds).Error
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
return inbounds, nil
}
func (s *InboundService) GetAllInbounds() ([]*model.Inbound, error) {
db := database.GetDB()
var inbounds []*model.Inbound
err := db.Model(model.Inbound{}).Find(&inbounds).Error
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
return inbounds, nil
}
func (s *InboundService) AddInbound(inbound *model.Inbound) error {
db := database.GetDB()
return db.Save(inbound).Error
}
func (s *InboundService) DelInbound(id int) error {
db := database.GetDB()
return db.Delete(model.Inbound{}, id).Error
}
func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
db := database.GetDB()
inbound := &model.Inbound{}
err := db.Model(model.Inbound{}).First(inbound, id).Error
if err != nil {
return nil, err
}
return inbound, nil
}
func (s *InboundService) UpdateInbound(inbound *model.Inbound) error {
oldInbound, err := s.GetInbound(inbound.Id)
if err != nil {
return err
}
oldInbound.Up = inbound.Up
oldInbound.Down = inbound.Down
oldInbound.Total = inbound.Total
oldInbound.Remark = inbound.Remark
oldInbound.Enable = inbound.Enable
oldInbound.ExpiryTime = inbound.ExpiryTime
oldInbound.Listen = inbound.Listen
oldInbound.Port = inbound.Port
oldInbound.Protocol = inbound.Protocol
oldInbound.Settings = inbound.Settings
oldInbound.StreamSettings = inbound.StreamSettings
oldInbound.Sniffing = inbound.Sniffing
oldInbound.Tag = fmt.Sprintf("inbound-%v", inbound.Port)
db := database.GetDB()
return db.Save(oldInbound).Error
}
func (s *InboundService) AddTraffic(traffics []*xray.Traffic) (err error) {
if len(traffics) == 0 {
return nil
}
db := database.GetDB()
db = db.Model(model.Inbound{})
tx := db.Begin()
defer func() {
if err != nil {
tx.Rollback()
} else {
tx.Commit()
}
}()
for _, traffic := range traffics {
if traffic.IsInbound {
err = tx.Where("tag = ?", traffic.Tag).
UpdateColumn("up", gorm.Expr("up + ?", traffic.Up)).
UpdateColumn("down", gorm.Expr("down + ?", traffic.Down)).
Error
if err != nil {
return
}
}
}
return
}
func (s *InboundService) DisableInvalidInbounds() (bool, error) {
db := database.GetDB()
result := db.Model(model.Inbound{}).
Where("up + down >= total and total > 0 and enable = ?", true).
Update("enable", false)
err := result.Error
count := result.RowsAffected
return count > 0, err
}