11package config
22
3- import "strings"
3+ import (
4+ "github.com/burntsushi/toml"
5+ "log"
6+ "os"
7+ "path/filepath"
8+ "reflect"
9+ "strings"
10+ )
11+
12+ var (
13+ ConfPath = "config.toml"
14+ Params * Config
15+ )
416
517type Config struct {
6- Jackett Jackett
7- Dest []Destination `toml:"destinations"`
18+ Dest []Destination `toml:"destinations"`
819}
920
1021type Destination struct {
1122 Name string
12- IP string
13- Port int
14- API string
15- }
16-
17- type Jackett struct {
18- IP string
19- Port int
20- API string
23+ Ip string
24+ Port uint16
25+ Api string
2126}
2227
2328func (c * Config ) GetDestination (name string ) * Destination {
@@ -29,4 +34,80 @@ func (c *Config) GetDestination(name string) *Destination {
2934 return nil
3035}
3136
32- var Params * Config
37+ func (c * Config ) SaveFile (path string ) error {
38+ ext := filepath .Ext (path )
39+ if ext == "" {
40+ path = path + ".toml"
41+ } else if ext != ".toml" {
42+ log .Fatal ("Config file does not have toml extension, please correct it" )
43+ }
44+
45+ f , err := os .OpenFile (path , os .O_WRONLY | os .O_CREATE | os .O_TRUNC , 0666 )
46+
47+ defer f .Close ()
48+ if err != nil {
49+ return err
50+ }
51+
52+ if err := toml .NewEncoder (f ).Encode (c ); err != nil {
53+ log .Fatal (err )
54+ return err
55+ }
56+
57+ return nil
58+ }
59+
60+ func (c * Config ) ChangeParams (dest , param string , value interface {}) {
61+ main := reflect .ValueOf (c )
62+ mainElem := main .Elem ()
63+ items := mainElem .FieldByName ("Dest" )
64+
65+ for i := 0 ; i < items .Len (); i ++ {
66+ item := items .Index (i )
67+ if item .FieldByName ("Name" ).String () == strings .Title (dest ) {
68+ field := item .FieldByName (strings .Title (param ))
69+ if field .IsValid () {
70+ if field .CanSet () {
71+ if field .Kind () == reflect .Uint16 {
72+ if reflect .TypeOf (value ).String () == "int" {
73+ newValue := uint64 (value .(int ))
74+ field .SetUint (newValue )
75+ }
76+ }
77+ if field .Kind () == reflect .String {
78+ newValue := value .(string )
79+ field .SetString (newValue )
80+ }
81+ }
82+ }
83+
84+ }
85+ }
86+ }
87+
88+ func ParseConfigFile () {
89+ if _ , err := toml .DecodeFile (ConfPath , & Params ); err != nil {
90+ log .Fatal (err )
91+ }
92+
93+ if len (Params .Dest ) < 1 {
94+ log .Fatal ("There is no Destination configured." )
95+ }
96+
97+ for _ , dest := range Params .Dest {
98+ if dest .Api == "" {
99+ param := os .Getenv (strings .ToUpper (dest .Name ))
100+
101+ if param != "" {
102+ Params .GetDestination (dest .Name ).Api = param
103+ } else {
104+ if len (Params .Dest ) == 1 {
105+ log .Fatalf ("There is no %s API configured." , dest .Name )
106+ } else {
107+ log .Printf ("There is no %s API configured." , dest .Name )
108+ }
109+ }
110+ }
111+
112+ }
113+ }
0 commit comments