-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
100 lines (88 loc) · 2.59 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
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
package control
import (
"context"
"encoding/json"
"errors"
"log/slog"
"net/http"
"os"
"strings"
"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 hasProfile(args ...string) bool {
for _, a := range args {
a = strings.TrimSpace(a)
if strings.HasPrefix(a, "--profile-directory") || strings.HasPrefix(a, "--user-data-dir") {
return true
}
}
return false
}
func TakeWithContext(ctx context.Context, logger *slog.Logger, args ...string) (session *Session, cancel func() error, err error) {
var userDataDir string
if !hasProfile(args...) {
// If there is no profile or user-data-dir in the startup arguments, then user-data-dir must be set
userDataDir, err = os.MkdirTemp("", "chrome-control-*")
if err != nil {
return nil, nil, errors.Join(err, errors.New("can't create temporary user data dir"))
}
args = append(args, "--user-data-dir="+userDataDir)
}
browser, err := chrome.Launch(ctx, args...)
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"))
}
cleanup := func() error {
if err := transport.Close(); err != nil {
return errors.Join(err, errors.New("can't close transport"))
}
if err = browser.Wait(); err != nil {
return errors.Join(err, errors.New("can't close browser gracefully"))
}
if userDataDir != "" {
if err := os.RemoveAll(userDataDir); err != nil {
return errors.Join(err, errors.New("can't clear user data dir"))
}
}
return nil
}
return session, cleanup, 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)
}