-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathbrowser.go
More file actions
473 lines (397 loc) · 10.8 KB
/
browser.go
File metadata and controls
473 lines (397 loc) · 10.8 KB
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
package browser
import (
"context"
"fmt"
"os"
"path/filepath"
"sync"
"time"
"github.com/go-rod/rod"
"github.com/go-rod/rod/lib/launcher"
"github.com/go-rod/rod/lib/proto"
"github.com/anxuanzi/bua/dom"
)
// Config holds browser configuration.
type Config struct {
// Headless runs the browser without a visible window.
Headless bool
// ProfileDir is the directory for browser profiles.
ProfileDir string
// ProfileName is the name of the profile to use.
// Empty string uses a temporary profile.
ProfileName string
// Viewport is the browser viewport size.
ViewportWidth int
ViewportHeight int
// ShowHighlight shows visual feedback for actions.
ShowHighlight bool
// HighlightDuration is how long to show highlights.
HighlightDuration time.Duration
// Debug enables verbose logging.
Debug bool
// ShowAnnotations enables element annotations on screenshots.
// When true, screenshots include bounding boxes and index labels.
ShowAnnotations bool
// Stealth configures anti-detection measures.
Stealth StealthConfig
}
// DefaultConfig returns a default browser configuration.
func DefaultConfig() Config {
return Config{
Headless: false,
ViewportWidth: 1280,
ViewportHeight: 720,
ShowHighlight: true,
HighlightDuration: 300 * time.Millisecond,
Stealth: DefaultStealthConfig(),
}
}
// TabInfo contains information about an open tab.
type TabInfo struct {
ID string
URL string
Title string
Active bool
}
// Browser wraps rod.Browser with enhanced functionality.
type Browser struct {
config Config
rod *rod.Browser
launcher *launcher.Launcher
// Tab management
pages map[string]*rod.Page
activeTabID string
// DOM extraction
extractor *dom.Extractor
// Temporary profile path for cleanup
tempProfilePath string
mu sync.RWMutex
}
// New creates a new browser instance.
func New(cfg Config) (*Browser, error) {
b := &Browser{
config: cfg,
pages: make(map[string]*rod.Page),
}
// Set default values
if cfg.ViewportWidth == 0 {
b.config.ViewportWidth = 1280
}
if cfg.ViewportHeight == 0 {
b.config.ViewportHeight = 720
}
if cfg.HighlightDuration == 0 {
b.config.HighlightDuration = 300 * time.Millisecond
}
return b, nil
}
// Start launches the browser.
func (b *Browser) Start(ctx context.Context) error {
b.mu.Lock()
defer b.mu.Unlock()
if b.rod != nil {
return fmt.Errorf("browser already started")
}
// Configure launcher
l := launcher.New()
if b.config.Headless {
l = l.Headless(true)
} else {
l = l.Headless(false)
}
// Configure profile
if b.config.ProfileName != "" {
// Use named profile
profilePath := filepath.Join(b.config.ProfileDir, b.config.ProfileName)
if err := os.MkdirAll(profilePath, 0755); err != nil {
return fmt.Errorf("failed to create profile directory: %w", err)
}
l = l.UserDataDir(profilePath)
} else {
// Use temporary profile
tempDir, err := os.MkdirTemp("", "bua-browser-*")
if err != nil {
return fmt.Errorf("failed to create temp profile: %w", err)
}
b.tempProfilePath = tempDir
l = l.UserDataDir(tempDir)
}
// Additional Chrome flags for general operation
l = l.Set("disable-background-networking").
Set("disable-breakpad").
Set("disable-client-side-phishing-detection").
Set("disable-default-apps").
Set("disable-extensions").
Set("disable-hang-monitor").
Set("disable-popup-blocking").
Set("disable-prompt-on-repost").
Set("disable-sync").
Set("disable-translate").
Set("metrics-recording-only").
Set("no-first-run").
Set("safebrowsing-disable-auto-update")
// Add stealth-specific flags if enabled
if b.config.Stealth.EnableStealth {
// Most important: disable automation detection
l = l.Set("disable-blink-features", "AutomationControlled")
l = l.Set("disable-infobars")
l = l.Set("disable-dev-shm-usage")
l = l.Set("disable-ipc-flooding-protection")
l = l.Set("disable-renderer-backgrounding")
l = l.Set("disable-background-timer-throttling")
l = l.Set("no-sandbox")
l = l.Set("ignore-certificate-errors")
if b.config.Debug {
fmt.Println("[Stealth] Anti-detection launch flags applied")
}
}
// Set window size to match viewport (prevents responsive layout issues)
l = l.Set("window-size", fmt.Sprintf("%d,%d", b.config.ViewportWidth, b.config.ViewportHeight))
// Launch browser
url, err := l.Launch()
if err != nil {
return fmt.Errorf("failed to launch browser: %w", err)
}
b.launcher = l
// Connect to browser
browser := rod.New().ControlURL(url)
if err := browser.Connect(); err != nil {
return fmt.Errorf("failed to connect to browser: %w", err)
}
b.rod = browser
// Set browser window size to match viewport (ensures consistency)
if !b.config.Headless {
// Get the first target to set window bounds
windowWidth := b.config.ViewportWidth + 16 // Add chrome border
windowHeight := b.config.ViewportHeight + 88 // Add toolbar height
boundsErr := proto.BrowserSetWindowBounds{
WindowID: 1,
Bounds: &proto.BrowserBounds{
Width: &windowWidth,
Height: &windowHeight,
},
}.Call(browser)
if boundsErr != nil && b.config.Debug {
fmt.Printf("[Browser] Warning: failed to set window bounds: %v\n", boundsErr)
}
}
// Create initial page
page, err := b.rod.Page(proto.TargetCreateTarget{URL: "about:blank"})
if err != nil {
return fmt.Errorf("failed to create initial page: %w", err)
}
// Apply stealth mode to page if enabled
if b.config.Stealth.EnableStealth {
if err := applyStealthMode(page, b.config.Stealth); err != nil {
if b.config.Debug {
fmt.Printf("[Stealth] Warning: failed to apply stealth mode: %v\n", err)
}
// Continue anyway - stealth is best-effort
} else if b.config.Debug {
fmt.Println("[Stealth] Anti-detection scripts injected")
}
}
// Set viewport
if err := page.SetViewport(&proto.EmulationSetDeviceMetricsOverride{
Width: b.config.ViewportWidth,
Height: b.config.ViewportHeight,
}); err != nil {
return fmt.Errorf("failed to set viewport: %w", err)
}
// Register initial tab
tabID := generateTabID()
b.pages[tabID] = page
b.activeTabID = tabID
// Create extractor
b.extractor = dom.NewExtractor(100)
return nil
}
// Close shuts down the browser and cleans up resources.
func (b *Browser) Close() error {
b.mu.Lock()
defer b.mu.Unlock()
var errs []error
// Close all pages
for _, page := range b.pages {
if err := page.Close(); err != nil {
errs = append(errs, err)
}
}
b.pages = make(map[string]*rod.Page)
// Close browser
if b.rod != nil {
if err := b.rod.Close(); err != nil {
errs = append(errs, err)
}
b.rod = nil
}
// Clean up temporary profile
if b.tempProfilePath != "" {
if err := os.RemoveAll(b.tempProfilePath); err != nil {
errs = append(errs, err)
}
b.tempProfilePath = ""
}
if len(errs) > 0 {
return fmt.Errorf("errors during close: %v", errs)
}
return nil
}
// ActivePage returns the currently active page.
func (b *Browser) ActivePage() *rod.Page {
b.mu.RLock()
defer b.mu.RUnlock()
return b.pages[b.activeTabID]
}
// GetURL returns the current page URL.
func (b *Browser) GetURL() string {
page := b.ActivePage()
if page == nil {
return ""
}
info, err := page.Info()
if err != nil {
return ""
}
return info.URL
}
// GetTitle returns the current page title.
func (b *Browser) GetTitle() string {
page := b.ActivePage()
if page == nil {
return ""
}
info, err := page.Info()
if err != nil {
return ""
}
return info.Title
}
// ListTabs returns information about all open tabs.
func (b *Browser) ListTabs() []TabInfo {
b.mu.RLock()
defer b.mu.RUnlock()
tabs := make([]TabInfo, 0, len(b.pages))
for id, page := range b.pages {
info, err := page.Info()
if err != nil {
continue
}
tabs = append(tabs, TabInfo{
ID: id,
URL: info.URL,
Title: info.Title,
Active: id == b.activeTabID,
})
}
return tabs
}
// NewTab creates a new tab and optionally navigates to a URL.
func (b *Browser) NewTab(ctx context.Context, url string) (string, error) {
b.mu.Lock()
defer b.mu.Unlock()
if b.rod == nil {
return "", fmt.Errorf("browser not started")
}
targetURL := "about:blank"
if url != "" {
targetURL = url
}
page, err := b.rod.Page(proto.TargetCreateTarget{URL: targetURL})
if err != nil {
return "", fmt.Errorf("failed to create new tab: %w", err)
}
// Apply stealth mode to new tab if enabled
if b.config.Stealth.EnableStealth {
if err := applyStealthMode(page, b.config.Stealth); err != nil {
if b.config.Debug {
fmt.Printf("[Stealth] Warning: failed to apply stealth mode to new tab: %v\n", err)
}
}
}
// Set viewport
if err := page.SetViewport(&proto.EmulationSetDeviceMetricsOverride{
Width: b.config.ViewportWidth,
Height: b.config.ViewportHeight,
}); err != nil {
return "", fmt.Errorf("failed to set viewport: %w", err)
}
if url != "" {
_ = page.WaitStable(500 * time.Millisecond)
}
tabID := generateTabID()
b.pages[tabID] = page
b.activeTabID = tabID
return tabID, nil
}
// SwitchTab switches to a tab by ID.
func (b *Browser) SwitchTab(tabID string) error {
b.mu.Lock()
defer b.mu.Unlock()
page, ok := b.pages[tabID]
if !ok {
return fmt.Errorf("tab not found: %s", tabID)
}
// Bring tab to front
if _, err := page.Activate(); err != nil {
return fmt.Errorf("failed to activate tab: %w", err)
}
b.activeTabID = tabID
return nil
}
// CloseTab closes a tab by ID.
func (b *Browser) CloseTab(tabID string) error {
b.mu.Lock()
defer b.mu.Unlock()
page, ok := b.pages[tabID]
if !ok {
return fmt.Errorf("tab not found: %s", tabID)
}
// Can't close the last tab
if len(b.pages) <= 1 {
return fmt.Errorf("cannot close the last tab")
}
if err := page.Close(); err != nil {
return fmt.Errorf("failed to close tab: %w", err)
}
delete(b.pages, tabID)
// Switch to another tab if we closed the active one
if b.activeTabID == tabID {
for id := range b.pages {
b.activeTabID = id
break
}
}
return nil
}
// GetElementMap extracts interactive elements from the current page.
func (b *Browser) GetElementMap(ctx context.Context) (*dom.ElementMap, error) {
page := b.ActivePage()
if page == nil {
return nil, fmt.Errorf("no active page")
}
return b.extractor.Extract(ctx, page)
}
// SetMaxElements sets the maximum number of elements to extract.
func (b *Browser) SetMaxElements(max int) {
b.extractor = dom.NewExtractor(max)
}
// WaitStable waits for the page to become stable.
func (b *Browser) WaitStable(ctx context.Context) error {
page := b.ActivePage()
if page == nil {
return fmt.Errorf("no active page")
}
_ = ctx // Context available for future use
return page.WaitStable(500 * time.Millisecond)
}
// generateTabID creates a unique 4-character tab ID.
func generateTabID() string {
const chars = "abcdefghijklmnopqrstuvwxyz0123456789"
id := make([]byte, 4)
for i := range id {
id[i] = chars[time.Now().UnixNano()%int64(len(chars))]
time.Sleep(time.Nanosecond)
}
return string(id)
}