vendor/github.com/go-rod/rod/lib/launcher/browser.go
279 lines · 7176 bytes
1package launcher
2
3import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "log"
9 "net/http"
10 "os"
11 "os/exec"
12 "path/filepath"
13 "runtime"
14 "strings"
15
16 "github.com/go-rod/rod/lib/defaults"
17 "github.com/go-rod/rod/lib/utils"
18 "github.com/ysmood/fetchup"
19 "github.com/ysmood/leakless"
20)
21
22// Host formats a revision number to a downloadable URL for the browser.
23type Host func(revision int) string
24
25var hostConf = map[string]struct {
26 urlPrefix string
27 zipName string
28}{
29 "darwin_amd64": {"Mac", "chrome-mac.zip"},
30 "darwin_arm64": {"Mac_Arm", "chrome-mac.zip"},
31 "linux_amd64": {"Linux_x64", "chrome-linux.zip"},
32 "windows_386": {"Win", "chrome-win.zip"},
33 "windows_amd64": {"Win_x64", "chrome-win.zip"},
34}[runtime.GOOS+"_"+runtime.GOARCH]
35
36// HostGoogle to download browser.
37func HostGoogle(revision int) string {
38 return fmt.Sprintf(
39 "https://storage.googleapis.com/chromium-browser-snapshots/%s/%d/%s",
40 hostConf.urlPrefix,
41 revision,
42 hostConf.zipName,
43 )
44}
45
46// HostNPM to download browser.
47func HostNPM(revision int) string {
48 return fmt.Sprintf(
49 "https://registry.npmmirror.com/-/binary/chromium-browser-snapshots/%s/%d/%s",
50 hostConf.urlPrefix,
51 revision,
52 hostConf.zipName,
53 )
54}
55
56// HostPlaywright to download browser.
57func HostPlaywright(revision int) string {
58 rev := RevisionPlaywright
59 if !(runtime.GOOS == "linux" && runtime.GOARCH == "arm64") {
60 rev = revision
61 }
62 return fmt.Sprintf(
63 "https://playwright.azureedge.net/builds/chromium/%d/chromium-linux-arm64.zip",
64 rev,
65 )
66}
67
68// DefaultBrowserDir for downloaded browser. For unix is "$HOME/.cache/rod/browser",
69// for Windows it's "%APPDATA%\rod\browser".
70var DefaultBrowserDir = filepath.Join(map[string]string{
71 "windows": os.Getenv("APPDATA"),
72 "darwin": filepath.Join(os.Getenv("HOME"), ".cache"),
73 "linux": filepath.Join(os.Getenv("HOME"), ".cache"),
74}[runtime.GOOS], "rod", "browser")
75
76// Browser is a helper to download browser smartly.
77type Browser struct {
78 Context context.Context
79
80 // Hosts are the candidates to download the browser.
81 // Such as [HostGoogle] or [HostNPM].
82 Hosts []Host
83
84 // Revision of the browser to use
85 Revision int
86
87 // RootDir to download different browser versions.
88 RootDir string
89
90 // Log to print output
91 Logger utils.Logger
92
93 // LockPort a tcp port to prevent race downloading. Default is 2968 .
94 LockPort int
95
96 // HTTPClient to download the browser
97 HTTPClient *http.Client
98}
99
100// NewBrowser with default values.
101func NewBrowser() *Browser {
102 return &Browser{
103 Context: context.Background(),
104 Revision: RevisionDefault,
105 Hosts: []Host{HostGoogle, HostNPM, HostPlaywright},
106 RootDir: DefaultBrowserDir,
107 Logger: log.New(os.Stdout, "[launcher.Browser]", log.LstdFlags),
108 LockPort: defaults.LockPort,
109 }
110}
111
112// Dir to download the browser.
113func (lc *Browser) Dir() string {
114 return filepath.Join(lc.RootDir, fmt.Sprintf("chromium-%d", lc.Revision))
115}
116
117// BinPath to download the browser executable.
118func (lc *Browser) BinPath() string {
119 bin := map[string]string{
120 "darwin": "Chromium.app/Contents/MacOS/Chromium",
121 "linux": "chrome",
122 "windows": "chrome.exe",
123 }[runtime.GOOS]
124
125 return filepath.Join(lc.Dir(), filepath.FromSlash(bin))
126}
127
128// Download browser from the fastest host.
129// It will race downloading a TCP packet from each host and use the fastest host.
130func (lc *Browser) Download() error {
131 us := []string{}
132 for _, host := range lc.Hosts {
133 us = append(us, host(lc.Revision))
134 }
135
136 dir := lc.Dir()
137
138 fu := fetchup.New(dir, us...)
139 fu.Ctx = lc.Context
140 fu.Logger = lc.Logger
141 if lc.HTTPClient != nil {
142 fu.HttpClient = lc.HTTPClient
143 }
144
145 err := fu.Fetch()
146 if err != nil {
147 return fmt.Errorf("can't find a browser binary for your OS, the doc might help https://go-rod.github.io/#/compatibility?id=os : %w", err) //nolint: lll
148 }
149
150 return fetchup.StripFirstDir(dir)
151}
152
153// Get is a smart helper to get the browser executable path.
154// If [Browser.BinPath] is not valid it will auto download the browser to [Browser.BinPath].
155func (lc *Browser) Get() (string, error) {
156 defer leakless.LockPort(lc.LockPort)()
157
158 if lc.Validate() == nil {
159 return lc.BinPath(), nil
160 }
161
162 // Try to cleanup before downloading
163 _ = os.RemoveAll(lc.Dir())
164
165 return lc.BinPath(), lc.Download()
166}
167
168// MustGet is similar with Get.
169func (lc *Browser) MustGet() string {
170 p, err := lc.Get()
171 utils.E(err)
172 return p
173}
174
175// Validate returns nil if the browser executable is valid.
176// If the executable is malformed it will return error.
177func (lc *Browser) Validate() error {
178 _, err := os.Stat(lc.BinPath())
179 if err != nil {
180 return err
181 }
182
183 cmd := exec.Command(lc.BinPath(), "--headless", "--no-sandbox",
184 "--use-mock-keychain", "--disable-dev-shm-usage",
185 "--disable-gpu", "--dump-dom", "about:blank")
186 b, err := cmd.CombinedOutput()
187 if err != nil {
188 if strings.Contains(string(b), "error while loading shared libraries") {
189 // When the os is missing some dependencies for chromium we treat it as valid binary.
190 return nil
191 }
192
193 return fmt.Errorf("failed to run the browser: %w\n%s", err, b)
194 }
195 if !bytes.Contains(b, []byte(`<html><head></head><body></body></html>`)) {
196 return errors.New("the browser executable doesn't support headless mode")
197 }
198
199 return nil
200}
201
202// LookPath searches for the browser executable from often used paths on current operating system.
203func LookPath() (found string, has bool) {
204 list := map[string][]string{
205 "darwin": {
206 "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
207 "/Applications/Chromium.app/Contents/MacOS/Chromium",
208 "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
209 "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
210 "/usr/bin/google-chrome-stable",
211 "/usr/bin/google-chrome",
212 "/usr/bin/chromium",
213 "/usr/bin/chromium-browser",
214 },
215 "linux": {
216 "chrome",
217 "google-chrome",
218 "/usr/bin/google-chrome",
219 "microsoft-edge",
220 "/usr/bin/microsoft-edge",
221 "chromium",
222 "chromium-browser",
223 "/usr/bin/google-chrome-stable",
224 "/usr/bin/chromium",
225 "/usr/bin/chromium-browser",
226 "/snap/bin/chromium",
227 "/data/data/com.termux/files/usr/bin/chromium-browser",
228 },
229 "openbsd": {
230 "chrome",
231 "chromium",
232 },
233 "windows": append([]string{"chrome", "edge"}, expandWindowsExePaths(
234 `Google\Chrome\Application\chrome.exe`,
235 `Chromium\Application\chrome.exe`,
236 `Microsoft\Edge\Application\msedge.exe`,
237 )...),
238 }[runtime.GOOS]
239
240 for _, path := range list {
241 var err error
242 found, err = exec.LookPath(path)
243 has = err == nil
244 if has {
245 break
246 }
247 }
248
249 return
250}
251
252// interface for testing.
253var openExec = exec.Command
254
255// Open tries to open the url via system's default browser.
256func Open(url string) {
257 // Windows doesn't support format [::]
258 url = strings.Replace(url, "[::]", "[::1]", 1)
259
260 if bin, has := LookPath(); has {
261 p := openExec(bin, url)
262 _ = p.Start()
263 _ = p.Process.Release()
264 }
265}
266
267func expandWindowsExePaths(list ...string) []string {
268 newList := []string{}
269 for _, p := range list {
270 newList = append(
271 newList,
272 filepath.Join(os.Getenv("ProgramFiles"), p),
273 filepath.Join(os.Getenv("ProgramFiles(x86)"), p),
274 filepath.Join(os.Getenv("LocalAppData"), p),
275 )
276 }
277
278 return newList
279}