-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbrowser.v
406 lines (372 loc) · 8.7 KB
/
browser.v
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
module cdv
import net.websocket
import net.http
import x.json2 as json
import time
import os
import log
const base_cache = os.cache_dir() + '/cdv'
pub enum BrowserType {
chrome
firefox
edge
}
pub type Strings = string | []string
@[heap]
pub struct Browser {
pub:
typ BrowserType
args []string
port int
ch chan string
ws_url string
timeout i64
pub mut:
browser_context_id ?string
target_id string
next_id int = 1
ws &websocket.Client = unsafe { nil }
base_url string
pages []Page
mut:
process &os.Process = unsafe { nil }
has_init bool = true
emits []EmitData
use_pages bool
}
@[params]
pub struct Config {
pub:
base_url string
ws_url string
args []string
executable_path ?string
port int = 9222
user_data_dir ?string
headless bool = true
host string = 'localhost'
secure bool
typ BrowserType = .chrome
incognito bool
use_pages bool
maximized bool
timeout i64 = ws_timeout
write_timeout i64 = ws_timeout
}
struct OnOpen {
ch chan int
}
const error_logger = setup_error_logger()
fn setup_error_logger() &log.Log {
mut l := &log.Log{}
l.set_level(.error)
return l
}
fn create_connection(opts Config) !&Browser {
base_url := get_base_url(opts)
url := base_url + '/json'
mut v_res := http.Response{}
mut ws_url := opts.ws_url
if ws_url == '' {
tt := 1 * time.second
for {
time.sleep(tt)
v_res = get_version_hell(url + '/version')
if v_res.status_code == 200 {
break
}
}
ws_url = json.decode[json.Any](v_res.body)!.as_map()['webSocketDebuggerUrl']!.str()
if ws_url == '' {
return error('cannot find socket url.')
}
}
ch := chan string{}
mut ws := websocket.new_client(ws_url,
logger: error_logger
read_timeout: opts.timeout
write_timeout: opts.write_timeout
)!
mut bwr := &Browser{
ws_url: ws_url
ch: ch
ws: ws
args: opts.args
port: opts.port
base_url: base_url
use_pages: opts.use_pages
timeout: opts.timeout
}
on_open := &OnOpen{
ch: chan int{cap: 1}
}
ws.on_open_ref(fn (mut ws websocket.Client, data &OnOpen) ! {
data.ch <- 1
}, on_open)
ws.on_message_ref(fn (mut ws websocket.Client, msg &websocket.Message, mut bwr Browser) ! {
if msg.payload.len > 0 {
bwr.ch <- msg.payload.bytestr()
}
}, bwr)
ws.on_error_ref(fn (mut ws websocket.Client, err string, mut bwr Browser) ! {
eprintln('ws.on_error error: ${err}')
bwr.close(force: true)
}, bwr)
ws.connect()!
spawn ws.listen()
wait_for_idle(on_open.ch)!
result := bwr.send('Target.getTargets')!.result
targets := result['targetInfos']!.arr()
mut target_id := ''
for target in targets {
target_map := target.as_map()
if target_map['type'] or { '' }.str() == 'page' {
target_id = target_map['targetId'] or { '' }.str()
break
}
}
if target_id == '' {
return error('no target_id detected!')
}
bwr.target_id = target_id
return bwr
}
fn wait_for_idle(ch chan int) ! {
for {
select {
_ := <-ch {
if !ch.closed {
ch.close()
}
break
}
10 * time.second {
return error('cannot open browser')
}
}
}
}
pub fn connect(opts Config) !&Browser {
return create_connection(opts)!
}
fn get_typ_browser(typ BrowserType) !string {
return match typ {
.chrome { find_chrome()! }
.edge { find_edge()! }
.firefox { find_firefox()! }
}
}
pub fn open_browser(opts Config) !&Browser {
executable_path := opts.executable_path or { get_typ_browser(opts.typ)! }
mut args := []string{}
if executable_path == '' {
return error('cannot find executable_path')
}
user_dir := opts.user_data_dir or {
mut dir := base_cache + '/' + opts.typ.str()
if opts.headless {
dir += '/headless'
} else {
dir += '/browser'
}
if !os.exists(dir) {
os.mkdir_all(dir)!
}
dir
}
args << def_args
args << opts.args
args << '--remote-debugging-port=${opts.port}'
args << '--user-data-dir=${user_dir}'
if opts.headless {
args << '--headless'
args << '--disable-gpu'
}
if opts.incognito {
args << '--incognito'
}
if opts.maximized {
args << '--start-maximized'
}
mut cmd := os.new_process(executable_path)
cmd.set_args(args)
cmd.set_redirect_stdio()
cmd.run()
mut has_ready := false
mut bwr := &Browser{}
cfg := Config{
...opts
args: args
user_data_dir: user_dir
executable_path: executable_path
}
for cmd.is_alive() {
if !has_ready {
bwr = create_connection(cfg) or {
cmd.signal_kill()
panic(err)
}
has_ready = true
break
}
}
bwr.process = cmd
return bwr
}
pub fn open_chrome(opts Config) !&Browser {
return open_browser(Config{ ...opts, typ: .chrome })
}
pub fn open_edge(opts Config) !&Browser {
return open_browser(Config{ ...opts, typ: .edge })
}
pub fn open_firefox(opts Config) !&Browser {
return open_browser(Config{ ...opts, typ: .firefox })
}
pub fn open_safari(opts Config) !&Browser {
return error('not supported')
}
pub fn open_opera(opts Config) !&Browser {
return error('not supported')
}
@[noreturn]
fn (mut bwr Browser) noop(err IError) {
bwr.close(force: true)
panic(err)
}
fn (mut bwr Browser) get_next_id(current_id int) int {
mut id := current_id
if id == -1 {
id = bwr.next_id++
}
return id
}
pub fn (mut bwr Browser) send(method string, opts MessageParams) !Result {
id := bwr.get_next_id(opts.id)
msg := MessageParams{
...opts
method: method
id: id
}
mut data := '{"id":${id},"method":"${method}"'
if params_map := msg.params {
params := params_map.str()
data += ',"params":${params}'
}
if session_id := msg.session_id {
data += ',"sessionId":"${session_id}"'
}
data += '}'
bwr.ws.write_string(data)!
return bwr.recv_method(msg)!
}
fn (mut bwr Browser) send_or_noop(method string, params MessageParams) Result {
return bwr.send(method, params) or { bwr.noop(err) }
}
fn (mut bwr Browser) send_event_or_noop(method string, params MessageParams) Result {
return bwr.send_event(method, params) or { bwr.noop(err) }
}
pub fn (mut bwr Browser) send_event(method string, params MessageParams) !Result {
return bwr.send(method, MessageParams{ ...params, typ: .event })!
}
fn (mut bwr Browser) recv_method(params MessageParams) !Result {
mut data, id, method := map[string]json.Any{}, params.id, params.method
session_id, typ := params.session_id or { '' }, params.typ
mut t_error := map[string]json.Any{}
mut is_error := false
mut is_done := false
mut release := params.timeout or { bwr.timeout }
mut timeout := release
for {
select {
raw := <-bwr.ch {
data = json.decode[json.Any](raw)!.as_map()
if session_id == data['sessionId'] or { '' }.str() {
if d_error := data['error'] {
t_error = d_error.as_map()
is_error = true
}
d_method := data['method'] or { json.Any('') }.str()
if d_method != '' {
if d_params := data['params'] {
mut d_msg := Message{
method: d_method
params: d_params.as_map()
session_id: session_id
}
if !isnil(params.cb) {
is_done = params.cb(mut d_msg, params.ref)!
}
is_done = bwr.emit(d_method, mut d_msg)
}
}
if typ == .command {
if data['id'] or { json.Any(-2) }.int() == id {
is_done = true
}
} else if typ == .event {
if d_method == method {
is_done = true
}
}
if is_done {
timeout = release
break
}
}
}
timeout {
break
}
}
}
return Result{
method: method
id: id
session_id: session_id
result: data['result'] or { json.Any{} }.as_map()
error: t_error
is_error: is_error
}
}
@[params]
pub struct BrowserCloseParams {
pub:
force bool
}
pub fn (mut bwr Browser) close(opts BrowserCloseParams) {
if ctx_id := bwr.browser_context_id {
bwr.send_or_noop('Target.disposeBrowserContext',
params: {
'browserContextId': ctx_id
}
)
if !opts.force {
return
}
}
bwr.process.signal_kill()
if !isnil(bwr.ws) {
bwr.ws.close(1000, 'normal') or { eprintln('browser is closed') }
}
if !bwr.ch.closed {
bwr.ch.close()
}
}
fn (mut bwr Browser) add_page(mut page Page) {
bwr.pages << page
}
fn (mut bwr Browser) struct_to_json_any[T](d T) json.Any {
return struct_to_json_any[T](d) or { bwr.noop(err) }
}
pub struct BrowserVersion {
pub:
protocol_version string @[json: 'protocolVersion']
product string @[json: 'product']
revision string @[json: 'revision']
user_agent string @[json: 'userAgent']
v8_version string @[json: 'jsVersion']
}
pub fn (mut bwr Browser) get_version() BrowserVersion {
res := bwr.send_or_noop('Browser.getVersion').result
return json.decode[BrowserVersion](res.str()) or { bwr.noop(err) }
}