2019-01-07 11:16:16 +01:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
2019-01-14 12:11:17 +01:00
|
|
|
"""
|
|
|
|
Operator is the main object that interacts with the foreign
|
|
|
|
service. It exposes methods to login, logout and check in and out.
|
|
|
|
"""
|
2019-01-11 18:19:35 +01:00
|
|
|
|
2019-01-14 12:11:17 +01:00
|
|
|
from datetime import datetime, timedelta
|
2019-01-11 18:19:35 +01:00
|
|
|
import logging
|
|
|
|
import os
|
2019-01-17 18:17:56 +01:00
|
|
|
import pkg_resources
|
2019-01-21 09:33:28 +01:00
|
|
|
import shutil
|
|
|
|
import sys
|
2019-01-13 00:04:02 +01:00
|
|
|
import time
|
2019-01-11 18:19:35 +01:00
|
|
|
import typing as T
|
2019-01-14 15:41:08 +01:00
|
|
|
from urllib.parse import urlparse
|
2019-01-11 18:19:35 +01:00
|
|
|
|
2019-01-21 17:59:44 +01:00
|
|
|
geckoexe = shutil.which("geckodriver")
|
2019-01-21 09:33:28 +01:00
|
|
|
if geckoexe is None:
|
2019-01-21 17:59:44 +01:00
|
|
|
local_path = pkg_resources.resource_filename(__name__, "bin")
|
2019-01-21 09:33:28 +01:00
|
|
|
try:
|
2019-01-21 17:59:44 +01:00
|
|
|
os.stat(os.path.join(local_path, "geckodriver"))
|
|
|
|
os.environ["PATH"] = os.environ["PATH"] + ":" + local_path
|
2019-01-21 09:33:28 +01:00
|
|
|
except FileNotFoundError:
|
|
|
|
print("Missing geckodriver executable in path", file=sys.stderr)
|
|
|
|
raise
|
2019-01-11 18:19:35 +01:00
|
|
|
|
2019-01-21 09:33:28 +01:00
|
|
|
from selenium import webdriver as wd # noqa
|
2019-01-21 17:59:44 +01:00
|
|
|
from selenium.common.exceptions import (
|
|
|
|
WebDriverException,
|
|
|
|
NoSuchElementException,
|
|
|
|
) # noqa
|
2019-01-11 18:19:35 +01:00
|
|
|
|
|
|
|
|
2019-01-28 18:15:22 +01:00
|
|
|
# TODO: read it from configuration.
|
|
|
|
RETRIES = 3
|
|
|
|
|
2019-02-05 15:10:45 +01:00
|
|
|
log_fmt = logging.Formatter("%(levelname)s: [%(name)s] -> %(message)s")
|
|
|
|
console = logging.StreamHandler(stream=sys.stdout)
|
|
|
|
console.setFormatter(log_fmt)
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
logger.addHandler(console)
|
|
|
|
logger.setLevel(os.environ.get("BOTZ_LOGLEVEL", logging.INFO))
|
|
|
|
logger.debug("Init at debug")
|
2019-01-11 18:19:35 +01:00
|
|
|
|
2019-01-28 18:15:54 +01:00
|
|
|
|
2019-01-28 18:15:22 +01:00
|
|
|
def safely(retries: int = 0) -> T.Callable:
|
2019-02-07 12:01:19 +01:00
|
|
|
retr = retries
|
|
|
|
|
2019-01-28 18:15:22 +01:00
|
|
|
def _safely(f: T.Callable) -> T.Callable:
|
2019-02-07 12:01:19 +01:00
|
|
|
ret = retr
|
|
|
|
|
2019-01-28 18:15:22 +01:00
|
|
|
def _protection(self, *args, **kwargs):
|
2019-02-07 12:01:19 +01:00
|
|
|
r = ret
|
2019-01-28 18:15:22 +01:00
|
|
|
done = False
|
2019-02-07 12:01:19 +01:00
|
|
|
while r > 0:
|
2019-01-28 18:15:22 +01:00
|
|
|
try:
|
|
|
|
f(self, *args, **kwargs)
|
2019-02-07 12:01:19 +01:00
|
|
|
logger.debug("Success executing %s", f.__name__)
|
|
|
|
self.switch_to.default_content()
|
|
|
|
return
|
2019-01-28 18:15:22 +01:00
|
|
|
except WebDriverException as e:
|
|
|
|
self.logger.error(
|
2019-02-07 12:01:19 +01:00
|
|
|
"Something went wrong: %s [tentative #%s]", e, ret - r
|
2019-01-28 18:15:22 +01:00
|
|
|
)
|
2019-02-07 12:01:19 +01:00
|
|
|
r -= 1
|
2019-01-21 17:59:44 +01:00
|
|
|
|
2019-01-28 18:15:22 +01:00
|
|
|
return _protection
|
2019-01-11 18:19:35 +01:00
|
|
|
|
2019-01-28 18:15:22 +01:00
|
|
|
return _safely
|
2019-01-11 18:19:35 +01:00
|
|
|
|
|
|
|
|
2019-01-14 12:11:17 +01:00
|
|
|
def _is_present(driver: wd.Firefox, xpath: str) -> bool:
|
|
|
|
try:
|
|
|
|
driver.find_element_by_xpath(xpath)
|
|
|
|
return True
|
|
|
|
except NoSuchElementException:
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
2019-01-21 17:59:44 +01:00
|
|
|
def is_present(
|
|
|
|
driver: wd.Firefox, xpath: str, timeout: T.Optional[timedelta] = None
|
|
|
|
) -> bool:
|
2019-01-14 12:11:17 +01:00
|
|
|
"""
|
|
|
|
Helper function. If an element is present in the DOM tree,
|
|
|
|
returns true. False otherwise.
|
|
|
|
"""
|
|
|
|
if timeout is None:
|
|
|
|
return _is_present(driver, xpath)
|
|
|
|
|
|
|
|
_now = datetime.now()
|
|
|
|
_elapsed = timedelta(seconds=0)
|
|
|
|
while _elapsed < timeout:
|
2019-02-05 15:10:45 +01:00
|
|
|
logger.debug("Not yet present: %s", xpath)
|
2019-01-14 12:11:17 +01:00
|
|
|
if _is_present(driver, xpath):
|
2019-02-05 15:10:45 +01:00
|
|
|
logger.debug("Present: %s", xpath)
|
2019-01-14 12:11:17 +01:00
|
|
|
return True
|
|
|
|
time.sleep(0.5)
|
|
|
|
_elapsed = datetime.now() - _now
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
2019-01-11 18:19:35 +01:00
|
|
|
class Operator(wd.Firefox):
|
|
|
|
def __init__(
|
2019-01-21 17:59:44 +01:00
|
|
|
self,
|
|
|
|
base_uri: str,
|
|
|
|
name: str = None,
|
|
|
|
timeout: int = 20,
|
|
|
|
proxy: T.Optional[T.Tuple[str, int]] = None,
|
|
|
|
headless: bool = True,
|
|
|
|
debug: bool = False,
|
|
|
|
*args,
|
|
|
|
**kwargs
|
|
|
|
) -> None:
|
2019-01-11 18:19:35 +01:00
|
|
|
"""
|
|
|
|
Adds some configuration to Firefox.
|
|
|
|
"""
|
2019-01-28 18:15:22 +01:00
|
|
|
self.retries = RETRIES
|
2019-01-11 18:19:35 +01:00
|
|
|
self.profile = wd.FirefoxProfile()
|
|
|
|
# Do not send telemetry
|
2019-01-21 17:59:44 +01:00
|
|
|
self.profile.set_preference("datareporting.policy.dataSubmissionEnabled", False)
|
|
|
|
self.profile.set_preference("datareporting.healthreport.service.enabled", False)
|
|
|
|
self.profile.set_preference("datareporting.healthreport.uploadEnabled", False)
|
2019-01-11 18:19:35 +01:00
|
|
|
|
|
|
|
self.opts = wd.firefox.options.Options()
|
|
|
|
self.opts.headless = headless
|
|
|
|
|
|
|
|
self.debug = debug
|
|
|
|
self.base_uri = base_uri
|
2019-01-14 15:41:08 +01:00
|
|
|
self.uri = urlparse(base_uri)
|
2019-01-14 12:11:17 +01:00
|
|
|
self.timeout = timedelta(seconds=timeout)
|
2019-01-11 18:19:35 +01:00
|
|
|
|
|
|
|
if proxy:
|
2019-01-21 17:59:44 +01:00
|
|
|
self.profile.set_preference("network.proxy.type", 1)
|
|
|
|
self.profile.set_preference("network.proxy.http", proxy[0])
|
|
|
|
self.profile.set_preference("network.proxy.http_port", proxy[1])
|
|
|
|
self.profile.set_preference("network.proxy.ssl", proxy[0])
|
|
|
|
self.profile.set_preference("network.proxy.ssl_port", proxy[1])
|
2019-01-11 18:19:35 +01:00
|
|
|
|
2019-01-21 17:59:44 +01:00
|
|
|
super().__init__(
|
|
|
|
firefox_profile=self.profile, options=self.opts, *args, **kwargs
|
|
|
|
)
|
2019-01-14 15:41:08 +01:00
|
|
|
self.fullscreen_window()
|
2019-01-11 18:19:35 +01:00
|
|
|
|
|
|
|
self.z_name = name if name is not None else __name__
|
|
|
|
self.logger = logging.getLogger("{}.{}".format(__name__, self.name))
|
|
|
|
if debug:
|
|
|
|
self.logger.setLevel(logging.DEBUG)
|
|
|
|
self.logger.debug("Debug level")
|
|
|
|
self._logged_in = False
|
|
|
|
self._checked_in = False
|
2019-02-07 12:01:19 +01:00
|
|
|
self.username = None
|
|
|
|
# Clean preceding session
|
|
|
|
self.delete_all_cookies()
|
2019-01-11 18:19:35 +01:00
|
|
|
|
2019-01-28 18:15:22 +01:00
|
|
|
@safely(RETRIES)
|
2019-01-21 17:59:44 +01:00
|
|
|
def login(self, user: str, password: str, force: bool = False) -> None:
|
2019-01-11 18:19:35 +01:00
|
|
|
"""
|
|
|
|
Do the login and proceed.
|
|
|
|
"""
|
2019-01-14 12:11:17 +01:00
|
|
|
if self._logged_in:
|
|
|
|
self.logger.warning("Already logged in: %s", user)
|
|
|
|
if not force:
|
|
|
|
return
|
|
|
|
self.logger.info("Forcing login: %s", user)
|
2019-01-11 18:19:35 +01:00
|
|
|
# Retrieve login page
|
2019-01-13 00:04:02 +01:00
|
|
|
self.get(self.base_uri)
|
2019-02-18 12:19:19 +01:00
|
|
|
time.sleep(5)
|
2019-01-21 17:59:44 +01:00
|
|
|
_correct_url = "cpccchk" in self.current_url
|
2019-01-14 12:11:17 +01:00
|
|
|
_now = datetime.now()
|
|
|
|
_elapsed = timedelta(seconds=0)
|
2019-02-18 12:19:19 +01:00
|
|
|
while (
|
|
|
|
not is_present(self, '//input[contains(@id, "_Accedi")]') and _correct_url
|
|
|
|
):
|
2019-01-14 12:11:17 +01:00
|
|
|
self.logger.debug("Not yet on login page: %s", self.current_url)
|
|
|
|
time.sleep(0.5)
|
2019-01-21 17:59:44 +01:00
|
|
|
_correct_url = "cpccchk" in self.current_url
|
2019-01-14 12:11:17 +01:00
|
|
|
_elapsed = datetime.now() - _now
|
|
|
|
if _elapsed > self.timeout:
|
2019-02-18 12:19:19 +01:00
|
|
|
self.logger.error(
|
|
|
|
"Login page did not load properly: %s", self.current_url
|
|
|
|
)
|
|
|
|
return
|
2019-01-11 18:19:35 +01:00
|
|
|
self.logger.debug("After login get: %s", self.current_url)
|
2019-01-14 12:11:17 +01:00
|
|
|
time.sleep(1)
|
2019-01-11 18:19:35 +01:00
|
|
|
# Username
|
2019-01-21 17:59:44 +01:00
|
|
|
user_form = self.find_element_by_name("m_cUserName")
|
2019-01-11 18:19:35 +01:00
|
|
|
# Password
|
2019-01-21 17:59:44 +01:00
|
|
|
pass_form = self.find_element_by_name("m_cPassword")
|
2019-01-11 18:19:35 +01:00
|
|
|
# Login button
|
|
|
|
login_butt = self.find_element_by_xpath('//input[contains(@id, "_Accedi")]')
|
|
|
|
# Compile and submit
|
|
|
|
user_form.send_keys(user)
|
|
|
|
pass_form.send_keys(password)
|
|
|
|
do_it = True
|
2019-02-20 18:11:08 +01:00
|
|
|
if self.debug and not force and not self.opts.headless:
|
2019-01-14 12:11:17 +01:00
|
|
|
_do_it = input("Really do the login? [y/n] ").lower()
|
2019-01-11 18:19:35 +01:00
|
|
|
do_it = True if _do_it == "y" else False
|
|
|
|
if do_it:
|
|
|
|
login_butt.submit()
|
2019-01-14 12:11:17 +01:00
|
|
|
time.sleep(5)
|
2019-01-11 18:19:35 +01:00
|
|
|
self.logger.debug("Login result: %s", self.title)
|
2019-01-21 17:59:44 +01:00
|
|
|
if "Routine window" in self.title:
|
2019-01-14 12:11:17 +01:00
|
|
|
self.logger.debug("Reloading...")
|
2019-01-13 00:04:02 +01:00
|
|
|
self.refresh()
|
2019-01-14 12:11:17 +01:00
|
|
|
self.switch_to.alert.accept()
|
|
|
|
if is_present(self, '//a[contains(@class, "imgMenu_ctrl")]', self.timeout):
|
2019-01-11 18:19:35 +01:00
|
|
|
self._logged_in = True
|
2019-01-13 00:04:02 +01:00
|
|
|
self.logger.info("Login success for user: %s", user)
|
2019-01-14 12:11:17 +01:00
|
|
|
else:
|
|
|
|
self.logger.error("Login failed: %s", user)
|
2019-02-07 12:01:19 +01:00
|
|
|
self.username = user
|
2019-01-14 12:11:17 +01:00
|
|
|
|
2019-01-28 18:15:22 +01:00
|
|
|
@safely(RETRIES)
|
2019-02-07 12:01:19 +01:00
|
|
|
def logout(self, force: bool = False) -> None:
|
2019-01-14 12:11:17 +01:00
|
|
|
"""
|
|
|
|
Do the logout.
|
|
|
|
"""
|
|
|
|
if not self._logged_in:
|
2019-02-07 12:01:19 +01:00
|
|
|
self.logger.warning("Not yet logged in")
|
2019-01-14 12:11:17 +01:00
|
|
|
if not force:
|
|
|
|
return
|
2019-02-07 12:01:19 +01:00
|
|
|
self.logger.info("Forcing logout: %s", self.username)
|
2019-01-14 12:11:17 +01:00
|
|
|
# Find the Profile menu and open it
|
2019-01-21 17:59:44 +01:00
|
|
|
profile_butt = self.find_element_by_xpath(
|
|
|
|
'//span[contains(@id, "imgNoPhotoLabel")]'
|
|
|
|
)
|
2019-01-14 12:11:17 +01:00
|
|
|
profile_butt.click()
|
|
|
|
time.sleep(1)
|
|
|
|
# Find the logout button
|
|
|
|
logout_butt = self.find_element_by_xpath('//input[@value="Logout user"]')
|
|
|
|
logout_butt.click()
|
|
|
|
if "jsp/usut_wapplogout_portlet.jsp" in self.current_url:
|
2019-02-07 12:01:19 +01:00
|
|
|
self.logger.info("User successfully logged out: %s", self.username)
|
|
|
|
self.username = None
|
2019-02-17 18:22:01 +01:00
|
|
|
self.delete_all_cookies()
|
2019-01-14 12:11:17 +01:00
|
|
|
else:
|
2019-02-07 12:01:19 +01:00
|
|
|
self.logger.warning("Logout failed: %s", self.username)
|
2019-01-14 12:11:17 +01:00
|
|
|
|
2019-01-14 15:41:08 +01:00
|
|
|
@property
|
|
|
|
def logged_in(self) -> bool:
|
2019-01-14 12:11:17 +01:00
|
|
|
"""
|
|
|
|
Check if already logged in. Checks if page is '/jsp/home.jsp'
|
|
|
|
and if login cookie is set (and not expired).
|
|
|
|
"""
|
2019-01-21 17:59:44 +01:00
|
|
|
_base_domain = ".".join(self.uri.netloc.split(".")[-2:])
|
|
|
|
cookies = [c["name"] for c in self.get_cookies() if _base_domain in c["domain"]]
|
2019-02-16 19:51:51 +01:00
|
|
|
self.logger.debug("Cookies: %s", cookies)
|
|
|
|
# _right_url = "/jsp/home.jsp" in self.current_url
|
|
|
|
_cookies = all(c in cookies for c in ("spcookie", "JSESSIONID", "ipclientid"))
|
|
|
|
return _cookies
|
2019-01-11 18:19:35 +01:00
|
|
|
|
2019-01-28 18:15:22 +01:00
|
|
|
@property
|
|
|
|
def checked_in(self) -> bool:
|
|
|
|
"""
|
|
|
|
Check if the user is checked in already.
|
|
|
|
"""
|
|
|
|
return self._checked_in
|
|
|
|
|
|
|
|
@safely(RETRIES)
|
2019-01-21 17:59:44 +01:00
|
|
|
def check_in(self, force: bool = False) -> None:
|
2019-01-11 18:19:35 +01:00
|
|
|
"""
|
|
|
|
Click the check in button.
|
|
|
|
"""
|
2019-01-14 15:41:08 +01:00
|
|
|
if not force and not self.logged_in:
|
|
|
|
self.logger.warning("Not logged in!")
|
|
|
|
return
|
2019-01-11 18:19:35 +01:00
|
|
|
if self._checked_in:
|
2019-01-14 15:41:08 +01:00
|
|
|
self.logger.warn("Already checked in!")
|
2019-01-11 18:19:35 +01:00
|
|
|
if not force:
|
|
|
|
return
|
2019-01-21 17:59:44 +01:00
|
|
|
iframe = self.find_element_by_xpath(
|
|
|
|
'//iframe[contains(@id, "gsmd_container.jsp")]'
|
|
|
|
)
|
2019-01-14 15:41:08 +01:00
|
|
|
self.switch_to.frame(iframe)
|
2019-01-14 12:11:17 +01:00
|
|
|
enter_butt = self.find_element_by_xpath('//input[@value="Entrata"]')
|
2019-01-14 15:41:08 +01:00
|
|
|
enter_butt.click()
|
2019-01-11 18:19:35 +01:00
|
|
|
# Click the check in button and change
|
|
|
|
# self._checked_in state in case of success
|
2019-01-28 18:15:22 +01:00
|
|
|
self._checked_in = True
|
2019-01-11 18:19:35 +01:00
|
|
|
|
2019-01-28 18:15:22 +01:00
|
|
|
@safely(RETRIES)
|
2019-01-21 17:59:44 +01:00
|
|
|
def check_out(self, force: bool = False) -> None:
|
2019-01-11 18:19:35 +01:00
|
|
|
"""
|
|
|
|
Click the check out button.
|
|
|
|
"""
|
2019-01-14 15:41:08 +01:00
|
|
|
if not force and not self.logged_in:
|
|
|
|
self.logger.warning("Not logged in!")
|
|
|
|
return
|
2019-01-11 18:19:35 +01:00
|
|
|
if not self._checked_in:
|
2019-01-14 15:41:08 +01:00
|
|
|
self.logger.warn("Not yet checked in!")
|
2019-01-11 18:19:35 +01:00
|
|
|
if not force:
|
|
|
|
return
|
2019-01-21 17:59:44 +01:00
|
|
|
iframe = self.find_element_by_xpath(
|
|
|
|
'//iframe[contains(@id, "gsmd_container.jsp")]'
|
|
|
|
)
|
2019-01-14 15:41:08 +01:00
|
|
|
self.switch_to.frame(iframe)
|
2019-01-14 12:11:17 +01:00
|
|
|
exit_butt = self.find_element_by_xpath('//input[@value="Uscita"]')
|
2019-01-14 15:41:08 +01:00
|
|
|
exit_butt.click()
|
2019-01-11 18:19:35 +01:00
|
|
|
# Click the check in button and change
|
|
|
|
# self._checked_in state in case of success
|
2019-01-28 18:15:22 +01:00
|
|
|
self._checked_in = False
|
2019-01-13 00:04:02 +01:00
|
|
|
|
2019-01-14 12:11:17 +01:00
|
|
|
def __del__(self) -> None:
|
2019-01-13 00:04:02 +01:00
|
|
|
self.quit()
|