forked from go-rod/rod
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
104 lines (90 loc) · 2.36 KB
/
utils.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
package rod
import (
"context"
"encoding/json"
"fmt"
"path/filepath"
"reflect"
"regexp"
"time"
"github.com/ysmood/goob"
"github.com/ysmood/kit"
"github.com/ysmood/rod/lib/cdp"
"github.com/ysmood/rod/lib/proto"
)
// Array of any type
type Array []interface{}
// SprintFnApply is a helper to render template into js code
// js looks like "(a, b) => {}", the a and b are the params passed into the function
func sprintFnApply(js string, params Array) string {
const tpl = `(%s).apply(this, %s)`
return fmt.Sprintf(tpl, js, kit.MustToJSON(params))
}
// SprintFnThis wrap js with this
func SprintFnThis(js string) string {
return fmt.Sprintf(`function() { return (%s).apply(this, arguments) }`, js)
}
// CancelPanic graceful panic
func CancelPanic(err error) {
if err != nil && err != context.Canceled {
panic(err)
}
}
// Event helps to convert a cdp.Event to proto.Event. Returns false if the conversion fails
func Event(msg *cdp.Event, evt proto.Event) bool {
if msg.Method == evt.MethodName() {
err := json.Unmarshal(msg.Params, evt)
return err == nil
}
return false
}
func isNilContextErr(err error) bool {
if err == nil {
return false
}
cdpErr, ok := err.(*cdp.Error)
return ok && cdpErr.Code == -32000
}
func matchWithFilter(s string, includes, excludes []string) bool {
for _, include := range includes {
if regexp.MustCompile(include).MatchString(s) {
for _, exclude := range excludes {
if regexp.MustCompile(exclude).MatchString(s) {
return false
}
}
return true
}
}
return false
}
func saveScreenshot(bin []byte, toFile []string) error {
if len(toFile) == 0 {
return nil
}
if toFile[0] == "" {
toFile = []string{"tmp", "screenshots", fmt.Sprintf("%d", time.Now().UnixNano()) + ".png"}
}
return kit.OutputFile(filepath.Join(toFile...), bin, nil)
}
func ginHTML(ctx kit.GinContext, body string) {
ctx.Header("Content-Type", "text/html; charset=utf-8")
_, _ = ctx.Writer.WriteString(body)
}
func eachEvent(s chan goob.Event) func(fn interface{}) {
return func(fn interface{}) {
fnType := reflect.TypeOf(fn)
fnVal := reflect.ValueOf(fn)
eventType := fnType.In(0).Elem()
goob.Each(s, func(e *cdp.Event) bool {
event := reflect.New(eventType)
if Event(e, event.Interface().(proto.Event)) {
ret := fnVal.Call([]reflect.Value{event})
if len(ret) > 0 {
return ret[0].Bool()
}
}
return false
})
}
}