aboutsummaryrefslogtreecommitdiffstats
path: root/queue/config.go
blob: bff5572fa37008042f5c9c72eb691fb2617dfc99 (plain) (blame)
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
package queue

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strings"
	"text/template"
	"time"

	"github.com/mpolden/lftpq/parser"
)

type Config struct {
	Default   Site
	LocalDirs []LocalDir
	Sites     []Site
}

type Replacement struct {
	Pattern     string
	pattern     *regexp.Regexp
	Replacement string
}

type LocalDir struct {
	Name         string
	Parser       string
	Dir          string
	Replacements []Replacement
	Template     *template.Template `json:"-"`
}

type Site struct {
	GetCmd       string
	Name         string
	Dirs         []string
	MaxAge       string
	maxAge       time.Duration
	Patterns     []string
	patterns     []*regexp.Regexp
	Filters      []string
	filters      []*regexp.Regexp
	SkipSymlinks bool
	SkipExisting bool
	SkipFiles    bool
	LocalDir     string
	Priorities   []string
	priorities   []*regexp.Regexp
	PostCommand  string
	postCommand  *exec.Cmd
	Merge        bool
	Skip         bool
	itemParser
}

type itemParser struct {
	parser       parser.Parser
	template     *template.Template
	replacements []Replacement
}

func compilePatterns(patterns []string) ([]*regexp.Regexp, error) {
	res := make([]*regexp.Regexp, 0, len(patterns))
	for _, p := range patterns {
		re, err := regexp.Compile(p)
		if err != nil {
			return nil, err
		}
		res = append(res, re)
	}
	return res, nil
}

func compileReplacements(replacements []Replacement) ([]Replacement, error) {
	res := make([]Replacement, 0, len(replacements))
	for _, r := range replacements {
		pattern, err := regexp.Compile(r.Pattern)
		if err != nil {
			return nil, err
		}
		r.pattern = pattern
		res = append(res, r)
	}
	return res, nil
}

func parseTemplate(tmpl string) (*template.Template, error) {
	funcMap := template.FuncMap{"Sprintf": fmt.Sprintf}
	t, err := template.New("").Funcs(funcMap).Parse(tmpl)
	if err != nil {
		return nil, err
	}
	return t, nil
}

func expandUser(path string) string {
	tilde := strings.Index(path, "~")
	end := strings.IndexRune(path, os.PathSeparator)
	if tilde != 0 {
		return path
	}
	if end == -1 {
		end = len(path)
	}
	home := os.Getenv("HOME")
	if end > 1 {
		home = filepath.Join(filepath.Dir(home), path[1:end])
	}
	return filepath.Join(home, path[end:])
}

func command(cmd string) (*exec.Cmd, error) {
	if cmd == "" {
		return nil, nil
	}
	argv := strings.Split(cmd, " ")
	program := expandUser(argv[0])
	if _, err := exec.LookPath(program); err != nil {
		return nil, err
	}
	return exec.Command(program, argv[1:]...), nil
}

func (c *Config) load() error {
	itemParsers := make(map[string]itemParser)
	for i, d := range c.LocalDirs {
		if d.Name == "" {
			return fmt.Errorf("invalid local dir name: %q", d.Name)
		}
		if d.Dir == "" {
			return fmt.Errorf("invalid local dir path: %q", d.Dir)
		}
		if _, ok := itemParsers[d.Name]; ok {
			return fmt.Errorf("invalid local dir: %q: declared multiple times", d.Name)
		}
		var parserFunc parser.Parser
		switch d.Parser {
		case "show":
			parserFunc = parser.Show
		case "movie":
			parserFunc = parser.Movie
		case "":
			parserFunc = parser.Default
		default:
			return fmt.Errorf("invalid local dir %q: invalid parser: %q (must be %q, %q or %q)",
				d.Name, d.Parser, "show", "movie", "")
		}
		tmpl, err := parseTemplate(d.Dir)
		if err != nil {
			return err
		}
		replacements, err := compileReplacements(d.Replacements)
		if err != nil {
			return err
		}
		itemParsers[d.Name] = itemParser{
			parser:       parserFunc,
			replacements: replacements,
			template:     tmpl,
		}
		c.LocalDirs[i].Template = tmpl
	}
	for i := range c.Sites {
		site := &c.Sites[i]
		maxAge, err := time.ParseDuration(site.MaxAge)
		if err != nil {
			return err
		}
		site.maxAge = maxAge
		patterns, err := compilePatterns(site.Patterns)
		if err != nil {
			return err
		}
		site.patterns = patterns
		filters, err := compilePatterns(site.Filters)
		if err != nil {
			return err
		}
		site.filters = filters
		priorities, err := compilePatterns(site.Priorities)
		if err != nil {
			return err
		}
		site.priorities = priorities

		cmd, err := command(site.PostCommand)
		if err != nil {
			return err
		}
		site.postCommand = cmd

		itemParser, ok := itemParsers[site.LocalDir]
		if !ok {
			return fmt.Errorf("site: %q: invalid local dir: %q", site.Name, site.LocalDir)
		}
		site.itemParser = itemParser
	}
	return nil
}

func (c *Config) SetLocalDir(name string) error {
	newCfg := *c
	newCfg.Sites = make([]Site, len(c.Sites))
	for i, s := range c.Sites {
		s.LocalDir = name
		newCfg.Sites[i] = s
	}
	if err := newCfg.load(); err != nil {
		return err
	}
	*c = newCfg
	return nil
}

func (c *Config) JSON() ([]byte, error) {
	return json.MarshalIndent(c, "", "  ")
}

func readConfig(r io.Reader) (Config, error) {
	data, err := ioutil.ReadAll(r)
	if err != nil {
		return Config{}, err
	}
	// Unmarshal config and replace every site with the default one
	var defaults Config
	if err := json.Unmarshal(data, &defaults); err != nil {
		return Config{}, err
	}
	for i := range defaults.Sites {
		defaults.Sites[i] = defaults.Default
	}
	// Unmarshal config again, letting individual sites override the defaults
	cfg := defaults
	if err := json.Unmarshal(data, &cfg); err != nil {
		return Config{}, err
	}
	return cfg, nil
}

func ReadConfig(path string) (Config, error) {
	path = expandUser(path)
	var r io.Reader
	if path == "-" {
		r = bufio.NewReader(os.Stdin)
	} else {
		f, err := os.Open(path)
		if err != nil {
			return Config{}, err
		}
		defer f.Close()
		r = f
	}
	cfg, err := readConfig(r)
	if err != nil {
		return Config{}, err
	}
	if err := cfg.load(); err != nil {
		return Config{}, err
	}
	return cfg, nil
}