github.com/cloudreve/Cloudreve/v3@v3.0.0-20240224133659-3edb00a6484c/models/node.go (about)

     1  package model
     2  
     3  import (
     4  	"encoding/json"
     5  	"github.com/jinzhu/gorm"
     6  )
     7  
     8  // Node 从机节点信息模型
     9  type Node struct {
    10  	gorm.Model
    11  	Status       NodeStatus // 节点状态
    12  	Name         string     // 节点别名
    13  	Type         ModelType  // 节点状态
    14  	Server       string     // 服务器地址
    15  	SlaveKey     string     `gorm:"type:text"` // 主->从 通信密钥
    16  	MasterKey    string     `gorm:"type:text"` // 从->主 通信密钥
    17  	Aria2Enabled bool       // 是否支持用作离线下载节点
    18  	Aria2Options string     `gorm:"type:text"` // 离线下载配置
    19  	Rank         int        // 负载均衡权重
    20  
    21  	// 数据库忽略字段
    22  	Aria2OptionsSerialized Aria2Option `gorm:"-"`
    23  }
    24  
    25  // Aria2Option 非公有的Aria2配置属性
    26  type Aria2Option struct {
    27  	// RPC 服务器地址
    28  	Server string `json:"server,omitempty"`
    29  	// RPC 密钥
    30  	Token string `json:"token,omitempty"`
    31  	// 临时下载目录
    32  	TempPath string `json:"temp_path,omitempty"`
    33  	// 附加下载配置
    34  	Options string `json:"options,omitempty"`
    35  	// 下载监控间隔
    36  	Interval int `json:"interval,omitempty"`
    37  	// RPC API 请求超时
    38  	Timeout int `json:"timeout,omitempty"`
    39  }
    40  
    41  type NodeStatus int
    42  type ModelType int
    43  
    44  const (
    45  	NodeActive NodeStatus = iota
    46  	NodeSuspend
    47  )
    48  
    49  const (
    50  	SlaveNodeType ModelType = iota
    51  	MasterNodeType
    52  )
    53  
    54  // GetNodeByID 用ID获取节点
    55  func GetNodeByID(ID interface{}) (Node, error) {
    56  	var node Node
    57  	result := DB.First(&node, ID)
    58  	return node, result.Error
    59  }
    60  
    61  // GetNodesByStatus 根据给定状态获取节点
    62  func GetNodesByStatus(status ...NodeStatus) ([]Node, error) {
    63  	var nodes []Node
    64  	result := DB.Where("status in (?)", status).Find(&nodes)
    65  	return nodes, result.Error
    66  }
    67  
    68  // AfterFind 找到节点后的钩子
    69  func (node *Node) AfterFind() (err error) {
    70  	// 解析离线下载设置到 Aria2OptionsSerialized
    71  	if node.Aria2Options != "" {
    72  		err = json.Unmarshal([]byte(node.Aria2Options), &node.Aria2OptionsSerialized)
    73  	}
    74  
    75  	return err
    76  }
    77  
    78  // BeforeSave Save策略前的钩子
    79  func (node *Node) BeforeSave() (err error) {
    80  	optionsValue, err := json.Marshal(&node.Aria2OptionsSerialized)
    81  	node.Aria2Options = string(optionsValue)
    82  	return err
    83  }
    84  
    85  // SetStatus 设置节点启用状态
    86  func (node *Node) SetStatus(status NodeStatus) error {
    87  	node.Status = status
    88  	return DB.Model(node).Updates(map[string]interface{}{
    89  		"status": status,
    90  	}).Error
    91  }