V2bX/core/selector.go

100 lines
2.0 KiB
Go
Raw Normal View History

2023-06-09 09:20:41 -04:00
package core
import (
"errors"
"sync"
2023-07-29 07:27:15 -04:00
"github.com/InazumaV/V2bX/api/panel"
"github.com/InazumaV/V2bX/conf"
2023-06-09 09:20:41 -04:00
"github.com/hashicorp/go-multierror"
)
2023-06-18 21:56:18 -04:00
type Selector struct {
2023-06-09 09:20:41 -04:00
cores []Core
nodes sync.Map
}
2023-06-18 21:56:18 -04:00
func (s *Selector) Start() error {
2023-06-09 09:20:41 -04:00
for i := range s.cores {
err := s.cores[i].Start()
return err
}
return nil
}
2023-06-18 21:56:18 -04:00
func (s *Selector) Close() error {
2023-06-09 09:20:41 -04:00
var errs error
for i := range s.cores {
errs = multierror.Append(errs, s.cores[i].Close())
}
return errs
}
func isSupported(protocol string, protocols []string) bool {
for i := range protocols {
if protocol == protocols[i] {
return true
}
}
return false
}
2023-07-29 06:47:47 -04:00
func (s *Selector) AddNode(tag string, info *panel.NodeInfo, config *conf.Options) error {
2023-06-09 09:20:41 -04:00
for i := range s.cores {
if !isSupported(info.Type, s.cores[i].Protocols()) {
continue
}
err := s.cores[i].AddNode(tag, info, config)
if err != nil {
return err
}
s.nodes.Store(tag, i)
2023-07-24 05:36:11 -04:00
return nil
2023-06-09 09:20:41 -04:00
}
return errors.New("the node type is not support")
}
2023-06-18 21:56:18 -04:00
func (s *Selector) DelNode(tag string) error {
2023-06-09 09:20:41 -04:00
if t, e := s.nodes.Load(tag); e {
err := s.cores[t.(int)].DelNode(tag)
if err != nil {
return err
}
s.nodes.Delete(tag)
return nil
}
return errors.New("the node is not have")
}
2023-06-18 21:56:18 -04:00
func (s *Selector) AddUsers(p *AddUsersParams) (added int, err error) {
2023-06-09 09:20:41 -04:00
t, e := s.nodes.Load(p.Tag)
if !e {
return 0, errors.New("the node is not have")
}
return s.cores[t.(int)].AddUsers(p)
}
2023-06-18 21:56:18 -04:00
func (s *Selector) GetUserTraffic(tag, uuid string, reset bool) (up int64, down int64) {
2023-06-09 09:20:41 -04:00
t, e := s.nodes.Load(tag)
if !e {
return 0, 0
}
return s.cores[t.(int)].GetUserTraffic(tag, uuid, reset)
}
2023-06-18 22:31:42 -04:00
func (s *Selector) DelUsers(users []panel.UserInfo, tag string) error {
2023-06-09 09:20:41 -04:00
t, e := s.nodes.Load(tag)
if !e {
return errors.New("the node is not have")
}
return s.cores[t.(int)].DelUsers(users, tag)
}
2023-06-18 21:56:18 -04:00
func (s *Selector) Protocols() []string {
2023-06-09 09:20:41 -04:00
protocols := make([]string, 0)
for i := range s.cores {
protocols = append(protocols, s.cores[i].Protocols()...)
}
return protocols
}