forked from lauyoume/gopiper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
filter.go
707 lines (633 loc) · 19.1 KB
/
filter.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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
package gopiper
import (
"errors"
"fmt"
"html"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"github.com/admpub/regexp2"
)
func init() {
RegisterFilter("preadd", preadd, "添加前缀", `preadd(prefix)`, ``)
RegisterFilter("postadd", postadd, "添加后缀", `postadd(suffix)`, ``)
RegisterFilter("replace", replace, "替换", `replace(find,replace)`, ``)
RegisterFilter("split", split, "将字符串按指定分隔符分割成数组", `split(-)`, ``)
RegisterFilter("join", join, "合并数组为字符串", `join(-)`, ``)
RegisterFilter("trim", trim, "剪掉头尾指定字符", `trim(;)`, ``)
RegisterFilter("trimspace", trimspace, "剪掉头尾空白", `trimspace`, ``)
RegisterFilter("substr", substr, "获取子字符串。字符串总是从左向右从0开始编号,参数1和参数2分别用来指定要截取的起止位置编号,截取子字符串时,总是包含起始编号的字符,不包含终止编号的字符", `substr(0,5)`, ``)
RegisterFilter("intval", intval, "转换为整数", `intval`, ``)
RegisterFilter("floatval", floatval, "转换为小数", `floatval`, ``)
RegisterFilter("hrefreplace", hrefreplace, "替换href属性。$2为捕获到的href属性值", `hrefreplace(data-url="$2")`, ``)
RegisterFilter("regexpreplace", regexpreplace, "正则替换", `regexpreplace(^A$,B)`, ``)
RegisterFilter("wraphtml", wraphtml, "将采集到的数据用HTML标签包围起来", `wraphtml(a)`, ``)
RegisterFilter("tosbc", tosbc, "将全角的标点符号和英文字母转换为半角", `tosbc`, ``)
RegisterFilter("unescape", unescape, "解码HTML", `unescape`, ``)
RegisterFilter("escape", escape, "编码HTML", `escape`, ``)
RegisterFilter("sprintf", sprintf, "格式化", `sprintf(%s)`, ``)
RegisterFilter("sprintfmap", sprintfmap, "用map值格式化(前提是采集到的数据必须是map类型)。参数1为模板字符串,其它参数用于指定相应map元素值的键值", `sprintfmap(%v-%v,a,b)`, ``)
RegisterFilter("unixtime", unixtime, "UNIX时间戳(秒)", `unixtime`, ``)
RegisterFilter("unixmill", unixmill, "UNIX时间戳(毫秒)", `unixmill`, ``)
RegisterFilter("paging", paging, "分页。参数1为起始页码,参数2为终止页码,参数3为步进值(可选)", `paging(1,10,1)`, ``)
RegisterFilter("quote", quote, "用双引号包起来", `quote`, ``)
RegisterFilter("unquote", unquote, "取消双引号包围", `unquote`, ``)
}
type FilterFunction func(src *reflect.Value, params *reflect.Value) (interface{}, error)
func NewFilter(name string, fn FilterFunction, description, usage, example string) *Filter {
return &Filter{
Name: name,
function: fn,
Description: description,
Usage: usage,
Example: example,
}
}
type Filter struct {
Name string
function FilterFunction
Description string `json:",omitempty"`
Usage string `json:",omitempty"`
Example string `json:",omitempty"`
}
var filters = make(map[string]*Filter)
func RegisterFilter(name string, fn FilterFunction, description, usage, example string) {
_, existing := filters[name]
if existing {
panic(fmt.Sprintf("Filter with name '%s' is already registered.", name))
}
filters[name] = NewFilter(name, fn, description, usage, example)
}
func ReplaceFilter(name string, fn FilterFunction, description, usage, example string) {
_, existing := filters[name]
if !existing {
panic(fmt.Sprintf("Filter with name '%s' does not exist (therefore cannot be overridden).", name))
}
filters[name] = NewFilter(name, fn, description, usage, example)
}
func AllFilter() map[string]*Filter {
return filters
}
var (
filterExp = regexp.MustCompile(`([a-zA-Z0-9\-_]+)(?:\(([\w\W]*?)\))?(\||$)`)
hrefFilterExp = regexp.MustCompile(`href(?:\s*)=(?:\s*)(['"])?([^'" ]*)(['"])?`)
hrefFilterExp2 = regexp2.MustCompile(`href(?:\s*)=(?:\s*)(['"]?)([^'" ]*)\1`, regexp2.IgnoreCase)
)
func applyFilter(name string, src *reflect.Value, params *reflect.Value) (interface{}, error) {
filter, existing := filters[name]
if !existing {
return nil, fmt.Errorf("Filter with name '%s' not found.", name)
}
return filter.function(src, params)
}
func callFilter(src interface{}, value string) (interface{}, error) {
if src == nil || len(value) == 0 {
return src, nil
}
vt := filterExp.FindAllStringSubmatch(value, -1)
for _, v := range vt {
if len(v) < 3 {
continue
}
name := v[1]
params := v[2]
srcValue := reflect.ValueOf(src)
paramValue := reflect.ValueOf(params)
next, err := applyFilter(name, &srcValue, ¶mValue)
if err != nil {
continue
}
src = next
}
return src, nil
}
//preadd(prefix) => {prefix}{src}
func preadd(src *reflect.Value, params *reflect.Value) (interface{}, error) {
switch src.Interface().(type) {
case string:
return params.String() + src.String(), nil
case []string:
vt, _ := src.Interface().([]string)
for i := 0; i < len(vt); i++ {
vt[i] = params.String() + vt[i]
}
return vt, nil
}
return params.String(), nil
}
//postadd(suffix) => {src}{suffix}
func postadd(src *reflect.Value, params *reflect.Value) (interface{}, error) {
switch src.Interface().(type) {
case string:
return src.String() + params.String(), nil
case []string:
vt, _ := src.Interface().([]string)
for i := 0; i < len(vt); i++ {
vt[i] = vt[i] + params.String()
}
return vt, nil
}
return params.String(), nil
}
func _substr(src string, params *reflect.Value) string {
vt := strings.Split(params.String(), ",")
switch len(vt) {
case 1:
start, _ := strconv.Atoi(vt[0])
return src[start:]
case 2:
start, _ := strconv.Atoi(vt[0])
end, _ := strconv.Atoi(vt[1])
return src[start:end]
}
return src
}
//substr(0,5) => src[0:5]
//substr(5) => src[5:]
func substr(src *reflect.Value, params *reflect.Value) (interface{}, error) {
switch src.Interface().(type) {
case string:
return _substr(src.String(), params), nil
case []string:
vt, _ := src.Interface().([]string)
for i := 0; i < len(vt); i++ {
vt[i] = _substr(vt[i], params)
}
return vt, nil
}
return src.Interface(), nil
}
func _replace(src string, params *reflect.Value) string {
vt := SplitParams(params.String())
switch len(vt) {
case 1:
return strings.Replace(src, vt[0], "", -1)
case 2:
return strings.Replace(src, vt[0], vt[1], -1)
case 3:
n, _ := strconv.Atoi(vt[2])
return strings.Replace(src, vt[0], vt[1], n)
}
return src
}
//replace(find,replace) => src=findaaa => replaceaaa
//replace(find) => src=findaaa => aaa
func replace(src *reflect.Value, params *reflect.Value) (interface{}, error) {
switch src.Interface().(type) {
case string:
return _replace(src.String(), params), nil
case []string:
vt, _ := src.Interface().([]string)
for i := 0; i < len(vt); i++ {
vt[i] = _replace(vt[i], params)
}
return vt, nil
}
return src.Interface(), nil
}
//trim(;) => src=;a; => a
func trim(src *reflect.Value, params *reflect.Value) (interface{}, error) {
if params == nil {
return src.Interface(), errors.New("filter trim nil params")
}
switch src.Interface().(type) {
case string:
return strings.Trim(src.String(), params.String()), nil
case []string:
vt, _ := src.Interface().([]string)
for i := 0; i < len(vt); i++ {
vt[i] = strings.Trim(vt[i], params.String())
}
return vt, nil
}
return src.Interface(), nil
}
//trimspace => src=" \naaa\n " => "aaa"
func trimspace(src *reflect.Value, params *reflect.Value) (interface{}, error) {
switch src.Interface().(type) {
case string:
return strings.TrimSpace(src.String()), nil
case []string:
vt, _ := src.Interface().([]string)
for i := 0; i < len(vt); i++ {
vt[i] = strings.TrimSpace(vt[i])
}
return vt, nil
}
return src.Interface(), nil
}
//split(:) => src="a:b" => [a,b]
func split(src *reflect.Value, params *reflect.Value) (interface{}, error) {
if params == nil {
return src.Interface(), errors.New("filter split nil params")
}
switch src.Interface().(type) {
case string:
str := strings.TrimSpace(src.String())
if len(str) == 0 {
return []string{}, nil
}
return strings.Split(str, params.String()), nil
case []string:
vt, _ := src.Interface().([]string)
rs := make([][]string, len(vt))
for i := 0; i < len(vt); i++ {
str := strings.TrimSpace(vt[i])
if len(str) == 0 {
rs[i] = []string{}
} else {
rs[i] = strings.Split(str, params.String())
}
}
return rs, nil
}
return src.Interface(), nil
}
//join(:) => src=["a","b"] => a:b
func join(src *reflect.Value, params *reflect.Value) (interface{}, error) {
if params == nil {
return src.Interface(), errors.New("filter split nil params")
}
switch src.Interface().(type) {
case []string:
vt, _ := src.Interface().([]string)
rs := make([]string, 0)
for _, v := range vt {
if len(v) > 0 {
rs = append(rs, v)
}
}
return strings.Join(rs, params.String()), nil
}
return src.Interface(), nil
}
//intval => src="123" => 123
func intval(src *reflect.Value, params *reflect.Value) (interface{}, error) {
switch src.Interface().(type) {
case string:
return strconv.Atoi(src.String())
case []string:
vt, _ := src.Interface().([]string)
rs := make([]int, len(vt))
for i := 0; i < len(vt); i++ {
v, _ := strconv.Atoi(vt[i])
rs[i] = v
}
return rs, nil
}
return 0, nil
}
//floatval => src="12.3" => 12.3
func floatval(src *reflect.Value, params *reflect.Value) (interface{}, error) {
switch src.Interface().(type) {
case string:
return strconv.ParseFloat(src.String(), 64)
case []string:
vt, _ := src.Interface().([]string)
rs := make([]float64, len(vt))
for i := 0; i < len(vt); i++ {
v, _ := strconv.ParseFloat(vt[i], 64)
rs[i] = v
}
return rs, nil
}
return 0.0, nil
}
//hrefreplace(data-url="$2") => src=`href="http://www.admpub.com"` => data-url="http://www.admpub.com"
func hrefreplace(src *reflect.Value, params *reflect.Value) (interface{}, error) {
switch src.Interface().(type) {
case string:
return hrefFilterExp2.Replace(src.String(), params.String(), 0, -1)
//return hrefFilterExp.ReplaceAllString(src.String(), params.String()), nil
case []string:
vt, _ := src.Interface().([]string)
for i := 0; i < len(vt); i++ {
vt[i], _ = hrefFilterExp2.Replace(src.String(), params.String(), 0, -1)
//vt[i] = hrefFilterExp.ReplaceAllString(vt[i], params.String())
}
return vt, nil
}
return src.Interface(), nil
}
func SplitParams(params string, separators ...string) []string {
separator := `,`
if len(separators) > 0 {
separator = separators[0]
if len(separator) < 1 {
return strings.Split(params, separator)
}
if len(separator) > 1 {
separator = separator[0:1]
}
}
vt := strings.Split(params, separator)
var (
lastEnd string
results []string
)
for k, v := range vt {
lastKey := k - 1
if lastEnd == `\` {
lastVal := vt[lastKey]
vt[lastKey] = lastVal[0:len(lastVal)-1] + separator + v
resultLen := len(results)
if resultLen > 0 {
results[resultLen-1] = vt[lastKey]
}
lastEnd = v[len(v)-1:]
continue
}
lastEnd = v[len(v)-1:]
results = append(results, v)
}
return results
}
//regexpreplace(^1) => src="1233" => "233"
//regexpreplace(^1,2) => src="1233" => "2233"
func regexpreplace(src *reflect.Value, params *reflect.Value) (interface{}, error) {
vt := SplitParams(params.String())
var (
expr string
repl string
startAt int
count = -1
)
switch len(vt) {
case 4:
count, _ = strconv.Atoi(vt[3])
fallthrough
case 3:
startAt, _ = strconv.Atoi(vt[2])
fallthrough
case 2:
repl = vt[1]
fallthrough
case 1:
expr = vt[0]
}
re, err := regexp2.Compile(expr, 0)
if err != nil {
return src.Interface(), err
}
switch src.Interface().(type) {
case string:
return re.Replace(src.String(), repl, startAt, count)
case []string:
vt, _ := src.Interface().([]string)
for i := 0; i < len(vt); i++ {
vt[i], _ = re.Replace(src.String(), repl, startAt, count)
}
return vt, nil
}
return src.Interface(), nil
}
// 将全角的标点符号和英文字母转换为半角
func _tosbc(src string) string {
var res string
for _, t := range src {
if t == 12288 {
t = 32
} else if t > 65280 && t < 65375 {
t = t - 65248
}
res += string(t)
}
return res
}
// tosbc => src="1~2" => "1~2"
func tosbc(src *reflect.Value, params *reflect.Value) (interface{}, error) {
switch src.Interface().(type) {
case string:
return _tosbc(src.String()), nil
case []string:
vt, _ := src.Interface().([]string)
for i := 0; i < len(vt); i++ {
vt[i] = _tosbc(vt[i])
}
return vt, nil
}
return src.Interface(), nil
}
// unescape => src="<" => "<"
func unescape(src *reflect.Value, params *reflect.Value) (interface{}, error) {
switch src.Interface().(type) {
case string:
return html.UnescapeString(src.String()), nil
case []string:
vt, _ := src.Interface().([]string)
for i := 0; i < len(vt); i++ {
vt[i] = html.UnescapeString(vt[i])
}
return vt, nil
}
return src.Interface(), nil
}
//escape => src="<" => "<"
func escape(src *reflect.Value, params *reflect.Value) (interface{}, error) {
switch src.Interface().(type) {
case string:
return html.EscapeString(src.String()), nil
case []string:
vt, _ := src.Interface().([]string)
for i := 0; i < len(vt); i++ {
vt[i] = html.EscapeString(vt[i])
}
return vt, nil
}
return src.Interface(), nil
}
//wraphtml(a) => <a>{src}</a>
func wraphtml(src *reflect.Value, params *reflect.Value) (interface{}, error) {
if params == nil {
return src.Interface(), errors.New("filter wraphtml nil params")
}
switch src.Interface().(type) {
case string:
return fmt.Sprintf("<%s>%s</%s>", params.String(), src.String(), params.String()), nil
case []string:
vt, _ := src.Interface().([]string)
for i := 0; i < len(vt); i++ {
vt[i] = fmt.Sprintf("<%s>%s</%s>", params.String(), vt[i], params.String())
}
return vt, nil
}
return src.Interface(), nil
}
//sprintf_multi_param(%veee%v) src=[1,2] => 1eee2
func sprintf_multi_param(src *reflect.Value, params *reflect.Value) (interface{}, error) {
if params == nil {
return src.Interface(), errors.New("filter split nil params ")
}
if src.Type().Kind() == reflect.Array || src.Type().Kind() == reflect.Slice {
count := strings.Count(params.String(), "%")
ret := make([]interface{}, 0)
for i := 0; i < src.Len(); i++ {
ret = append(ret, src.Index(i).Interface())
}
if len(ret) > count {
return fmt.Sprintf(params.String(), ret[:count]...), nil
}
return fmt.Sprintf(params.String(), ret...), nil
}
return fmt.Sprintf(params.String(), src.Interface()), nil
}
//sprintf(%s) src=a => a
func sprintf(src *reflect.Value, params *reflect.Value) (interface{}, error) {
if params == nil {
return src.Interface(), errors.New("filter split nil params")
}
switch src.Interface().(type) {
case string:
return fmt.Sprintf(params.String(), src.String()), nil
case []string:
vt, _ := src.Interface().([]string)
for i := 0; i < len(vt); i++ {
if len(vt[i]) <= 0 {
continue
}
vt[i] = fmt.Sprintf(params.String(), vt[i])
}
return vt, nil
}
return fmt.Sprintf(params.String(), src.Interface()), nil
}
//sprintfmap(%v-%v,a,b) src={"a":1,"b":2} => "1-2"
func sprintfmap(src *reflect.Value, params *reflect.Value) (interface{}, error) {
if params == nil {
return src.Interface(), errors.New("filter split nil params")
}
msrc, ok := src.Interface().(map[string]interface{})
if ok == false {
return src.Interface(), errors.New("value is not map[string]interface{}")
}
vt := SplitParams(params.String())
if len(vt) <= 1 {
return src.Interface(), errors.New("params length must > 1")
}
pArray := []interface{}{}
for _, x := range vt[1:] {
if vm, ok := msrc[x]; ok {
pArray = append(pArray, vm)
} else {
pArray = append(pArray, nil)
}
}
return fmt.Sprintf(vt[0], pArray...), nil
}
//unixtime 时间戳(总秒数)
func unixtime(src *reflect.Value, params *reflect.Value) (interface{}, error) {
return time.Now().Unix(), nil
}
//unixmill 时间戳(总毫秒数)
func unixmill(src *reflect.Value, params *reflect.Value) (interface{}, error) {
return time.Now().UnixNano() / int64(time.Millisecond), nil
}
//paging(startAt,endAt,step)
//paging(1,10) / paging(1,10,2)
func paging(src *reflect.Value, params *reflect.Value) (interface{}, error) {
if params == nil {
return src.Interface(), errors.New("filter paging nil params")
}
srcType := src.Type().Kind()
if srcType != reflect.Slice && srcType != reflect.Array && srcType != reflect.String {
return src.Interface(), errors.New("value is not slice ,array or string")
}
vt := strings.Split(params.String(), ",")
if len(vt) < 2 {
return src.Interface(), errors.New("params length must > 1")
}
start, err := strconv.Atoi(vt[0])
if err != nil {
return src.Interface(), errors.New("params type error:need int." + err.Error())
}
end, err := strconv.Atoi(vt[1])
if err != nil {
return src.Interface(), errors.New("params type error:need int." + err.Error())
}
offset := -1
if len(vt) == 3 {
offset, err = strconv.Atoi(vt[2])
if err != nil {
return src.Interface(), errors.New("params type error:need int." + err.Error())
}
if offset < 1 {
return src.Interface(), errors.New("offset must > 0")
}
}
var result []string
switch src.Interface().(type) {
case []interface{}:
vt, _ := src.Interface().([]interface{})
for i := start; i <= end; i++ {
for j := 0; j < len(vt); j++ {
if offset > 0 {
result = append(result, sprintf_replace(vt[j].(string), []string{strconv.Itoa(i * offset), strconv.Itoa((i + 1) * offset)}))
} else {
result = append(result, sprintf_replace(vt[j].(string), []string{strconv.Itoa(i)}))
}
}
}
return result, nil
case []string:
vt, _ := src.Interface().([]string)
for i := start; i <= end; i++ {
for j := 0; j < len(vt); j++ {
if offset > 0 {
result = append(result, sprintf_replace(vt[i], []string{strconv.Itoa(i * offset), strconv.Itoa((i + 1) * offset)}))
} else {
result = append(result, sprintf_replace(vt[i], []string{strconv.Itoa(i)}))
}
}
}
return result, nil
case string:
msrc1, ok := src.Interface().(string)
if ok == true {
for i := start; i <= end; i++ {
if offset > 0 {
result = append(result, sprintf_replace(msrc1, []string{strconv.Itoa(i * offset), strconv.Itoa((i + 1) * offset)}))
} else {
result = append(result, sprintf_replace(msrc1, []string{strconv.Itoa(i)}))
}
}
return result, nil
}
}
return src.Interface(), errors.New("do nothing,src type not support!")
}
func sprintf_replace(src string, param []string) string {
for i := range param {
src = strings.Replace(src, "{"+strconv.Itoa(i)+"}", param[i], -1)
}
return src
}
//quote => src=`a` => `"a"`
func quote(src *reflect.Value, params *reflect.Value) (interface{}, error) {
switch src.Interface().(type) {
case string:
return strconv.Quote(src.String()), nil
case []string:
vt, _ := src.Interface().([]string)
for i := 0; i < len(vt); i++ {
vt[i] = strconv.Quote(vt[i])
}
return vt, nil
}
return src.Interface(), nil
}
//unquote => src=`"a"` => `a`
func unquote(src *reflect.Value, params *reflect.Value) (interface{}, error) {
switch src.Interface().(type) {
case string:
return strconv.Unquote(`"` + src.String() + `"`)
case []string:
vt, _ := src.Interface().([]string)
for i := 0; i < len(vt); i++ {
vt[i], _ = strconv.Unquote(`"` + vt[i] + `"`)
}
return vt, nil
}
return src.Interface(), nil
}