-
Notifications
You must be signed in to change notification settings - Fork 124
/
lib.rs
1950 lines (1807 loc) · 76.5 KB
/
lib.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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! A high-level API for programmatically interacting with web pages through WebDriver.
//!
//! This crate uses the [WebDriver protocol] to drive a conforming (potentially headless) browser
//! through relatively high-level operations such as "click this element", "submit this form", etc.
//!
//! Most interactions are driven by using [CSS selectors]. With most WebDriver-compatible browser
//! being fairly recent, the more expressive levels of the CSS standard are also supported, giving
//! fairly [powerful] [operators].
//!
//! Forms are managed by first calling `Client::form`, and then using the methods on `Form` to
//! manipulate the form's fields and eventually submitting it.
//!
//! For low-level access to the page, `Client::source` can be used to fetch the full page HTML
//! source code, and `Client::raw_client_for` to build a raw HTTP request for a particular URL.
//!
//! # Examples
//!
//! These examples all assume that you have a [WebDriver compatible] process running on port 4444.
//! A quick way to get one is to run [`geckodriver`] at the command line. The code also has
//! partial support for the legacy WebDriver protocol used by `chromedriver` and `ghostdriver`.
//!
//! The examples will be using `unwrap` generously --- you should probably not do that in your
//! code, and instead deal with errors when they occur. This is particularly true for methods that
//! you *expect* might fail, such as lookups by CSS selector.
//!
//! Let's start out clicking around on Wikipedia:
//!
//! ```no_run
//! # extern crate tokio_core;
//! # extern crate futures;
//! # extern crate fantoccini;
//! # fn main() {
//! use fantoccini::{Client, Locator};
//! use futures::future::Future;
//! let mut core = tokio_core::reactor::Core::new().unwrap();
//! let c = Client::new("http://localhost:4444", &core.handle());
//! let c = core.run(c).unwrap();
//!
//! {
//! // we want to have a reference to c so we can use it in the and_thens below
//! let c = &c;
//!
//! // now let's set up the sequence of steps we want the browser to take
//! // first, go to the Wikipedia page for Foobar
//! let f = c.goto("https://en.wikipedia.org/wiki/Foobar")
//! .and_then(move |_| c.current_url())
//! .and_then(move |url| {
//! assert_eq!(url.as_ref(), "https://en.wikipedia.org/wiki/Foobar");
//! // click "Foo (disambiguation)"
//! c.find(Locator::Css(".mw-disambig"))
//! })
//! .and_then(|e| e.click())
//! .and_then(move |_| {
//! // click "Foo Lake"
//! c.find(Locator::LinkText("Foo Lake"))
//! })
//! .and_then(|e| e.click())
//! .and_then(move |_| c.current_url())
//! .and_then(|url| {
//! assert_eq!(url.as_ref(), "https://en.wikipedia.org/wiki/Foo_Lake");
//! Ok(())
//! });
//!
//! // and set the browser off to do those things
//! core.run(f).unwrap();
//! }
//!
//! // drop the client to delete the browser session
//! if let Some(fin) = c.close() {
//! // and wait for cleanup to finish
//! core.run(fin).unwrap();
//! }
//! # }
//! ```
//!
//! How did we get to the Foobar page in the first place? We did a search!
//! Let's make the program do that for us instead:
//!
//! ```no_run
//! # extern crate tokio_core;
//! # extern crate futures;
//! # extern crate fantoccini;
//! # fn main() {
//! # use fantoccini::{Client, Locator};
//! # use futures::future::Future;
//! # let mut core = tokio_core::reactor::Core::new().unwrap();
//! # let c = Client::new("http://localhost:4444", &core.handle());
//! # let c = core.run(c).unwrap();
//! # {
//! # let c = &c;
//! # let f =
//! // -- snip wrapper code --
//! // go to the Wikipedia frontpage this time
//! c.goto("https://www.wikipedia.org/")
//! .and_then(move |_| {
//! // find the search form
//! c.form(Locator::Css("#search-form"))
//! })
//! .and_then(|f| {
//! // fill it out
//! f.set_by_name("search", "foobar")
//! })
//! .and_then(|f| {
//! // and submit it
//! f.submit()
//! })
//! // we should now have ended up in the rigth place
//! .and_then(move |_| c.current_url())
//! .and_then(|url| {
//! assert_eq!(url.as_ref(), "https://en.wikipedia.org/wiki/Foobar");
//! Ok(())
//! })
//! // -- snip wrapper code --
//! # ;
//! # core.run(f).unwrap();
//! # }
//! # if let Some(fin) = c.close() {
//! # core.run(fin).unwrap();
//! # }
//! # }
//! ```
//!
//! What if we want to download a raw file? Fantoccini has you covered:
//!
//! ```no_run
//! # extern crate tokio_core;
//! # extern crate futures;
//! # extern crate fantoccini;
//! # fn main() {
//! # use fantoccini::{Client, Locator};
//! # use futures::future::Future;
//! # let mut core = tokio_core::reactor::Core::new().unwrap();
//! # let c = Client::new("http://localhost:4444", &core.handle());
//! # let c = core.run(c).unwrap();
//! # {
//! # let c = &c;
//! # let f =
//! // -- snip wrapper code --
//! // go back to the frontpage
//! c.goto("https://www.wikipedia.org/")
//! .and_then(move |_| {
//! // find the source for the Wikipedia globe
//! c.find(Locator::Css("img.central-featured-logo"))
//! })
//! .and_then(|img| {
//! img.attr("src")
//! .map(|src| src.expect("image should have a src"))
//! })
//! .and_then(move |src| {
//! // now build a raw HTTP client request (which also has all current cookies)
//! c.raw_client_for(fantoccini::Method::Get, &src)
//! })
//! .and_then(|raw| {
//! use futures::Stream;
//! // we then read out the image bytes
//! raw.body().map_err(fantoccini::error::CmdError::from).fold(
//! Vec::new(),
//! |mut pixels, chunk| {
//! pixels.extend(&*chunk);
//! futures::future::ok::<Vec<u8>, fantoccini::error::CmdError>(pixels)
//! },
//! )
//! })
//! .and_then(|pixels| {
//! // and voilla, we now have the bytes for the Wikipedia logo!
//! assert!(pixels.len() > 0);
//! println!("Wikipedia logo is {}b", pixels.len());
//! Ok(())
//! })
//! // -- snip wrapper code --
//! # ;
//! # core.run(f).unwrap();
//! # }
//! # if let Some(fin) = c.close() {
//! # core.run(fin).unwrap();
//! # }
//! # }
//! ```
//!
//! [WebDriver protocol]: https://www.w3.org/TR/webdriver/
//! [CSS selectors]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors
//! [powerful]: https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes
//! [operators]: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
//! [WebDriver compatible]: https://github.com/Fyrd/caniuse/issues/2757#issuecomment-304529217
//! [`geckodriver`]: https://github.com/mozilla/geckodriver
#![deny(missing_docs)]
extern crate futures;
extern crate hyper;
extern crate hyper_tls;
extern crate rustc_serialize;
extern crate tokio_core;
extern crate url;
extern crate webdriver;
use futures::{future, Future, Stream};
use rustc_serialize::json::Json;
use std::cell::RefCell;
use std::rc::Rc;
use webdriver::command::WebDriverCommand;
use webdriver::common::ELEMENT_KEY;
use webdriver::error::ErrorStatus;
use webdriver::error::WebDriverError;
pub use hyper::Method;
/// Error types.
pub mod error;
/// An element locator.
///
/// See <https://www.w3.org/TR/webdriver/#element-retrieval>.
#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Debug, Hash)]
pub enum Locator<'a> {
/// Find an element matching the given CSS selector.
Css(&'a str),
/// Find an element using the given `id`
Id(&'a str),
/// Find a link element with the given link text.
///
/// The text matching is exact.
LinkText(&'a str),
/// Find an element using the given XPath expression.
XPath(&'a str),
}
impl<'a> Into<webdriver::command::LocatorParameters> for Locator<'a> {
fn into(self) -> webdriver::command::LocatorParameters {
match self {
Locator::Css(s) => webdriver::command::LocatorParameters {
using: webdriver::common::LocatorStrategy::CSSSelector,
value: s.to_string(),
},
Locator::Id(s) => webdriver::command::LocatorParameters {
using: webdriver::common::LocatorStrategy::XPath,
value: format!("//*[@id=\"{}\"]", s),
},
Locator::XPath(s) => webdriver::command::LocatorParameters {
using: webdriver::common::LocatorStrategy::XPath,
value: s.to_string(),
},
Locator::LinkText(s) => webdriver::command::LocatorParameters {
using: webdriver::common::LocatorStrategy::LinkText,
value: s.to_string(),
},
}
}
}
type Cmd = WebDriverCommand<webdriver::command::VoidWebDriverExtensionCommand>;
/// State held by a `Client`
struct Inner {
c: hyper::Client<hyper_tls::HttpsConnector<hyper::client::HttpConnector>, hyper::Body>,
handle: tokio_core::reactor::Handle,
wdb: url::Url,
session: RefCell<Option<String>>,
legacy: bool,
ua: RefCell<Option<String>>,
}
impl Inner {
fn shutdown(&self) -> Option<impl Future<Item = (), Error = hyper::Error>> {
if self.session.borrow().is_some() {
let url = {
let s = self.session.borrow();
self.wdb
.join(&format!("session/{}", s.as_ref().unwrap()))
.unwrap()
};
*self.session.borrow_mut() = None;
Some(
self.c
.request(hyper::client::Request::new(
Method::Delete,
url.as_ref().parse().unwrap(),
))
.map(move |_| ()),
)
} else {
None
}
}
}
impl Drop for Inner {
// NOTE: we must implement Drop for Inner, *not* for Client, since Client is dropped often
fn drop(&mut self) {
if let Some(end) = self.shutdown() {
self.handle.spawn(end.map_err(|_| ()));
}
}
}
/// A WebDriver client tied to a single browser session.
pub struct Client(Rc<Inner>);
/// A single element on the current page.
pub struct Element {
c: Client,
e: webdriver::common::WebElement,
}
/// An HTML form on the current page.
pub struct Form {
c: Client,
f: webdriver::common::WebElement,
}
impl Client {
fn init(
mut self,
params: webdriver::command::NewSessionParameters,
) -> impl Future<Item = Self, Error = error::NewSessionError> + 'static {
if let webdriver::command::NewSessionParameters::Legacy(..) = params {
Rc::get_mut(&mut self.0)
.expect("during legacy init there should be only one Client instance")
.legacy = true;
}
// Create a new session for this client
// https://www.w3.org/TR/webdriver/#dfn-new-session
self.issue_wd_cmd(WebDriverCommand::NewSession(params))
.then(move |r| match r {
Ok((this, Json::Object(mut v))) => {
// TODO: not all impls are w3c compatible
// See https://github.com/SeleniumHQ/selenium/blob/242d64ca4cd3523489ac1e58703fd7acd4f10c5a/py/selenium/webdriver/remote/webdriver.py#L189
// and https://github.com/SeleniumHQ/selenium/blob/242d64ca4cd3523489ac1e58703fd7acd4f10c5a/py/selenium/webdriver/remote/webdriver.py#L200
if let Some(session_id) = v.remove("sessionId") {
if let Some(session_id) = session_id.as_string() {
*this.0.session.borrow_mut() = Some(session_id.to_string());
return Ok(this);
}
v.insert("sessionId".to_string(), session_id);
Err(error::NewSessionError::NotW3C(Json::Object(v)))
} else {
Err(error::NewSessionError::NotW3C(Json::Object(v)))
}
}
Ok((_, v)) | Err(error::CmdError::NotW3C(v)) => {
Err(error::NewSessionError::NotW3C(v))
}
Err(error::CmdError::Failed(e)) => Err(error::NewSessionError::Failed(e)),
Err(error::CmdError::Lost(e)) => Err(error::NewSessionError::Lost(e)),
Err(error::CmdError::NotJson(v)) => {
Err(error::NewSessionError::NotW3C(Json::String(v)))
}
Err(error::CmdError::Standard(
e @ WebDriverError {
error: ErrorStatus::SessionNotCreated,
..
},
)) => Err(error::NewSessionError::SessionNotCreated(e)),
Err(e) => {
panic!("unexpected webdriver error; {}", e);
}
})
}
/// Create a new `Client` associated with a new WebDriver session on the server at the given
/// URL.
///
/// Calls `with_capabilities` with an empty capabilities list.
#[cfg_attr(feature = "cargo-clippy", allow(new_ret_no_self))]
pub fn new(
webdriver: &str,
handle: &tokio_core::reactor::Handle,
) -> impl Future<Item = Self, Error = error::NewSessionError> + 'static {
Self::with_capabilities(
webdriver,
webdriver::capabilities::Capabilities::new(),
handle,
)
}
/// Create a new `Client` associated with a new WebDriver session on the server at the given
/// URL.
///
/// The given capabilities will be requested in `alwaysMatch` or `desiredCapabilities`
/// depending on the protocol version supported by the server.
///
/// Returns a future that resolves to a handle for issuing additional WebDriver tasks.
///
/// Note that most callers should explicitly call `Client::close`, and wait for the returned
/// future before exiting. Not doing so may result in the WebDriver session not being cleanly
/// closed, which is particularly important for some drivers, such as geckodriver, where
/// multiple simulatenous sessions are not supported. If `close` is not explicitly called, a
/// session close request will be spawned on the given `handle` when the last instance of this
/// `Client` is dropped.
pub fn with_capabilities(
webdriver: &str,
mut cap: webdriver::capabilities::Capabilities,
handle: &tokio_core::reactor::Handle,
) -> impl Future<Item = Self, Error = error::NewSessionError> + 'static {
// Where is the WebDriver server?
let wdb = match webdriver.parse::<url::Url>() {
Ok(wdb) => wdb,
Err(e) => {
return future::Either::B(future::err(error::NewSessionError::BadWebdriverUrl(e)));
}
};
// We want a tls-enabled client
let client = hyper::Client::configure()
.connector(hyper_tls::HttpsConnector::new(4, handle).unwrap())
.build(handle);
// Set up our WebDriver client
let c = Client(Rc::new(Inner {
c: client.clone(),
handle: handle.clone(),
wdb: wdb.clone(),
session: RefCell::new(None),
legacy: false,
ua: RefCell::new(None),
}));
// Required capabilities
// https://www.w3.org/TR/webdriver/#capabilities
// - we want the browser to wait for the page to load
cap.insert(
"pageLoadStrategy".to_string(),
Json::String("normal".to_string()),
);
let session_config = webdriver::capabilities::SpecNewSessionParameters {
alwaysMatch: cap.clone(),
firstMatch: vec![],
};
let spec = webdriver::command::NewSessionParameters::Spec(session_config);
let f = c.dup().init(spec).or_else(move |e| {
match e {
error::NewSessionError::NotW3C(json) => {
let mut legacy = false;
match json {
Json::String(ref err) if err.starts_with("Missing Command Parameter") => {
// ghostdriver
legacy = true;
}
Json::Object(ref err) => {
legacy = err.get("message")
.and_then(|m| m.as_string())
.map(|s| {
// chromedriver < 2.29 || chromedriver == 2.29 || saucelabs
s.contains("cannot find dict 'desiredCapabilities'")
|| s.contains("Missing or invalid capabilities")
|| s.contains("Unexpected server error.")
})
.unwrap_or(false);
}
_ => {}
}
if legacy {
// we're dealing with an implementation that only supports the legacy
// WebDriver protocol:
// https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol
let session_config = webdriver::capabilities::LegacyNewSessionParameters {
desired: cap,
required: webdriver::capabilities::Capabilities::new(),
};
let spec = webdriver::command::NewSessionParameters::Legacy(session_config);
// try a new client
future::Either::A(c.init(spec))
} else {
future::Either::B(future::err(error::NewSessionError::NotW3C(json)))
}
}
e => future::Either::B(future::err(e)),
}
});
future::Either::A(f)
}
fn dup(&self) -> Self {
Client(Rc::clone(&self.0))
}
/// Set the User Agent string to use for all subsequent requests.
pub fn set_ua<S: Into<String>>(&mut self, ua: S) {
*self.0.ua.borrow_mut() = Some(ua.into());
}
/// Helper for determining what URL endpoint to use for various requests.
///
/// This mapping is essentially that of https://www.w3.org/TR/webdriver/#list-of-endpoints.
fn endpoint_for(&self, cmd: &Cmd) -> Result<url::Url, url::ParseError> {
if let WebDriverCommand::NewSession(..) = *cmd {
return self.0.wdb.join("session");
}
let base = {
let session = self.0.session.borrow();
self.0
.wdb
.join(&format!("session/{}/", session.as_ref().unwrap()))?
};
match *cmd {
WebDriverCommand::NewSession(..) => unreachable!(),
WebDriverCommand::DeleteSession => unreachable!(),
WebDriverCommand::Get(..) | WebDriverCommand::GetCurrentUrl => base.join("url"),
WebDriverCommand::GoBack => base.join("back"),
WebDriverCommand::Refresh => base.join("refresh"),
WebDriverCommand::GetPageSource => base.join("source"),
WebDriverCommand::FindElement(..) => base.join("element"),
WebDriverCommand::GetCookies => base.join("cookie"),
WebDriverCommand::ExecuteScript(..) if self.0.legacy => base.join("execute"),
WebDriverCommand::ExecuteScript(..) => base.join("execute/sync"),
WebDriverCommand::GetElementProperty(ref we, ref prop) => {
base.join(&format!("element/{}/property/{}", we.id, prop))
}
WebDriverCommand::GetElementAttribute(ref we, ref attr) => {
base.join(&format!("element/{}/attribute/{}", we.id, attr))
}
WebDriverCommand::FindElementElement(ref p, _) => {
base.join(&format!("element/{}/element", p.id))
}
WebDriverCommand::ElementClick(ref we) => {
base.join(&format!("element/{}/click", we.id))
}
WebDriverCommand::GetElementText(ref we) => {
base.join(&format!("element/{}/text", we.id))
}
WebDriverCommand::ElementSendKeys(ref we, _) => {
base.join(&format!("element/{}/value", we.id))
}
WebDriverCommand::SetWindowRect(..) => base.join("window/rect"),
WebDriverCommand::GetWindowRect => base.join("window/rect"),
_ => unimplemented!(),
}
}
/// Helper for issuing a WebDriver command, and then reading and parsing the response.
///
/// Since most `WebDriverCommand` arguments already implement `ToJson`, this is mostly a matter
/// of picking the right URL and method from [the spec], and stuffing the JSON encoded
/// arguments (if any) into the body.
///
/// [the spec]: https://www.w3.org/TR/webdriver/#list-of-endpoints
fn issue_wd_cmd(
self,
cmd: WebDriverCommand<webdriver::command::VoidWebDriverExtensionCommand>,
) -> impl Future<Item = (Self, Json), Error = error::CmdError> {
use rustc_serialize::json::ToJson;
use webdriver::command;
// most actions are just get requests with not parameters
let url = match self.endpoint_for(&cmd) {
Ok(url) => url,
Err(e) => return future::Either::B(future::err(error::CmdError::from(e))),
};
let mut method = Method::Get;
let mut body = None;
// but some are special
match cmd {
WebDriverCommand::NewSession(command::NewSessionParameters::Spec(ref conf)) => {
body = Some(format!("{}", conf.to_json()));
method = Method::Post;
}
WebDriverCommand::NewSession(command::NewSessionParameters::Legacy(ref conf)) => {
body = Some(format!("{}", conf.to_json()));
method = Method::Post;
}
WebDriverCommand::Get(ref params) => {
body = Some(format!("{}", params.to_json()));
method = Method::Post;
}
WebDriverCommand::FindElement(ref loc)
| WebDriverCommand::FindElementElement(_, ref loc) => {
body = Some(format!("{}", loc.to_json()));
method = Method::Post;
}
WebDriverCommand::ExecuteScript(ref script) => {
body = Some(format!("{}", script.to_json()));
method = Method::Post;
}
WebDriverCommand::ElementSendKeys(_, ref keys) => {
body = Some(format!("{}", keys.to_json()));
method = Method::Post;
}
WebDriverCommand::ElementClick(..)
| WebDriverCommand::GoBack
| WebDriverCommand::Refresh => {
body = Some("{}".to_string());
method = Method::Post;
}
WebDriverCommand::SetWindowRect(ref params) => {
body = Some(format!("{}", params.to_json()));
method = Method::Post;
}
_ => {}
}
// issue the command to the webdriver server
let mut req = hyper::client::Request::new(method, url.as_ref().parse().unwrap());
if let Some(ref s) = *self.0.ua.borrow() {
req.headers_mut()
.set(hyper::header::UserAgent::new(s.to_owned()));
}
// because https://github.com/hyperium/hyper/pull/727
if !url.username().is_empty() || url.password().is_some() {
req.headers_mut()
.set(hyper::header::Authorization(hyper::header::Basic {
username: url.username().to_string(),
password: url.password().map(|pwd| pwd.to_string()),
}));
}
if let Some(ref body) = body {
req.headers_mut().set(hyper::header::ContentType::json());
req.headers_mut()
.set(hyper::header::ContentLength(body.len() as u64));
req.set_body(body.clone());
}
let req = self.0.c.request(req);
let f = req.map_err(error::CmdError::from)
.and_then(move |res| {
// keep track of result status (.body() consumes self -- ugh)
let status = res.status();
// check that the server sent us json
let ctype = {
let ctype = res.headers()
.get::<hyper::header::ContentType>()
.expect("webdriver response did not have a content type");
(**ctype).clone()
};
// What did the server send us?
res.body()
.concat2()
.map(move |body| (self, body, ctype, status))
.map_err(|e| -> error::CmdError { e.into() })
})
.and_then(|(this, body, ctype, status)| {
// Too bad we can't stream into a String :(
let body =
String::from_utf8(body.to_vec()).expect("non utf-8 response from webdriver");
if ctype.type_() == hyper::mime::APPLICATION && ctype.subtype() == hyper::mime::JSON
{
Ok((this, body, status))
} else {
// nope, something else...
Err(error::CmdError::NotJson(body))
}
})
.and_then(move |(this, body, status)| {
let is_new_session = if let WebDriverCommand::NewSession(..) = cmd {
true
} else {
false
};
let mut is_success = status.is_success();
let mut legacy_status = 0;
// https://www.w3.org/TR/webdriver/#dfn-send-a-response
// NOTE: the standard specifies that even errors use the "Send a Reponse" steps
let body = match Json::from_str(&*body)? {
Json::Object(mut v) => {
if this.0.legacy {
legacy_status = v["status"].as_u64().unwrap();
is_success = legacy_status == 0;
}
if this.0.legacy && is_new_session {
// legacy implementations do not wrap sessionId inside "value"
Ok(Json::Object(v))
} else {
v.remove("value")
.ok_or_else(|| error::CmdError::NotW3C(Json::Object(v)))
}
}
v => Err(error::CmdError::NotW3C(v)),
}?;
if is_success {
return Ok((this, body));
}
// https://www.w3.org/TR/webdriver/#dfn-send-an-error
// https://www.w3.org/TR/webdriver/#handling-errors
if !body.is_object() {
return Err(error::CmdError::NotW3C(body));
}
let mut body = body.into_object().unwrap();
// phantomjs injects a *huge* field with the entire screen contents -- remove that
body.remove("screen");
let es = if this.0.legacy {
// old clients use status codes instead of "error", and we now have to map them
// https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol#response-status-codes
if !body.contains_key("message") || !body["message"].is_string() {
return Err(error::CmdError::NotW3C(Json::Object(body)));
}
match legacy_status {
6 | 33 => ErrorStatus::SessionNotCreated,
7 => ErrorStatus::NoSuchElement,
8 => ErrorStatus::NoSuchFrame,
9 => ErrorStatus::UnknownCommand,
10 => ErrorStatus::StaleElementReference,
11 => ErrorStatus::ElementNotInteractable,
12 => ErrorStatus::InvalidElementState,
13 => ErrorStatus::UnknownError,
15 => ErrorStatus::ElementNotSelectable,
17 => ErrorStatus::JavascriptError,
19 | 32 => ErrorStatus::InvalidSelector,
21 => ErrorStatus::Timeout,
23 => ErrorStatus::NoSuchWindow,
24 => ErrorStatus::InvalidCookieDomain,
25 => ErrorStatus::UnableToSetCookie,
26 => ErrorStatus::UnexpectedAlertOpen,
27 => ErrorStatus::NoSuchAlert,
28 => ErrorStatus::ScriptTimeout,
29 => ErrorStatus::InvalidCoordinates,
34 => ErrorStatus::MoveTargetOutOfBounds,
_ => return Err(error::CmdError::NotW3C(Json::Object(body))),
}
} else {
if !body.contains_key("error") || !body.contains_key("message")
|| !body["error"].is_string()
|| !body["message"].is_string()
{
return Err(error::CmdError::NotW3C(Json::Object(body)));
}
use hyper::StatusCode;
let error = body["error"].as_string().unwrap();
match status {
StatusCode::BadRequest => match error {
"element click intercepted" => ErrorStatus::ElementClickIntercepted,
"element not selectable" => ErrorStatus::ElementNotSelectable,
"element not interactable" => ErrorStatus::ElementNotInteractable,
"insecure certificate" => ErrorStatus::InsecureCertificate,
"invalid argument" => ErrorStatus::InvalidArgument,
"invalid cookie domain" => ErrorStatus::InvalidCookieDomain,
"invalid coordinates" => ErrorStatus::InvalidCoordinates,
"invalid element state" => ErrorStatus::InvalidElementState,
"invalid selector" => ErrorStatus::InvalidSelector,
"no such alert" => ErrorStatus::NoSuchAlert,
"no such frame" => ErrorStatus::NoSuchFrame,
"no such window" => ErrorStatus::NoSuchWindow,
"stale element reference" => ErrorStatus::StaleElementReference,
_ => unreachable!(),
},
StatusCode::NotFound => match error {
"unknown command" => ErrorStatus::UnknownCommand,
"no such cookie" => ErrorStatus::NoSuchCookie,
"invalid session id" => ErrorStatus::InvalidSessionId,
"no such element" => ErrorStatus::NoSuchElement,
_ => unreachable!(),
},
StatusCode::InternalServerError => match error {
"javascript error" => ErrorStatus::JavascriptError,
"move target out of bounds" => ErrorStatus::MoveTargetOutOfBounds,
"session not created" => ErrorStatus::SessionNotCreated,
"unable to set cookie" => ErrorStatus::UnableToSetCookie,
"unable to capture screen" => ErrorStatus::UnableToCaptureScreen,
"unexpected alert open" => ErrorStatus::UnexpectedAlertOpen,
"unknown error" => ErrorStatus::UnknownError,
"unsupported operation" => ErrorStatus::UnsupportedOperation,
_ => unreachable!(),
},
StatusCode::RequestTimeout => match error {
"timeout" => ErrorStatus::Timeout,
"script timeout" => ErrorStatus::ScriptTimeout,
_ => unreachable!(),
},
StatusCode::MethodNotAllowed => match error {
"unknown method" => ErrorStatus::UnknownMethod,
_ => unreachable!(),
},
_ => unreachable!(),
}
};
let message = body["message"].as_string().unwrap().to_string();
Err(error::CmdError::from(WebDriverError::new(es, message)))
});
future::Either::A(f)
}
/// Terminate the connection to the webservice.
///
/// Normally, a shutdown of the WebDriver connection will be initiated when the last clone of a
/// `Client` is dropped. Specifically, the shutdown request will be issued using the tokio
/// `Handle` given when creating this `Client`. This in turn means that any errors will be
/// dropped, and that the teardown may not even occur if the reactor does not continue being
/// turned.
///
/// This function is safe to call multiple times, but once it has been called on one instance
/// of a `Client`, all requests to other instances of that `Client` will fail. The returned
/// `Option` will only be true the first time `close` is called.
///
/// This function may be useful in conjunction with `raw_client_for`, as it allows you to close
/// the automated browser window while doing e.g., a large download.
pub fn close(self) -> Option<impl Future<Item = (), Error = hyper::Error>> {
self.0.shutdown()
}
/// Sets the x, y, width, and height properties of the current window.
///
/// All values must be `>= 0` or you will get a `CmdError::InvalidArgument`.
pub fn set_window_rect(
&self,
x: i32,
y: i32,
width: i32,
height: i32,
) -> impl Future<Item = Self, Error = error::CmdError> + 'static {
use webdriver::common::Nullable;
if x < 0 {
return future::Either::A(future::err(error::CmdError::InvalidArgument(
stringify!(x).into(),
format!("Expected to be `>= 0` but was `{}`", x),
)));
}
if y < 0 {
return future::Either::A(future::err(error::CmdError::InvalidArgument(
stringify!(y).into(),
format!("Expected to be `>= 0` but was `{}`", y),
)));
}
if width < 0 {
return future::Either::A(future::err(error::CmdError::InvalidArgument(
stringify!(width).into(),
format!("Expected to be `>= 0` but was `{}`", width),
)));
}
if height < 0 {
return future::Either::A(future::err(error::CmdError::InvalidArgument(
stringify!(height).into(),
format!("Expected to be `>= 0` but was `{}`", height),
)));
}
let cmd = WebDriverCommand::SetWindowRect(webdriver::command::WindowRectParameters {
x: Nullable::Value(x),
y: Nullable::Value(y),
width: Nullable::Value(width),
height: Nullable::Value(height),
});
future::Either::B(self.dup().issue_wd_cmd(cmd).map(|(this, _)| this))
}
/// Gets the x, y, width, and height properties of the current window.
pub fn get_window_rect(
&self,
) -> impl Future<Item = (u64, u64, u64, u64), Error = error::CmdError> + 'static {
self.dup()
.issue_wd_cmd(WebDriverCommand::GetWindowRect)
.and_then(|(_, v)| match v {
Json::Object(mut obj) => {
let x = match obj.remove("x").and_then(|x| x.as_u64()) {
Some(x) => x,
None => return Err(error::CmdError::NotW3C(Json::Object(obj))),
};
let y = match obj.remove("y").and_then(|y| y.as_u64()) {
Some(y) => y,
None => return Err(error::CmdError::NotW3C(Json::Object(obj))),
};
let width = match obj.remove("width").and_then(|width| width.as_u64()) {
Some(width) => width,
None => return Err(error::CmdError::NotW3C(Json::Object(obj))),
};
let height = match obj.remove("height").and_then(|height| height.as_u64()) {
Some(height) => height,
None => return Err(error::CmdError::NotW3C(Json::Object(obj))),
};
Ok((x, y, width, height))
}
_ => Err(error::CmdError::NotW3C(v)),
})
}
/// Sets the x, y, width, and height properties of the current window.
///
/// All values must be `>= 0` or you will get a `CmdError::InvalidArgument`.
pub fn set_window_size(
&self,
width: i32,
height: i32,
) -> impl Future<Item = Self, Error = error::CmdError> + 'static {
use webdriver::common::Nullable;
if width < 0 {
return future::Either::A(future::err(error::CmdError::InvalidArgument(
stringify!(width).into(),
format!("Expected to be `>= 0` but was `{}`", width),
)));
}
if height < 0 {
return future::Either::A(future::err(error::CmdError::InvalidArgument(
stringify!(height).into(),
format!("Expected to be `>= 0` but was `{}`", height),
)));
}
let cmd = WebDriverCommand::SetWindowRect(webdriver::command::WindowRectParameters {
x: Nullable::Null,
y: Nullable::Null,
width: Nullable::Value(width),
height: Nullable::Value(height),
});
future::Either::B(self.dup().issue_wd_cmd(cmd).map(|(this, _)| this))
}
/// Gets the width and height of the current window.
pub fn get_window_size(
&self,
) -> impl Future<Item = (u64, u64), Error = error::CmdError> + 'static {
self.dup()
.issue_wd_cmd(WebDriverCommand::GetWindowRect)
.and_then(|(_, v)| match v {
Json::Object(mut obj) => {
let width = match obj.remove("width").and_then(|width| width.as_u64()) {
Some(width) => width,
None => return Err(error::CmdError::NotW3C(Json::Object(obj))),
};
let height = match obj.remove("height").and_then(|height| height.as_u64()) {
Some(height) => height,
None => return Err(error::CmdError::NotW3C(Json::Object(obj))),
};
Ok((width, height))
}
_ => Err(error::CmdError::NotW3C(v)),
})
}
/// Sets the x, y, width, and height properties of the current window.
///
/// All values must be `>= 0` or you will get a `CmdError::InvalidArgument`.
pub fn set_window_position(
&self,
x: i32,
y: i32,
) -> impl Future<Item = Self, Error = error::CmdError> + 'static {
use webdriver::common::Nullable;
if x < 0 {
return future::Either::A(future::err(error::CmdError::InvalidArgument(
stringify!(x).into(),
format!("Expected to be `>= 0` but was `{}`", x),
)));
}
if y < 0 {
return future::Either::A(future::err(error::CmdError::InvalidArgument(
stringify!(y).into(),
format!("Expected to be `>= 0` but was `{}`", y),
)));
}
let cmd = WebDriverCommand::SetWindowRect(webdriver::command::WindowRectParameters {
x: Nullable::Value(x),
y: Nullable::Value(y),
width: Nullable::Null,
height: Nullable::Null,
});
future::Either::B(self.dup().issue_wd_cmd(cmd).map(|(this, _)| this))
}
/// Gets the x and y top-left coordinate of the current window.
pub fn get_window_position(
&self,
) -> impl Future<Item = (u64, u64), Error = error::CmdError> + 'static {
self.dup()
.issue_wd_cmd(WebDriverCommand::GetWindowRect)
.and_then(|(_, v)| match v {
Json::Object(mut obj) => {
let x = match obj.remove("x").and_then(|x| x.as_u64()) {
Some(x) => x,
None => return Err(error::CmdError::NotW3C(Json::Object(obj))),
};
let y = match obj.remove("y").and_then(|y| y.as_u64()) {