forked from mattsse/chromiumoxide
-
Notifications
You must be signed in to change notification settings - Fork 0
/
target.rs
705 lines (650 loc) · 25.5 KB
/
target.rs
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
use std::collections::VecDeque;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Instant;
use futures::channel::oneshot::Sender;
use futures::stream::Stream;
use futures::task::{Context, Poll};
use chromiumoxide_cdp::cdp::browser_protocol::page::{FrameId, GetFrameTreeParams};
use chromiumoxide_cdp::cdp::browser_protocol::{
browser::BrowserContextId,
log as cdplog, performance,
target::{AttachToTargetParams, SessionId, SetAutoAttachParams, TargetId, TargetInfo},
};
use chromiumoxide_cdp::cdp::events::CdpEvent;
use chromiumoxide_cdp::cdp::CdpEventMessage;
use chromiumoxide_types::{Command, Method, Request, Response};
use crate::cdp::browser_protocol::target::CloseTargetParams;
use crate::cmd::CommandChain;
use crate::cmd::CommandMessage;
use crate::error::{CdpError, Result};
use crate::handler::browser::BrowserContext;
use crate::handler::domworld::DOMWorldKind;
use crate::handler::emulation::EmulationManager;
use crate::handler::frame::{
FrameEvent, FrameManager, NavigationError, NavigationId, NavigationOk,
};
use crate::handler::frame::{FrameNavigationRequest, UTILITY_WORLD_NAME};
use crate::handler::http::HttpRequest;
use crate::handler::network::{NetworkEvent, NetworkManager};
use crate::handler::page::PageHandle;
use crate::handler::viewport::Viewport;
use crate::handler::{PageInner, REQUEST_TIMEOUT};
use crate::listeners::{EventListenerRequest, EventListeners};
use crate::page::Page;
use chromiumoxide_cdp::cdp::js_protocol::runtime::ExecutionContextId;
use std::time::Duration;
macro_rules! advance_state {
($s:ident, $cx:ident, $now:ident, $cmds: ident, $next_state:expr ) => {{
if let Poll::Ready(poll) = $cmds.poll($now) {
return match poll {
None => {
$s.init_state = $next_state;
$s.poll($cx, $now)
}
Some(Ok((method, params))) => Some(TargetEvent::Request(Request {
method,
session_id: $s.session_id.clone().map(Into::into),
params,
})),
Some(Err(_)) => Some($s.on_initialization_failed()),
};
} else {
return None;
}
}};
}
#[derive(Debug)]
pub struct Target {
/// Info about this target as returned from the chromium instance
info: TargetInfo,
/// The type of this target
r#type: TargetType,
/// Configs for this target
config: TargetConfig,
/// The context this target is running in
browser_context: BrowserContext,
/// The frame manager that maintains the state of all frames and handles
/// navigations of frames
frame_manager: FrameManager,
/// Handles all the https
network_manager: NetworkManager,
emulation_manager: EmulationManager,
/// The identifier of the session this target is attached to
session_id: Option<SessionId>,
/// The handle of the browser page of this target
page: Option<PageHandle>,
/// Drives this target towards initialization
init_state: TargetInit,
/// Currently queued events to report to the `Handler`
queued_events: VecDeque<TargetEvent>,
/// All registered event subscriptions
event_listeners: EventListeners,
/// Senders that need to be notified once the main frame has loaded
wait_for_frame_navigation: Vec<Sender<Option<Arc<HttpRequest>>>>,
/// The sender who requested the page.
initiator: Option<Sender<Result<Page>>>,
}
impl Target {
/// Create a new target instance with `TargetInfo` after a
/// `CreateTargetParams` request.
pub fn new(info: TargetInfo, config: TargetConfig, browser_context: BrowserContext) -> Self {
let ty = TargetType::new(&info.r#type);
let request_timeout = config.request_timeout;
let network_manager = NetworkManager::new(config.ignore_https_errors, request_timeout);
Self {
info,
r#type: ty,
config,
frame_manager: FrameManager::new(request_timeout),
network_manager,
emulation_manager: EmulationManager::new(request_timeout),
session_id: None,
page: None,
init_state: TargetInit::AttachToTarget,
wait_for_frame_navigation: Default::default(),
queued_events: Default::default(),
event_listeners: Default::default(),
initiator: None,
browser_context,
}
}
pub fn set_session_id(&mut self, id: SessionId) {
self.session_id = Some(id)
}
pub fn session_id(&self) -> Option<&SessionId> {
self.session_id.as_ref()
}
pub fn browser_context(&self) -> &BrowserContext {
&self.browser_context
}
pub fn session_id_mut(&mut self) -> &mut Option<SessionId> {
&mut self.session_id
}
/// The identifier for this target
pub fn target_id(&self) -> &TargetId {
&self.info.target_id
}
/// The type of this target
pub fn r#type(&self) -> &TargetType {
&self.r#type
}
/// Whether this target is already initialized
pub fn is_initialized(&self) -> bool {
matches!(self.init_state, TargetInit::Initialized)
}
/// Navigate a frame
pub fn goto(&mut self, req: FrameNavigationRequest) {
self.frame_manager.goto(req)
}
fn create_page(&mut self) {
if self.page.is_none() {
if let Some(session) = self.session_id.clone() {
let handle = PageHandle::new(self.target_id().clone(), session);
self.page = Some(handle);
}
}
}
/// Tries to create the `PageInner` if this target is already initialized
pub(crate) fn get_or_create_page(&mut self) -> Option<&Arc<PageInner>> {
self.create_page();
self.page.as_ref().map(|p| p.inner())
}
pub fn is_page(&self) -> bool {
self.r#type().is_page()
}
pub fn browser_context_id(&self) -> Option<&BrowserContextId> {
self.info.browser_context_id.as_ref()
}
pub fn info(&self) -> &TargetInfo {
&self.info
}
/// Get the target that opened this target. Top-level targets return `None`.
pub fn opener(&self) -> Option<&TargetId> {
self.info.opener_id.as_ref()
}
pub fn frame_manager_mut(&mut self) -> &mut FrameManager {
&mut self.frame_manager
}
pub fn event_listeners_mut(&mut self) -> &mut EventListeners {
&mut self.event_listeners
}
/// Received a response to a command issued by this target
pub fn on_response(&mut self, resp: Response, method: &str) {
if let Some(cmds) = self.init_state.commands_mut() {
cmds.received_response(method);
}
#[allow(clippy::single_match)] // allow for now
match method {
GetFrameTreeParams::IDENTIFIER => {
if let Some(resp) = resp
.result
.and_then(|val| GetFrameTreeParams::response_from_value(val).ok())
{
self.frame_manager.on_frame_tree(resp.frame_tree);
}
}
// requests originated from the network manager all return an empty response, hence they
// can be ignored here
_ => {}
}
}
pub fn on_event(&mut self, event: CdpEventMessage) {
let CdpEventMessage { params, method, .. } = event;
match ¶ms {
// `FrameManager` events
CdpEvent::PageFrameAttached(ev) => self
.frame_manager
.on_frame_attached(ev.frame_id.clone(), Some(ev.parent_frame_id.clone())),
CdpEvent::PageFrameDetached(ev) => self.frame_manager.on_frame_detached(ev),
CdpEvent::PageFrameNavigated(ev) => self.frame_manager.on_frame_navigated(&ev.frame),
CdpEvent::PageNavigatedWithinDocument(ev) => {
self.frame_manager.on_frame_navigated_within_document(ev)
}
CdpEvent::RuntimeExecutionContextCreated(ev) => {
self.frame_manager.on_frame_execution_context_created(ev)
}
CdpEvent::RuntimeExecutionContextDestroyed(ev) => {
self.frame_manager.on_frame_execution_context_destroyed(ev)
}
CdpEvent::RuntimeExecutionContextsCleared(_) => {
self.frame_manager.on_execution_contexts_cleared()
}
CdpEvent::RuntimeBindingCalled(ev) => {
// TODO check if binding registered and payload is json
self.frame_manager.on_runtime_binding_called(ev)
}
CdpEvent::PageLifecycleEvent(ev) => self.frame_manager.on_page_lifecycle_event(ev),
CdpEvent::PageFrameStartedLoading(ev) => {
self.frame_manager.on_frame_started_loading(ev);
}
// `NetworkManager` events
CdpEvent::FetchRequestPaused(ev) => self.network_manager.on_fetch_request_paused(&*ev),
CdpEvent::FetchAuthRequired(ev) => self.network_manager.on_fetch_auth_required(&*ev),
CdpEvent::NetworkRequestWillBeSent(ev) => {
self.network_manager.on_request_will_be_sent(&*ev)
}
CdpEvent::NetworkRequestServedFromCache(ev) => {
self.network_manager.on_request_served_from_cache(ev)
}
CdpEvent::NetworkResponseReceived(ev) => {
self.network_manager.on_response_received(&*ev)
}
CdpEvent::NetworkLoadingFinished(ev) => {
self.network_manager.on_network_loading_finished(ev)
}
CdpEvent::NetworkLoadingFailed(ev) => {
self.network_manager.on_network_loading_failed(ev)
}
_ => {}
}
chromiumoxide_cdp::consume_event!(match params {
|ev| self.event_listeners.start_send(ev),
|json| { let _ = self.event_listeners.try_send_custom(&method, json);}
});
}
/// Called when a init command timed out
fn on_initialization_failed(&mut self) -> TargetEvent {
if let Some(initiator) = self.initiator.take() {
let _ = initiator.send(Err(CdpError::Timeout));
}
self.init_state = TargetInit::Closing;
let close_target = CloseTargetParams::new(self.info.target_id.clone());
TargetEvent::Request(Request {
method: close_target.identifier(),
session_id: self.session_id.clone().map(Into::into),
params: serde_json::to_value(close_target).unwrap(),
})
}
/// Advance that target's state
pub(crate) fn poll(&mut self, cx: &mut Context<'_>, now: Instant) -> Option<TargetEvent> {
if !self.is_page() {
// can only poll pages
return None;
}
match &mut self.init_state {
TargetInit::AttachToTarget => {
self.init_state = TargetInit::InitializingFrame(FrameManager::init_commands(
self.config.request_timeout,
));
let params = AttachToTargetParams::builder()
.target_id(self.target_id().clone())
.flatten(true)
.build()
.unwrap();
return Some(TargetEvent::Request(Request::new(
params.identifier(),
serde_json::to_value(params).unwrap(),
)));
}
TargetInit::InitializingFrame(cmds) => {
self.session_id.as_ref()?;
if let Poll::Ready(poll) = cmds.poll(now) {
return match poll {
None => {
if let Some(isolated_world_cmds) =
self.frame_manager.ensure_isolated_world(UTILITY_WORLD_NAME)
{
*cmds = isolated_world_cmds;
} else {
self.init_state = TargetInit::InitializingNetwork(
self.network_manager.init_commands(),
);
}
self.poll(cx, now)
}
Some(Ok((method, params))) => Some(TargetEvent::Request(Request {
method,
session_id: self.session_id.clone().map(Into::into),
params,
})),
Some(Err(_)) => Some(self.on_initialization_failed()),
};
} else {
return None;
}
}
TargetInit::InitializingNetwork(cmds) => {
advance_state!(
self,
cx,
now,
cmds,
TargetInit::InitializingPage(Self::page_init_commands(
self.config.request_timeout
))
);
}
TargetInit::InitializingPage(cmds) => {
advance_state!(
self,
cx,
now,
cmds,
match self.config.viewport.as_ref() {
Some(viewport) => TargetInit::InitializingEmulation(
self.emulation_manager.init_commands(viewport)
),
None => TargetInit::Initialized,
}
);
}
TargetInit::InitializingEmulation(cmds) => {
advance_state!(self, cx, now, cmds, TargetInit::Initialized);
}
TargetInit::Initialized => {
if let Some(initiator) = self.initiator.take() {
// make sure that the main frame of the page has finished loading
if self
.frame_manager
.main_frame()
.map(|frame| frame.is_loaded())
.unwrap_or_default()
{
if let Some(page) = self.get_or_create_page() {
let _ = initiator.send(Ok(page.clone().into()));
} else {
self.initiator = Some(initiator);
}
} else {
self.initiator = Some(initiator);
}
}
}
TargetInit::Closing => return None,
};
loop {
if let Some(frame) = self.frame_manager.main_frame() {
if frame.is_loaded() {
while let Some(tx) = self.wait_for_frame_navigation.pop() {
let _ = tx.send(frame.http_request().cloned());
}
}
}
// Drain queued messages first.
if let Some(ev) = self.queued_events.pop_front() {
return Some(ev);
}
if let Some(handle) = self.page.as_mut() {
while let Poll::Ready(Some(msg)) = Pin::new(&mut handle.rx).poll_next(cx) {
match msg {
TargetMessage::Command(cmd) => {
self.queued_events.push_back(TargetEvent::Command(cmd));
}
TargetMessage::MainFrame(tx) => {
let _ =
tx.send(self.frame_manager.main_frame().map(|f| f.id().clone()));
}
TargetMessage::AllFrames(tx) => {
let _ = tx.send(
self.frame_manager
.frames()
.map(|f| f.id().clone())
.collect(),
);
}
TargetMessage::Url(tx) => {
let _ = tx.send(
self.frame_manager
.main_frame()
.and_then(|f| f.url().map(str::to_string)),
);
}
TargetMessage::WaitForNavigation(tx) => {
if let Some(frame) = self.frame_manager.main_frame() {
// TODO submit a navigation watcher: waitForFrameNavigation
// TODO return the watchers navigationResponse
if frame.is_loaded() {
let _ = tx.send(frame.http_request().cloned());
} else {
self.wait_for_frame_navigation.push(tx);
}
} else {
self.wait_for_frame_navigation.push(tx);
}
}
TargetMessage::AddEventListener(req) => {
// register a new listener
self.event_listeners.add_listener(req);
}
TargetMessage::GetExecutionContext(ctx) => {
let GetExecutionContext {
dom_world,
frame_id,
tx,
} = ctx;
let frame = if let Some(frame_id) = frame_id {
self.frame_manager.frame(&frame_id)
} else {
self.frame_manager.main_frame()
};
if let Some(frame) = frame {
match dom_world {
DOMWorldKind::Main => {
let _ = tx.send(frame.main_world().execution_context());
}
DOMWorldKind::Secondary => {
let _ =
tx.send(frame.secondary_world().execution_context());
}
}
} else {
let _ = tx.send(None);
}
}
}
}
}
while let Some(event) = self.network_manager.poll() {
match event {
NetworkEvent::SendCdpRequest((method, params)) => {
// send a message to the browser
self.queued_events.push_back(TargetEvent::Request(Request {
method,
session_id: self.session_id.clone().map(Into::into),
params,
}))
}
NetworkEvent::Request(_) => {}
NetworkEvent::Response(_) => {}
NetworkEvent::RequestFailed(request) => {
self.frame_manager.on_http_request_finished(request);
}
NetworkEvent::RequestFinished(request) => {
self.frame_manager.on_http_request_finished(request);
}
}
}
while let Some(event) = self.frame_manager.poll(now) {
match event {
FrameEvent::NavigationResult(res) => {
self.queued_events
.push_back(TargetEvent::NavigationResult(res));
}
FrameEvent::NavigationRequest(id, req) => {
self.queued_events
.push_back(TargetEvent::NavigationRequest(id, req));
}
}
}
if self.queued_events.is_empty() {
return None;
}
}
}
/// Set the sender half of the channel who requested the creation of this
/// target
pub fn set_initiator(&mut self, tx: Sender<Result<Page>>) {
self.initiator = Some(tx);
}
pub(crate) fn page_init_commands(timeout: Duration) -> CommandChain {
let attach = SetAutoAttachParams::builder()
.flatten(true)
.auto_attach(true)
.wait_for_debugger_on_start(true)
.build()
.unwrap();
let enable_performance = performance::EnableParams::default();
let enable_log = cdplog::EnableParams::default();
CommandChain::new(
vec![
(attach.identifier(), serde_json::to_value(attach).unwrap()),
(
enable_performance.identifier(),
serde_json::to_value(enable_performance).unwrap(),
),
(
enable_log.identifier(),
serde_json::to_value(enable_log).unwrap(),
),
],
timeout,
)
}
}
#[derive(Debug, Clone)]
pub struct TargetConfig {
pub ignore_https_errors: bool,
/// Request timeout to use
pub request_timeout: Duration,
pub viewport: Option<Viewport>,
}
impl TargetConfig {
pub fn new(
ignore_https_errors: bool,
request_timeout: Duration,
viewport: Option<Viewport>,
) -> Self {
Self {
ignore_https_errors,
request_timeout,
viewport,
}
}
}
impl Default for TargetConfig {
fn default() -> Self {
Self {
ignore_https_errors: true,
request_timeout: Duration::from_secs(REQUEST_TIMEOUT),
viewport: Default::default(),
}
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum TargetType {
Page,
BackgroundPage,
ServiceWorker,
SharedWorker,
Other,
Browser,
Webview,
Unknown(String),
}
impl TargetType {
pub fn new(ty: &str) -> Self {
match ty {
"page" => TargetType::Page,
"background_page" => TargetType::BackgroundPage,
"service_worker" => TargetType::ServiceWorker,
"shared_worker" => TargetType::SharedWorker,
"other" => TargetType::Other,
"browser" => TargetType::Browser,
"webview" => TargetType::Webview,
s => TargetType::Unknown(s.to_string()),
}
}
pub fn is_page(&self) -> bool {
matches!(self, TargetType::Page)
}
pub fn is_background_page(&self) -> bool {
matches!(self, TargetType::BackgroundPage)
}
pub fn is_service_worker(&self) -> bool {
matches!(self, TargetType::ServiceWorker)
}
pub fn is_shared_worker(&self) -> bool {
matches!(self, TargetType::SharedWorker)
}
pub fn is_other(&self) -> bool {
matches!(self, TargetType::Other)
}
pub fn is_browser(&self) -> bool {
matches!(self, TargetType::Browser)
}
pub fn is_webview(&self) -> bool {
matches!(self, TargetType::Webview)
}
}
#[derive(Debug)]
pub(crate) enum TargetEvent {
/// An internal request
Request(Request),
/// An internal navigation request
NavigationRequest(NavigationId, Request),
/// Indicates that a previous requested navigation has finished
NavigationResult(Result<NavigationOk, NavigationError>),
/// A new command arrived via a channel
Command(CommandMessage),
}
// TODO this can be moved into the classes?
#[derive(Debug)]
pub enum TargetInit {
InitializingFrame(CommandChain),
InitializingNetwork(CommandChain),
InitializingPage(CommandChain),
InitializingEmulation(CommandChain),
AttachToTarget,
Initialized,
Closing,
}
impl TargetInit {
fn commands_mut(&mut self) -> Option<&mut CommandChain> {
match self {
TargetInit::InitializingFrame(cmd) => Some(cmd),
TargetInit::InitializingNetwork(cmd) => Some(cmd),
TargetInit::InitializingPage(cmd) => Some(cmd),
TargetInit::InitializingEmulation(cmd) => Some(cmd),
TargetInit::AttachToTarget => None,
TargetInit::Initialized => None,
TargetInit::Closing => None,
}
}
}
#[derive(Debug)]
pub struct GetExecutionContext {
/// For which world the execution context was requested
pub dom_world: DOMWorldKind,
/// The if of the frame to get the `ExecutionContext` for
pub frame_id: Option<FrameId>,
/// Sender half of the channel to send the response back
pub tx: Sender<Option<ExecutionContextId>>,
}
impl GetExecutionContext {
pub fn new(tx: Sender<Option<ExecutionContextId>>) -> Self {
Self {
dom_world: DOMWorldKind::Main,
frame_id: None,
tx,
}
}
}
#[derive(Debug)]
pub(crate) enum TargetMessage {
/// Execute a command within the session of this target
Command(CommandMessage),
/// Return the main frame of this target's page
MainFrame(Sender<Option<FrameId>>),
/// Return all the frames of this target's page
AllFrames(Sender<Vec<FrameId>>),
/// Return the url of this target's page
Url(Sender<Option<String>>),
/// A Message that resolves when the frame finished loading a new url
WaitForNavigation(Sender<Option<Arc<HttpRequest>>>),
/// A request to submit a new listener that gets notified with every
/// received event
AddEventListener(EventListenerRequest),
/// Get the `ExecutionContext` if available
GetExecutionContext(GetExecutionContext),
}