| 1 | import re |
| 2 | import sys |
| 3 | |
| 4 | import requests |
| 5 | |
| 6 | from . import logger |
| 7 | from .user_agent import UAGetter |
| 8 | |
| 9 | CHROME_DRIVER_INFO_JSON_URL = 'https://pypi.org/pypi/chromedriver-py/json' |
| 10 | VIVALDI_WEBSITE = 'https://vivaldi.com' |
| 11 | |
| 12 | |
| 13 | class ChromeDriverVersion: |
| 14 | def __init__(self, ua_string: str) -> None: |
| 15 | self.__ua_string = ua_string |
| 16 | |
| 17 | def __get_chrome_major_version(self) -> str: |
| 18 | try: |
| 19 | return self.__ua_string.split('Chrome/')[1].split('.')[0] |
| 20 | except Exception: |
| 21 | raise ValueError('Not a Chrome user agent string') |
| 22 | |
| 23 | def __get_matching_chrome_driver_version(self) -> str: |
| 24 | releases = requests.get(CHROME_DRIVER_INFO_JSON_URL).json()['releases'] |
| 25 | major_version = self.__get_chrome_major_version() |
| 26 | major_version_matches = [] |
| 27 | for k in releases.keys(): |
| 28 | if k.startswith(major_version): |
| 29 | major_version_matches.append(k) |
| 30 | return max(major_version_matches) |
| 31 | |
| 32 | def get(self): |
| 33 | return self.__get_matching_chrome_driver_version() |
| 34 | |
| 35 | |
| 36 | def get_driver_version_from_chromium_based_binary(binary_location: str) -> str: |
| 37 | logger.info( |
| 38 | f'Getting driver version from Chromium based binary: {binary_location}') |
| 39 | return ChromeDriverVersion(UAGetter(binary_location, UAGetter.HEADLESS_NEW).get()).get() |
| 40 | |
| 41 | |
| 42 | def get_vivaldi_driver_version_from_web() -> str: |
| 43 | logger.info('Getting Vivaldi version from web') |
| 44 | res = requests.get(f'{VIVALDI_WEBSITE}/download/') |
| 45 | found = re.findall(r'Vivaldi\s(\d+.\d+)<', res.text) |
| 46 | if len(found) != 1: |
| 47 | return None |
| 48 | |
| 49 | res = requests.get( |
| 50 | f'{VIVALDI_WEBSITE}/changelog-vivaldi-browser-{found[0]}/') |
| 51 | chromium_major = re.findall(r'\[Chromium\][^\d]+(\d+)', res.text) |
| 52 | if len(chromium_major) != 1: |
| 53 | return None |
| 54 | return ChromeDriverVersion(f'Chrome/{chromium_major[0]}').get() |
| 55 | |
| 56 | |
| 57 | def get_vivaldi_driver_version(binary_location, is_github_actions) -> str: |
| 58 | if sys.platform == 'win32' and is_github_actions: |
| 59 | return get_vivaldi_driver_version_from_web() |
| 60 | return get_driver_version_from_chromium_based_binary(binary_location) |