From 99968c72a5efbd535362e050baf314f9e0cff709 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Fri, 30 Jul 2021 19:24:41 +0200 Subject: refactor: browser as modular funcs --- src/browser/mod.rs | 19 +++++++++++++ src/browser/web_browser.rs | 68 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+) create mode 100644 src/browser/mod.rs create mode 100644 src/browser/web_browser.rs (limited to 'src/browser') diff --git a/src/browser/mod.rs b/src/browser/mod.rs new file mode 100644 index 0000000..8359c51 --- /dev/null +++ b/src/browser/mod.rs @@ -0,0 +1,19 @@ +use self::web_browser::{Browser, WEB_BROWSER}; +use crate::Config; +use thirtyfour::prelude::WebDriverResult; + +mod web_browser; + +pub async fn init(driver_url: &String) { + unsafe { + WEB_BROWSER = Some(Browser::new(driver_url).await); + } +} + +pub async unsafe fn login(credentials: &Config) -> WebDriverResult<()> { + if let Some(driver) = &WEB_BROWSER { + driver._login(credentials).await?; + } + + Ok(()) +} diff --git a/src/browser/web_browser.rs b/src/browser/web_browser.rs new file mode 100644 index 0000000..53b8baa --- /dev/null +++ b/src/browser/web_browser.rs @@ -0,0 +1,68 @@ +use crate::Config; +use std::{thread, time}; +use thirtyfour::error::{WebDriverError, WebDriverErrorInfo, WebDriverErrorValue}; +use thirtyfour::prelude::{By, WebDriverResult}; +use thirtyfour::{FirefoxCapabilities, WebDriver, WebDriverCommands}; + +const LOGIN_URL: &str = "https://studenti.smartedu.unict.it/WorkFlow2011/Logon/Logon.aspx"; + +pub struct Browser { + driver: Option, +} + +impl Browser { + pub async fn new(driver_url: &String) -> Self { + Self { + driver: Some( + WebDriver::new(driver_url, FirefoxCapabilities::new()) + .await + .unwrap(), + ), + } + } + + // TODO: Close the driver fixing the borrowing error + // async fn _close(self) -> Result<(), Box> { + // Ok(()) + // } + + pub async unsafe fn _login(&self, credentials: &Config) -> WebDriverResult<()> { + if let Some(_d) = &self.driver { + _d.get(LOGIN_URL).await?; + + let cf_input = _d.find_element(By::Name("ctl01$contents$UserName")).await?; + cf_input.send_keys(&credentials.cf).await?; + + let psw_input = _d + .find_element(By::Name("ctl01$contents$UserPassword")) + .await?; + psw_input.send_keys(&credentials.password).await?; + + thread::sleep(time::Duration::from_millis(1000)); + + _d.find_element(By::Name("ctl01$contents$LogonButton")) + .await? + .click() + .await?; + + thread::sleep(time::Duration::from_millis(2000)); + + if _d.current_url().await? == LOGIN_URL { + return Err(WebDriverError::SessionNotCreated(WebDriverErrorInfo { + status: 400, + error: "SessionNotCreated".to_string(), + value: WebDriverErrorValue { + message: "SessionNotCreated".to_string(), + error: None, + stacktrace: None, + data: None, + }, + })); + } + } + + Ok(()) + } +} + +pub static mut WEB_BROWSER: Option = None; -- cgit v1.2.3-18-g5258