/
filters.go
399 lines (355 loc) · 10.3 KB
/
filters.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
package indexer
import (
"errors"
"fmt"
log "github.com/sirupsen/logrus"
"github.com/sp0x/torrentd/indexer/formatting"
"net/url"
"regexp"
"strconv"
"strings"
"text/scanner"
"time"
"unicode"
"github.com/bcampbell/fuzzytime"
)
const (
filterTimeFormat = time.RFC1123Z
)
var filterLogger log.FieldLogger = log.New()
func defaultFilterConfig() map[string]string {
return map[string]string{
"striprussian": "true",
}
}
//Filter out whatever's needed
func invokeFilter(name string, args interface{}, value string) (string, error) {
switch name {
case "querystring":
param, ok := args.(string)
if !ok {
return "", fmt.Errorf("Filter %q requires a string argument", name)
}
return filterQueryString(param, value)
case "timeparse", "dateparse", "dateparseAlt":
if args == nil {
return filterDateParse(nil, value)
}
if layout, ok := args.(string); ok {
return filterDateParse([]string{layout}, value)
}
return "", fmt.Errorf("Filter argument type %T was invalid", args)
case "bool":
value := formatting.NormalizeSpace(value)
if value != "" {
value = "true"
} else {
value = "false"
}
return value, nil
case "regexp":
pattern, ok := args.(string)
if !ok {
return "", fmt.Errorf("Filter %q requires a string argument", name)
}
return filterRegexp(pattern, value)
case "split":
sep, ok := (args.([]interface{}))[0].(string)
if !ok {
return "", fmt.Errorf("Filter %q requires a string argument at idx 0", name)
}
pos, ok := (args.([]interface{}))[1].(int)
if !ok {
return "", fmt.Errorf("Filter %q requires an int argument at idx 1", name)
}
return filterSplit(sep, pos, value)
case "replace":
from, ok := (args.([]interface{}))[0].(string)
if !ok {
return "", fmt.Errorf("Filter %q requires a string argument at idx 0", name)
}
to, ok := (args.([]interface{}))[1].(string)
if !ok {
return "", fmt.Errorf("Filter %q requires a string argument at idx 1", name)
}
return strings.Replace(value, from, to, -1), nil
case "trim":
cutset, ok := args.(string)
if !ok {
return "", fmt.Errorf("Filter %q requires a string argument at idx 0", name)
}
return strings.Trim(value, cutset), nil
case "whitespace":
return formatting.NormalizeSpace(value), nil
case "append":
str, ok := args.(string)
if !ok {
return "", fmt.Errorf("Filter %q requires a string argument at idx 0", name)
}
return value + str, nil
case "prepend":
str, ok := args.(string)
if !ok {
return "", fmt.Errorf("Filter %q requires a string argument at idx 0", name)
}
return str + value, nil
case "urldecode":
decoded, err := url.QueryUnescape(value)
if err != nil {
return "", fmt.Errorf("Filter urldecode couldn't decode value `%s`, %s\n", value, err)
}
return decoded, nil
case "urlarg":
argName, ok := args.(string)
if !ok {
return "", fmt.Errorf("Filter %q requires a string argument at idx 0", name)
}
urlx, err := url.Parse(value)
if err != nil {
return "", fmt.Errorf("urlarg filter couldn't parse url value: %s", value)
}
value = urlx.Query().Get(argName)
return value, nil
case "size":
value = fmt.Sprint(formatting.SizeStrToBytes(value))
return value, nil
case "number":
value = formatting.StripToNumber(formatting.NormalizeSpace(value))
return value, nil
case "mapreplace":
return filterMapReplace(value, args)
case "re_replace":
return filterReReplace(value, args)
case "timeago", "fuzzytime", "reltime":
return filterFuzzyTime(value, time.Now(), true)
}
return "", errors.New("Unknown filter " + name)
}
func filterMapReplace(value string, args interface{}) (string, error) {
replacemenets := args.(map[interface{}]interface{})
for oldVal, newVal := range replacemenets {
value = strings.Replace(value, oldVal.(string), newVal.(string), -1)
}
return value, nil
}
func filterReReplace(value string, args interface{}) (string, error) {
pattern := args.([]interface{})[0].(string)
replacement := args.([]interface{})[1].(string)
re, err := regexp.Compile(pattern)
if err != nil {
return "", err
}
value = re.ReplaceAllString(value, replacement)
return value, nil
}
func filterQueryString(param string, value string) (string, error) {
u, err := url.Parse(value)
if err != nil {
return "", err
}
return u.Query().Get(param), nil
}
func filterDateParse(layouts []string, value string) (string, error) {
var err error
for _, layout := range layouts {
var t time.Time
if t, err = time.Parse(layout, value); err == nil {
return t.Format(filterTimeFormat), nil
}
}
return "", fmt.Errorf("no matching date pattern for %s. %s", value, err)
}
func filterSplit(sep string, pos int, value string) (string, error) {
frags := strings.Split(value, sep)
if pos < 0 {
pos = len(frags) + pos
}
return frags[pos], nil
}
func filterRegexp(pattern string, value string) (string, error) {
re, err := regexp.Compile(pattern)
if err != nil {
return "", err
}
matches := re.FindStringSubmatch(value)
if len(matches) == 0 {
return "", errors.New("No matches found for pattern")
}
filterLogger.WithFields(log.Fields{"matches": matches}).Debug("Regex matched")
//If we have groups, use the groups concatenated by a space
if len(matches) > 1 {
matches = matches[1:]
return strings.Join(matches, " "), nil
}
return matches[0], nil
}
func splitDecimalStr(s string) (int, float64, error) {
if parts := strings.SplitN(s, ".", 2); len(parts) == 2 {
i, err := strconv.Atoi(parts[0])
if err != nil {
return 0, 0, err
}
f, err := strconv.ParseFloat("0."+parts[1], 64)
if err != nil {
return 0, 0, err
}
return i, f, nil
}
i, err := strconv.Atoi(s)
if err != nil {
return 0, 0, err
}
return i, 0, nil
}
var (
timeAgoRegexp = regexp.MustCompile(`(?i)\bago`)
todayRegexp = regexp.MustCompile(`(?i)\btoday([\s,]+|$)`)
tomorrowRegexp = regexp.MustCompile(`(?i)\btomorrow([\s,]+|$)`)
yesterdayRegexp = regexp.MustCompile(`(?i)\byesterday([\s,]+|$)`)
missingYearRegexp = regexp.MustCompile(`^\d{1,2}-\d{1,2}\b`)
)
func normalizeNumber(s string) string {
normalized := normalizeSpace(strings.Trim(s, "-"))
normalized = strings.Replace(s, ",", "", -1)
if normalized == "" {
normalized = "0"
}
return normalized
}
func normalizeSpace(s string) string {
return strings.TrimSpace(strings.Map(func(r rune) rune {
if unicode.IsSpace(r) {
return ' '
}
return r
}, s))
}
func parseTimeAgo(src string, now time.Time) (time.Time, error) {
normalized := normalizeSpace(src)
normalized = strings.ToLower(normalized)
var s scanner.Scanner
s.Init(strings.NewReader(normalized))
var tok rune
for tok != scanner.EOF {
tok = s.Scan()
switch s.TokenText() {
case ",", "ago", "", "and":
continue
}
v, fraction, err := splitDecimalStr(s.TokenText())
if err != nil {
return now, fmt.Errorf(
"failed to parse decimal time %q in time format at %s", s.TokenText(), s.Pos())
}
tok = s.Scan()
if tok == scanner.EOF {
return now, fmt.Errorf(
"expected a time unit at %s:%v", s.TokenText(), s.Pos())
}
unit := s.TokenText()
if unit != "s" {
unit = strings.TrimSuffix(s.TokenText(), "s")
}
switch unit {
case "year", "yr", "y":
now = now.AddDate(-v, 0, 0)
if fraction > 0 {
now = now.Add(time.Duration(float64(now.AddDate(-1, 0, 0).Sub(now)) * fraction))
}
case "month", "mnth", "mo":
now = now.AddDate(0, -v, 0)
if fraction > 0 {
now = now.Add(time.Duration(float64(now.AddDate(0, -1, 0).Sub(now)) * fraction))
}
case "week", "wk", "w":
now = now.AddDate(0, 0, -7)
if fraction > 0 {
now = now.Add(time.Duration(float64(now.AddDate(0, 0, -7).Sub(now)) * fraction))
}
case "day", "d":
now = now.AddDate(0, 0, -v)
if fraction > 0 {
now = now.Add(time.Minute * -time.Duration(fraction*1440))
}
case "hour", "hr", "h":
now = now.Add(time.Hour * -time.Duration(v))
if fraction > 0 {
now = now.Add(time.Second * -time.Duration(fraction*3600))
}
case "minute", "min", "m":
now = now.Add(time.Minute * -time.Duration(v))
if fraction > 0 {
now = now.Add(time.Second * -time.Duration(fraction*60))
}
case "second", "sec", "s":
now = now.Add(time.Second * -time.Duration(v))
default:
return now, fmt.Errorf("Unsupporting unit of time %q", unit)
}
}
return now, nil
}
var todayTimeFormat = "15:04:05"
func parseFuzzyTime(src string, now time.Time, allowPartialDate bool) (time.Time, error) {
if okTime, err := time.Parse(todayTimeFormat, src); err == nil {
dt := fuzzytime.DateTime{}
dt.Time.SetHour(okTime.Hour())
dt.Time.SetSecond(okTime.Second())
dt.Time.SetMinute(okTime.Minute())
dt.Date.SetYear(now.Year())
dt.Date.SetDay(now.Day())
dt.Date.SetMonth(int(now.Month()))
isof := dt.ISOFormat()
okTime, _ = time.Parse("2006-01-02T15:04:05", isof)
return okTime, nil
}
if timeAgoRegexp.MatchString(src) {
t, err := parseTimeAgo(src, now)
if err != nil {
return t, fmt.Errorf("error parsing time ago %q: %v", src, err)
}
return t, nil
}
normalized := normalizeSpace(src)
out := todayRegexp.ReplaceAllLiteralString(normalized, now.Format("2006 "))
out = tomorrowRegexp.ReplaceAllLiteralString(out, now.AddDate(0, 0, 1).Format("Mon, 02 Jan 2006 "))
out = yesterdayRegexp.ReplaceAllLiteralString(out, now.AddDate(0, 0, -1).Format("Mon, 02 Jan 2006 "))
if m := missingYearRegexp.FindStringSubmatch(out); len(m) > 0 {
out = missingYearRegexp.ReplaceAllLiteralString(src, m[0]+now.Format("-2006"))
}
dt, _, err := fuzzytime.USContext.Extract(out)
if err != nil {
return time.Time{}, fmt.Errorf("error extracting date from %q: %v", out, err)
}
if dt.Time.Empty() {
dt.Time.SetHour(0)
dt.Time.SetMinute(0)
dtx, err := time.Parse("2006", out)
if err != nil {
dtx, err = time.Parse("Jan 2006", out)
if err == nil {
return dtx, nil
}
} else {
return dtx, nil
}
}
//If we dont support partial dates, we return an error
if !allowPartialDate && !dt.HasFullDate() {
return time.Time{}, fmt.Errorf("found only partial date %v", dt.ISOFormat())
}
if !dt.Time.HasSecond() {
dt.Time.SetSecond(0)
}
if !dt.HasTZOffset() {
dt.Time.SetTZOffset(0)
}
return time.Parse("2006-01-02T15:04:05Z07:00", dt.ISOFormat())
}
func filterFuzzyTime(src string, now time.Time, allowPartialDate bool) (string, error) {
t, err := parseFuzzyTime(src, now, allowPartialDate)
if err != nil {
return "", fmt.Errorf("error parsing fuzzy time %q: %v", src, err)
}
return t.Format(filterTimeFormat), nil
}