-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
68 lines (63 loc) · 1.86 KB
/
main.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
package control
import (
"context"
"encoding/json"
"errors"
"log/slog"
"net/http"
"github.com/ecwid/control/cdp"
"github.com/ecwid/control/chrome"
"github.com/ecwid/control/protocol/target"
)
func Take(args ...string) (session *Session, cancel func() error, err error) {
return TakeWithContext(context.TODO(), nil, args...)
}
func TakeWithContext(ctx context.Context, logger *slog.Logger, chromeArgs ...string) (session *Session, cancel func() error, err error) {
browser, err := chrome.Launch(ctx, chromeArgs...)
if err != nil {
return nil, nil, errors.Join(err, errors.New("chrome launch failed"))
}
tab, err := browser.NewTab(http.DefaultClient, "")
if err != nil {
return nil, nil, errors.Join(err, errors.New("failed to open a new tab"))
}
transport, err := cdp.DefaultDial(ctx, browser.WebSocketUrl, logger)
if err != nil {
return nil, nil, errors.Join(err, errors.New("websocket dial failed"))
}
session, err = NewSession(transport, target.TargetID(tab.ID))
if err != nil {
return nil, nil, errors.Join(err, errors.New("failed to create a new session"))
}
teardown := func() error {
if err := transport.Close(); err != nil {
return errors.Join(err, errors.New("can't close transport"))
}
if err = browser.WaitCloseGracefully(); err != nil {
return errors.Join(err, errors.New("can't close browser gracefully"))
}
return nil
}
return session, teardown, nil
}
func Subscribe[T any](s *Session, method string, filter func(T) bool) cdp.Future[T] {
var (
channel, cancel = s.Subscribe()
)
callback := func(resolve func(T), reject func(error)) {
for value := range channel {
if value.Method == method {
var result T
if err := json.Unmarshal(value.Params, &result); err != nil {
reject(err)
return
}
if filter(result) {
resolve(result)
return
}
}
}
}
return cdp.NewPromise(callback, cancel)
}