-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
dev_helpers.go
273 lines (222 loc) · 6.73 KB
/
dev_helpers.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
// This file defines the helpers to develop automation.
// 这个文件定义了一些开发自动化的辅助工具
// Such as when running automation we can use trace to visually
// see where the mouse going to click.
// 如在运行自动化时,我们可以用trace(跟踪)来直观地看到鼠标要点击的地方。
package rod
import (
"encoding/json"
"fmt"
"html"
"net"
"net/http"
"strings"
"time"
"github.com/go-rod/rod/lib/assets"
"github.com/go-rod/rod/lib/js"
"github.com/go-rod/rod/lib/proto"
"github.com/go-rod/rod/lib/utils"
)
// TraceType for logger
// 日志的 Trace 类型
type TraceType string
// String interface
func (t TraceType) String() string {
return fmt.Sprintf("[%s]", string(t))
}
const (
// TraceTypeWaitRequestsIdle type
TraceTypeWaitRequestsIdle TraceType = "wait requests idle"
// TraceTypeWaitRequests type
TraceTypeWaitRequests TraceType = "wait requests"
// TraceTypeQuery type
TraceTypeQuery TraceType = "query"
// TraceTypeWait type
TraceTypeWait TraceType = "wait"
// TraceTypeInput type
TraceTypeInput TraceType = "input"
)
// ServeMonitor starts the monitor server.
// 启动一个监控服务
// The reason why not to use "chrome://inspect/#devices" is one target cannot be driven by multiple controllers.
// 不使用 "chrome://inspect/#devices "的原因是一个目标不能被多个控制器驱动。
func (b *Browser) ServeMonitor(host string) string {
url, mux, close := serve(host)
go func() {
<-b.ctx.Done()
utils.E(close())
}()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
httHTML(w, assets.Monitor)
})
mux.HandleFunc("/api/pages", func(w http.ResponseWriter, r *http.Request) {
res, err := proto.TargetGetTargets{}.Call(b)
utils.E(err)
list := []*proto.TargetTargetInfo{}
for _, info := range res.TargetInfos {
if info.Type == proto.TargetTargetInfoTypePage {
list = append(list, info)
}
}
w.WriteHeader(http.StatusOK)
utils.E(w.Write(utils.MustToJSONBytes(list)))
})
mux.HandleFunc("/page/", func(w http.ResponseWriter, r *http.Request) {
httHTML(w, assets.MonitorPage)
})
mux.HandleFunc("/api/page/", func(w http.ResponseWriter, r *http.Request) {
id := r.URL.Path[strings.LastIndex(r.URL.Path, "/")+1:]
info, err := b.pageInfo(proto.TargetTargetID(id))
utils.E(err)
w.WriteHeader(http.StatusOK)
utils.E(w.Write(utils.MustToJSONBytes(info)))
})
mux.HandleFunc("/screenshot/", func(w http.ResponseWriter, r *http.Request) {
id := r.URL.Path[strings.LastIndex(r.URL.Path, "/")+1:]
target := proto.TargetTargetID(id)
p := b.MustPageFromTargetID(target)
w.Header().Add("Content-Type", "image/png;")
utils.E(w.Write(p.MustScreenshot()))
})
return url
}
// check method and sleep if needed
// 检查方法并在需要时进行睡眠。
func (b *Browser) trySlowmotion() {
if b.slowMotion == 0 {
return
}
time.Sleep(b.slowMotion)
}
// ExposeHelpers helper functions to page's js context so that we can use the Devtools' console to debug them.
// 将ExposeHelpers的辅助函数放到页面的js ctx 中,这样我们就可以使用Devtools的控制台来调试它们。
func (p *Page) ExposeHelpers(list ...*js.Function) {
p.MustEvaluate(evalHelper(&js.Function{
Name: "_" + utils.RandString(8), // use a random name so it won't hit the cache
Definition: "() => { window.rod = functions }",
Dependencies: list,
}))
}
// Overlay a rectangle on the main frame with specified message
// 在主 Frame 上叠加一个带有指定消息的矩形
func (p *Page) Overlay(left, top, width, height float64, msg string) (remove func()) {
id := utils.RandString(8)
_, _ = p.root.Evaluate(evalHelper(js.Overlay,
id,
left,
top,
width,
height,
msg,
).ByPromise())
remove = func() {
_, _ = p.root.Evaluate(evalHelper(js.RemoveOverlay, id))
}
return
}
func (p *Page) tryTrace(typ TraceType, msg ...interface{}) func() {
if !p.browser.trace {
return func() {}
}
msg = append([]interface{}{typ}, msg...)
msg = append(msg, p)
p.browser.logger.Println(msg...)
return p.Overlay(0, 0, 500, 0, fmt.Sprint(msg))
}
func (p *Page) tryTraceQuery(opts *EvalOptions) func() {
if !p.browser.trace {
return func() {}
}
p.browser.logger.Println(TraceTypeQuery, opts, p)
msg := fmt.Sprintf("<code>%s</code>", html.EscapeString(opts.String()))
return p.Overlay(0, 0, 500, 0, msg)
}
func (p *Page) tryTraceReq(includes, excludes []string) func(map[proto.NetworkRequestID]string) {
if !p.browser.trace {
return func(map[proto.NetworkRequestID]string) {}
}
msg := map[string][]string{
"includes": includes,
"excludes": excludes,
}
p.browser.logger.Println(TraceTypeWaitRequestsIdle, msg, p)
cleanup := p.Overlay(0, 0, 500, 0, utils.MustToJSON(msg))
ch := make(chan map[string]string)
update := func(list map[proto.NetworkRequestID]string) {
clone := map[string]string{}
for k, v := range list {
clone[string(k)] = v
}
ch <- clone
}
go func() {
var waitlist map[string]string
t := time.NewTicker(time.Second)
for {
select {
case <-p.ctx.Done():
t.Stop()
cleanup()
return
case waitlist = <-ch:
case <-t.C:
p.browser.logger.Println(TraceTypeWaitRequests, p, waitlist)
}
}
}()
return update
}
// Overlay msg on the element
// 在元素上叠加 msg
func (el *Element) Overlay(msg string) (removeOverlay func()) {
id := utils.RandString(8)
_, _ = el.Evaluate(evalHelper(js.ElementOverlay,
id,
msg,
).ByPromise())
removeOverlay = func() {
_, _ = el.Evaluate(evalHelper(js.RemoveOverlay, id))
}
return
}
func (el *Element) tryTrace(typ TraceType, msg ...interface{}) func() {
if !el.page.browser.trace {
return func() {}
}
msg = append([]interface{}{typ}, msg...)
msg = append(msg, el)
el.page.browser.logger.Println(msg...)
return el.Overlay(fmt.Sprint(msg))
}
func (m *Mouse) initMouseTracer() {
_, _ = m.page.Evaluate(evalHelper(js.InitMouseTracer, m.id, assets.MousePointer).ByPromise())
}
func (m *Mouse) updateMouseTracer() bool {
res, err := m.page.Evaluate(evalHelper(js.UpdateMouseTracer, m.id, m.x, m.y))
if err != nil {
return true
}
return res.Value.Bool()
}
// Serve a port, if host is empty a random port will be used.
// 为端口提供服务,如果主机为空,将使用随机端口。
func serve(host string) (string, *http.ServeMux, func() error) {
if host == "" {
host = "127.0.0.1:0"
}
mux := http.NewServeMux()
srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
w.WriteHeader(http.StatusBadRequest)
utils.E(json.NewEncoder(w).Encode(err))
}
}()
mux.ServeHTTP(w, r)
})}
l, err := net.Listen("tcp", host)
utils.E(err)
go func() { _ = srv.Serve(l) }()
url := "http://" + l.Addr().String()
return url, mux, srv.Close
}