forked from boypt/simple-torrent
/
config.go
245 lines (214 loc) · 5.81 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
package engine
import (
"errors"
"fmt"
"log"
"os"
"path/filepath"
"reflect"
"strings"
"github.com/c2h5oh/datasize"
"github.com/spf13/viper"
"golang.org/x/time/rate"
)
const (
ForbidRuntimeChange uint8 = 1 << iota
NeedEngineReConfig
NeedRestartWatch
NeedUpdateTracker
)
const (
defaultTrackerListURL = "https://raw.githubusercontent.com/ngosang/trackerslist/master/trackers_best.txt"
defaultScraperURL = "https://raw.githubusercontent.com/boypt/simple-torrent/master/scraper-config.json"
)
type Config struct {
AutoStart bool
EngineDebug bool
MuteEngineLog bool
ObfsPreferred bool
ObfsRequirePreferred bool
DisableTrackers bool
DisableIPv6 bool
DownloadDirectory string
WatchDirectory string
EnableUpload bool
EnableSeeding bool
IncomingPort int
DoneCmd string
SeedRatio float32
UploadRate string
DownloadRate string
TrackerListURL string
AlwaysAddTrackers bool
ProxyURL string
RssURL string
ScraperURL string
}
func InitConf(specPath string) (*Config, error) {
viper.SetConfigName("cloud-torrent")
viper.AddConfigPath("/etc/cloud-torrent/")
viper.AddConfigPath("/etc/")
viper.AddConfigPath("$HOME/.cloud-torrent")
viper.AddConfigPath(".")
viper.SetDefault("DownloadDirectory", "./downloads")
viper.SetDefault("WatchDirectory", "./torrents")
viper.SetDefault("EnableUpload", true)
viper.SetDefault("EnableSeeding", true)
viper.SetDefault("AutoStart", true)
viper.SetDefault("DoneCmd", "")
viper.SetDefault("SeedRatio", 0)
viper.SetDefault("ObfsPreferred", true)
viper.SetDefault("ObfsRequirePreferred", false)
viper.SetDefault("IncomingPort", 50007)
viper.SetDefault("TrackerListURL", defaultTrackerListURL)
viper.SetDefault("ScraperURL", defaultScraperURL)
// user specific config path
if stat, err := os.Stat(specPath); stat != nil && err == nil {
viper.SetConfigFile(specPath)
}
configExists := true
if err := viper.ReadInConfig(); err != nil {
if strings.Contains(err.Error(), "Not Found") {
log.Println("[viper Config]", err)
configExists = false
if specPath == "" {
specPath = "./cloud-torrent.yaml"
}
viper.SetConfigFile(specPath)
} else {
return nil, err
}
}
c := &Config{}
viper.Unmarshal(c)
dirChanged, err := c.NormlizeConfigDir()
if err != nil {
return nil, err
}
if dirChanged {
viper.Set("DownloadDirectory", c.DownloadDirectory)
viper.Set("WatchDirectory", c.WatchDirectory)
}
cf := viper.ConfigFileUsed()
log.Println("[config] selected config file: ", cf)
if !configExists || dirChanged {
if err := viper.WriteConfig(); err != nil {
return nil, err
}
log.Println("[config] config file written: ", cf, "exists:", configExists, "dirchanged", dirChanged)
}
return c, nil
}
func (c *Config) NormlizeConfigDir() (bool, error) {
var changed bool
if c.DownloadDirectory != "" {
dldir, err := filepath.Abs(c.DownloadDirectory)
if err != nil {
return false, fmt.Errorf("Invalid path %s, %w", c.WatchDirectory, err)
}
if c.DownloadDirectory != dldir {
changed = true
c.DownloadDirectory = dldir
}
}
if c.WatchDirectory != "" {
wdir, err := filepath.Abs(c.WatchDirectory)
if err != nil {
return false, fmt.Errorf("Invalid path %s, %w", c.WatchDirectory, err)
}
if c.WatchDirectory != wdir {
changed = true
c.WatchDirectory = wdir
}
}
return changed, nil
}
func (c *Config) UploadLimiter() *rate.Limiter {
l, err := rateLimiter(c.UploadRate)
if err != nil {
c.UploadRate = ""
log.Printf("RateLimit [%s] unreconized, set as unlimited", c.UploadRate)
return rate.NewLimiter(rate.Inf, 0)
}
return l
}
func (c *Config) DownloadLimiter() *rate.Limiter {
l, err := rateLimiter(c.DownloadRate)
if err != nil {
c.DownloadRate = ""
log.Printf("RateLimit [%s] unreconized, set as unlimited", c.DownloadRate)
return rate.NewLimiter(rate.Inf, 0)
}
return l
}
func (c *Config) Validate(nc *Config) uint8 {
var status uint8
if c.DoneCmd != nc.DoneCmd {
status |= ForbidRuntimeChange
}
if c.WatchDirectory != nc.WatchDirectory {
status |= NeedRestartWatch
}
if c.TrackerListURL != nc.TrackerListURL {
status |= NeedUpdateTracker
}
rfc := reflect.ValueOf(c)
rfnc := reflect.ValueOf(nc)
for _, field := range []string{"IncomingPort", "DownloadDirectory",
"EngineDebug", "EnableUpload", "EnableSeeding", "UploadRate",
"DownloadRate", "ObfsPreferred", "ObfsRequirePreferred",
"DisableTrackers", "DisableIPv6", "ProxyURL"} {
cval := reflect.Indirect(rfc).FieldByName(field)
ncval := reflect.Indirect(rfnc).FieldByName(field)
if cval.Interface() != ncval.Interface() {
status |= NeedEngineReConfig
break
}
}
return status
}
func (c *Config) SyncViper(nc Config) error {
cv := reflect.ValueOf(*c)
nv := reflect.ValueOf(nc)
typeOfC := cv.Type()
for i := 0; i < typeOfC.NumField(); i++ {
if cv.Field(i).Interface() != nv.Field(i).Interface() {
name := typeOfC.Field(i).Name
oval := cv.Field(i).Interface()
val := nv.Field(i).Interface()
viper.Set(name, val)
log.Println("config updated ", name, ": ", oval, " -> ", val)
}
}
return viper.WriteConfig()
}
func rateLimiter(rstr string) (*rate.Limiter, error) {
var rateSize int
rstr = strings.ToLower(strings.TrimSpace(rstr))
switch rstr {
case "low":
// ~50k/s
rateSize = 50000
case "medium":
// ~500k/s
rateSize = 500000
case "high":
// ~1500k/s
rateSize = 1500000
case "unlimited", "0", "":
// unlimited
return rate.NewLimiter(rate.Inf, 0), nil
default:
var v datasize.ByteSize
err := v.UnmarshalText([]byte(rstr))
if err != nil {
return nil, err
}
if v > 2147483647 {
// max of int, unlimited
return nil, errors.New("excceed int val")
}
rateSize = int(v)
}
return rate.NewLimiter(rate.Limit(rateSize), rateSize*3), nil
}