vendor/github.com/go-rod/rod/utils.go
271 lines · 5941 bytes
1package rod
2
3import (
4 "bytes"
5 "context"
6 "encoding/base64"
7 "encoding/json"
8 "fmt"
9 "io"
10 "log"
11 "net/http"
12 "os"
13 "path/filepath"
14 "reflect"
15 "regexp"
16 "runtime/debug"
17 "sync"
18 "time"
19
20 "github.com/go-rod/rod/lib/cdp"
21 "github.com/go-rod/rod/lib/proto"
22 "github.com/go-rod/rod/lib/utils"
23)
24
25// CDPClient is usually used to make rod side-effect free. Such as proxy all IO of rod.
26type CDPClient interface {
27 Event() <-chan *cdp.Event
28 Call(ctx context.Context, sessionID, method string, params interface{}) ([]byte, error)
29}
30
31// Message represents a cdp.Event.
32type Message struct {
33 SessionID proto.TargetSessionID
34 Method string
35
36 lock *sync.Mutex
37 data json.RawMessage
38 event reflect.Value
39}
40
41// Load data into e, returns true if e matches the event type.
42func (msg *Message) Load(e proto.Event) bool {
43 if msg.Method != e.ProtoEvent() {
44 return false
45 }
46
47 eVal := reflect.ValueOf(e)
48 if eVal.Kind() != reflect.Ptr {
49 return true
50 }
51 eVal = reflect.Indirect(eVal)
52
53 msg.lock.Lock()
54 defer msg.lock.Unlock()
55 if msg.data == nil {
56 eVal.Set(msg.event)
57 return true
58 }
59
60 utils.E(json.Unmarshal(msg.data, e))
61 msg.event = eVal
62 msg.data = nil
63 return true
64}
65
66// DefaultLogger for rod.
67var DefaultLogger = log.New(os.Stdout, "[rod] ", log.LstdFlags)
68
69// DefaultSleeper generates the default sleeper for retry, it uses backoff to grow the interval.
70// The growth looks like:
71//
72// A(0) = 100ms, A(n) = A(n-1) * random[1.9, 2.1), A(n) < 1s
73//
74// Why the default is not RequestAnimationFrame or DOM change events is because of if a retry never
75// ends it can easily flood the program. But you can always easily config it into what you want.
76var DefaultSleeper = func() utils.Sleeper {
77 return utils.BackoffSleeper(100*time.Millisecond, time.Second, nil)
78}
79
80// NewPagePool instance.
81func NewPagePool(limit int) Pool[Page] {
82 return NewPool[Page](limit)
83}
84
85// NewBrowserPool instance.
86func NewBrowserPool(limit int) Pool[Browser] {
87 return NewPool[Browser](limit)
88}
89
90// Pool is used to thread-safely limit the number of elements at the same time.
91// It's a common practice to use a channel to limit concurrency, it's not special for rod.
92// This helper is more like an example to use Go Channel.
93// Reference: https://golang.org/doc/effective_go#channels
94type Pool[T any] chan *T
95
96// NewPool instance.
97func NewPool[T any](limit int) Pool[T] {
98 p := make(chan *T, limit)
99 for i := 0; i < limit; i++ {
100 p <- nil
101 }
102 return p
103}
104
105// Get a elem from the pool, allow error. Use the [Pool[T].Put] to make it reusable later.
106func (p Pool[T]) Get(create func() (*T, error)) (elem *T, err error) {
107 elem = <-p
108 if elem == nil {
109 elem, err = create()
110 }
111 return
112}
113
114// Put an elem back to the pool.
115func (p Pool[T]) Put(elem *T) {
116 p <- elem
117}
118
119// Cleanup helper.
120func (p Pool[T]) Cleanup(iteratee func(*T)) {
121 for i := 0; i < cap(p); i++ {
122 select {
123 case elem := <-p:
124 if elem != nil {
125 iteratee(elem)
126 }
127 default:
128 }
129 }
130}
131
132var _ io.ReadCloser = &StreamReader{}
133
134// StreamReader for browser data stream.
135type StreamReader struct {
136 Offset *int
137
138 c proto.Client
139 handle proto.IOStreamHandle
140 buf *bytes.Buffer
141}
142
143// NewStreamReader instance.
144func NewStreamReader(c proto.Client, h proto.IOStreamHandle) *StreamReader {
145 return &StreamReader{
146 c: c,
147 handle: h,
148 buf: &bytes.Buffer{},
149 }
150}
151
152func (sr *StreamReader) Read(p []byte) (n int, err error) {
153 res, err := proto.IORead{
154 Handle: sr.handle,
155 Offset: sr.Offset,
156 }.Call(sr.c)
157 if err != nil {
158 return 0, err
159 }
160
161 if !res.EOF {
162 var bin []byte
163 if res.Base64Encoded {
164 bin, err = base64.StdEncoding.DecodeString(res.Data)
165 if err != nil {
166 return 0, err
167 }
168 } else {
169 bin = []byte(res.Data)
170 }
171
172 _, _ = sr.buf.Write(bin)
173 }
174
175 return sr.buf.Read(p)
176}
177
178// Close the stream, discard any temporary backing storage.
179func (sr *StreamReader) Close() error {
180 return proto.IOClose{Handle: sr.handle}.Call(sr.c)
181}
182
183// Try try fn with recover, return the panic as rod.ErrTry.
184func Try(fn func()) (err error) {
185 defer func() {
186 if val := recover(); val != nil {
187 err = &TryError{val, string(debug.Stack())}
188 }
189 }()
190
191 fn()
192
193 return err
194}
195
196func genRegMatcher(includes, excludes []string) func(string) bool {
197 regIncludes := make([]*regexp.Regexp, len(includes))
198 for i, p := range includes {
199 regIncludes[i] = regexp.MustCompile(p)
200 }
201
202 regExcludes := make([]*regexp.Regexp, len(excludes))
203 for i, p := range excludes {
204 regExcludes[i] = regexp.MustCompile(p)
205 }
206
207 return func(s string) bool {
208 for _, include := range regIncludes {
209 if include.MatchString(s) {
210 for _, exclude := range regExcludes {
211 if exclude.MatchString(s) {
212 goto end
213 }
214 }
215 return true
216 }
217 }
218 end:
219 return false
220 }
221}
222
223type saveFileType int
224
225const (
226 saveFileTypeScreenshot saveFileType = iota
227 saveFileTypePDF
228)
229
230func saveFile(fileType saveFileType, bin []byte, toFile []string) error {
231 if len(toFile) == 0 {
232 return nil
233 }
234 if toFile[0] == "" {
235 stamp := fmt.Sprintf("%d", time.Now().UnixNano())
236 switch fileType {
237 case saveFileTypeScreenshot:
238 toFile = []string{"tmp", "screenshots", stamp + ".png"}
239 case saveFileTypePDF:
240 toFile = []string{"tmp", "pdf", stamp + ".pdf"}
241 }
242 }
243 return utils.OutputFile(filepath.Join(toFile...), bin)
244}
245
246func httHTML(w http.ResponseWriter, body string) {
247 w.Header().Add("Content-Type", "text/html; charset=utf-8")
248 _, _ = w.Write([]byte(body))
249}
250
251func mustToJSONForDev(value interface{}) string {
252 buf := new(bytes.Buffer)
253 enc := json.NewEncoder(buf)
254 enc.SetEscapeHTML(false)
255
256 utils.E(enc.Encode(value))
257
258 return buf.String()
259}
260
261// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
262var regDataURI = regexp.MustCompile(`\Adata:(.+?)?(;base64)?,`)
263
264func parseDataURI(uri string) (string, []byte) {
265 matches := regDataURI.FindStringSubmatch(uri)
266 l := len(matches[0])
267 contentType := matches[1]
268
269 bin, _ := base64.StdEncoding.DecodeString(uri[l:])
270 return contentType, bin
271}