forked from cardigann/cardigann
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
562 lines (450 loc) · 11.5 KB
/
main.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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
package main
import (
"bytes"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"runtime"
"strings"
_ "net/http/pprof"
"github.com/Sirupsen/logrus"
"github.com/cardigann/cardigann/config"
"github.com/cardigann/cardigann/indexer"
"github.com/cardigann/cardigann/logger"
"github.com/cardigann/cardigann/server"
"github.com/cardigann/cardigann/torznab"
"github.com/equinox-io/equinox"
"github.com/kardianos/service"
"gopkg.in/alecthomas/kingpin.v2"
)
var (
Version string
log = logger.Logger
)
func version() string {
if Version == "" {
return "dev"
}
return Version
}
func main() {
run(os.Args[1:], os.Exit)
}
func run(args []string, exit func(code int)) {
app := kingpin.New("cardigann",
`A torznab proxy for torrent indexer sites`)
app.Version(version())
app.Writer(os.Stdout)
app.DefaultEnvars()
app.Terminate(exit)
if err := configureServerCommand(app); err != nil {
log.Error(err)
return
}
configureQueryCommand(app)
configureDownloadCommand(app)
configureTestDefinitionCommand(app)
configureServiceCommand(app)
configureUpdateCommand(app)
configureRatiosCommand(app)
kingpin.MustParse(app.Parse(args))
}
func newConfig() (config.Config, error) {
f, err := config.GetConfigPath()
if err != nil {
return nil, err
}
log.WithField("path", f).Debug("Reading config")
return config.NewJSONConfig(f)
}
func lookupRunner(key string, opts indexer.RunnerOpts) (torznab.Indexer, error) {
if key == "aggregate" {
return lookupAggregate(opts)
}
def, err := indexer.DefaultDefinitionLoader.Load(key)
if err != nil {
return nil, err
}
return indexer.NewRunner(def, opts), nil
}
func lookupAggregate(opts indexer.RunnerOpts) (torznab.Indexer, error) {
keys, err := indexer.DefaultDefinitionLoader.List()
if err != nil {
return nil, err
}
agg := indexer.Aggregate{}
for _, key := range keys {
if config.IsSectionEnabled(key, opts.Config) {
def, err := indexer.DefaultDefinitionLoader.Load(key)
if err != nil {
return nil, err
}
agg = append(agg, indexer.NewRunner(def, opts))
}
}
return agg, nil
}
var globals struct {
Debug bool
}
func configureGlobalFlags(cmd *kingpin.CmdClause) {
cmd.Flag("debug", "Print out debug logging").BoolVar(&globals.Debug)
}
func applyGlobalFlags() {
if globals.Debug {
logger.SetLevel(logrus.DebugLevel)
}
}
func configureQueryCommand(app *kingpin.Application) {
var key, format string
var args []string
cmd := app.Command("query", "Manually query an indexer using torznab commands")
cmd.Alias("q")
cmd.Flag("format", "Either json, xml or rss").
Default("json").
Short('f').
EnumVar(&format, "xml", "json", "rss")
cmd.Arg("key", "The indexer key").
Required().
StringVar(&key)
cmd.Arg("args", "Arguments to use to query").
StringsVar(&args)
configureGlobalFlags(cmd)
cmd.Action(func(c *kingpin.ParseContext) error {
applyGlobalFlags()
return queryCommand(key, format, args)
})
}
func queryCommand(key, format string, args []string) error {
conf, err := newConfig()
if err != nil {
return err
}
indexer, err := lookupRunner(key, indexer.RunnerOpts{
Config: conf,
})
if err != nil {
return err
}
vals := url.Values{}
for _, arg := range args {
tokens := strings.SplitN(arg, "=", 2)
if len(tokens) == 1 {
vals.Set("q", tokens[0])
} else {
vals.Add(tokens[0], tokens[1])
}
}
query, err := torznab.ParseQuery(vals)
if err != nil {
return fmt.Errorf("Parsing query failed: %s", err.Error())
}
feed, err := indexer.Search(query)
if err != nil {
return fmt.Errorf("Searching failed: %s", err.Error())
}
switch format {
case "xml":
x, err := xml.MarshalIndent(feed, "", " ")
if err != nil {
return fmt.Errorf("Failed to marshal XML: %s", err.Error())
}
fmt.Printf("%s", x)
case "json":
j, err := json.MarshalIndent(feed, "", " ")
if err != nil {
return fmt.Errorf("Failed to marshal JSON: %s", err.Error())
}
fmt.Printf("%s", j)
}
return nil
}
func configureDownloadCommand(app *kingpin.Application) {
var key, url, file string
cmd := app.Command("download", "Download a torrent from the tracker")
cmd.Arg("key", "The indexer key").
Required().
StringVar(&key)
cmd.Arg("url", "The url of the file to download").
Required().
StringVar(&url)
cmd.Arg("file", "The filename to download to").
Required().
StringVar(&file)
configureGlobalFlags(cmd)
cmd.Action(func(c *kingpin.ParseContext) error {
applyGlobalFlags()
return downloadCommand(key, url, file)
})
}
func downloadCommand(key, url, file string) error {
conf, err := newConfig()
if err != nil {
return err
}
indexer, err := lookupRunner(key, indexer.RunnerOpts{
Config: conf,
})
if err != nil {
return err
}
rc, _, err := indexer.Download(url)
if err != nil {
return fmt.Errorf("Downloading failed: %s", err.Error())
}
defer rc.Close()
f, err := os.Create(file)
if err != nil {
return fmt.Errorf("Creating file failed: %s", err.Error())
}
n, err := io.Copy(f, rc)
if err != nil {
return fmt.Errorf("Creating file failed: %s", err.Error())
}
log.WithFields(logrus.Fields{"bytes": n}).Info("Downloading file")
return nil
}
func configureServerCommand(app *kingpin.Application) error {
conf, err := newConfig()
if err != nil {
return err
}
s, err := server.New(conf, version())
if err != nil {
return err
}
cmd := app.Command("server", "Run the proxy (and web) server")
cmd.Flag("port", "The port to listen on").
Default(s.Port).
StringVar(&s.Port)
cmd.Flag("bind", "The address to bind to").
Default(s.Bind).
StringVar(&s.Bind)
cmd.Flag("prefix", "A path prefix for the server").
Default("/").
StringVar(&s.PathPrefix)
cmd.Flag("passphrase", "Require a passphrase to view web interface").
Short('p').
StringVar(&s.Passphrase)
cmd.Flag("hostname", "The hostname to use for the links back to the server").
StringVar(&s.Hostname)
configureGlobalFlags(cmd)
cmd.Action(func(c *kingpin.ParseContext) error {
applyGlobalFlags()
return serverCommand(s)
})
return nil
}
func serverCommand(s *server.Server) error {
if globals.Debug {
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
}
return s.Listen()
}
func configureTestDefinitionCommand(app *kingpin.Application) {
var f *os.File
var savePath, replayPath string
var cachePages, verbose bool
cmd := app.Command("test-definition", "Test a yaml indexer definition file")
cmd.Alias("test")
cmd.Flag("verbose", "Wheter to show info logger output").
BoolVar(&verbose)
cmd.Flag("cachepages", "Whether to store the output of browser actions for debugging").
BoolVar(&cachePages)
cmd.Flag("save", "Save all requests and responses to a har file").
StringVar(&savePath)
cmd.Flag("replay", "Replay all responses from a har file").
StringVar(&replayPath)
cmd.Arg("file", "The definition yaml file").
FileVar(&f)
configureGlobalFlags(cmd)
cmd.Action(func(c *kingpin.ParseContext) error {
if !verbose {
logger.SetLevel(logrus.WarnLevel)
}
applyGlobalFlags()
return testDefinitionCommand(f, cachePages, savePath, replayPath)
})
}
func testDefinitionCommand(f *os.File, cachePages bool, savePath, replayPath string) error {
logOutput := &bytes.Buffer{}
logger.SetOutput(logOutput)
defer func() {
if logOutput.Len() > 0 {
fmt.Printf("\nLogging output:\n")
io.Copy(os.Stderr, logOutput)
fmt.Println()
}
}()
conf, err := newConfig()
if err != nil {
return err
}
defs := []*indexer.IndexerDefinition{}
if f == nil {
var err error
defs, err = indexer.LoadEnabledDefinitions(conf)
if err != nil {
log.Fatal(err)
}
} else {
def, err := indexer.ParseDefinitionFile(f)
if err != nil {
return err
}
defs = append(defs, def)
}
fmt.Printf("→ Testing %d definition(s) (%s/%s/%s)\n",
len(defs),
version(),
runtime.GOOS, runtime.GOARCH,
)
for _, def := range defs {
runner := indexer.NewRunner(def, indexer.RunnerOpts{
Config: conf,
CachePages: cachePages,
})
tester := indexer.Tester{Runner: runner, Opts: indexer.TesterOpts{
Download: true,
}}
if err = tester.Test(); err != nil {
return fmt.Errorf("One or more tests failed")
}
}
return nil
}
func configureServiceCommand(app *kingpin.Application) {
var action string
var userService bool
var possibleActions = append(service.ControlAction[:], "run")
cmd := app.Command("service", "Control the cardigann service")
cmd.Flag("user", "Whether to use a user service rather than a system one").
BoolVar(&userService)
cmd.Arg("action", "One of "+strings.Join(possibleActions, ", ")).
Required().
EnumVar(&action, possibleActions...)
configureGlobalFlags(cmd)
cmd.Action(func(c *kingpin.ParseContext) error {
applyGlobalFlags()
prg, err := newProgram(programOpts{
UserService: userService,
})
if err != nil {
return err
}
log.Debugf("Running service action %s on platform %v.", action, service.Platform())
if action != "run" {
return service.Control(prg.service, action)
}
return runServiceCommand(prg)
})
}
func runServiceCommand(prg *program) error {
var err error
errs := make(chan error)
prg.logger, err = prg.service.Logger(errs)
if err != nil {
log.Fatal(err)
}
logger.SetOutput(ioutil.Discard)
logger.AddHook(&serviceLogHook{prg.logger})
logger.SetFormatter(&serviceLogFormatter{})
go func() {
for {
err := <-errs
if err != nil {
log.Error(err)
}
}
}()
err = prg.service.Run()
if err != nil {
prg.logger.Error(err)
}
return nil
}
func configureUpdateCommand(app *kingpin.Application) {
var channel string
var dryRun bool
cmd := app.Command("update", "Update cardigann to the latest version")
cmd.Flag("channel", "The channel to update from").
EnumVar(&channel, "stable", "edge")
cmd.Flag("dry-run", "Whether to do a dry run or to execute").
BoolVar(&dryRun)
configureGlobalFlags(cmd)
cmd.Action(func(c *kingpin.ParseContext) error {
return runUpdateCommand(channel, dryRun)
})
}
const appID = "app_doJjayUsKxb"
var publicKey = []byte(`
-----BEGIN ECDSA PUBLIC KEY-----
MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEJmeGsHuOSDZI6nhtlWljGkwHVUow7yVx
KaGKMPQAGXIVEGg4kTYmDPTvCOoFmMZT+foLsJ2qu6xsLAavaZYlY7oXrYyNzM3S
x0cFjxMjM+8k+dQFEfYnemm5TUFQ3Hwz
-----END ECDSA PUBLIC KEY-----
`)
func runUpdateCommand(channel string, dryRun bool) error {
opts := equinox.Options{
Channel: channel,
}
if err := opts.SetPublicKeyPEM(publicKey); err != nil {
return err
}
// check for the update
resp, err := equinox.Check(appID, opts)
switch {
case err == equinox.NotAvailableErr:
log.Info("No update available, already at the latest version!")
return nil
case err != nil:
log.Errorf("Update failed:", err)
return err
}
if dryRun {
log.Infof("Update found from %s to %s, would be applied", Version, resp.ReleaseVersion)
return nil
}
// fetch the update and apply it
err = resp.Apply()
if err != nil {
return err
}
log.Infof("Updated to new version: %s!\n", resp.ReleaseVersion)
return nil
}
func configureRatiosCommand(app *kingpin.Application) {
cmd := app.Command("ratios", "Find your ratio on all your indexers")
configureGlobalFlags(cmd)
cmd.Action(func(c *kingpin.ParseContext) error {
return runRatiosCommand()
})
}
func runRatiosCommand() error {
conf, err := newConfig()
if err != nil {
return err
}
defs, err := indexer.LoadEnabledDefinitions(conf)
if err != nil {
return err
}
for _, def := range defs {
runner := indexer.NewRunner(def, indexer.RunnerOpts{
Config: conf,
})
ratio, err := runner.Ratio()
if err != nil {
return fmt.Errorf("Failed to get ratio for %s: %v", def.Site, err)
}
fmt.Printf("Ratio for %s is %v\n", def.Site, ratio)
}
return nil
}