from app.request import VALID_PARAMS from app.utils.filter_utils import * from bs4.element import ResultSet from cryptography.fernet import Fernet import re import os import urllib.parse as urlparse from urllib.parse import parse_qs import cssutils class Filter: def __init__(self, user_keys: dict, mobile=False, config=None): if config is None: config = {} self.near = config['near'] if 'near' in config else '' self.dark = config['dark'] if 'dark' in config else False self.nojs = config['nojs'] if 'nojs' in config else False self.theme = config['theme'] if 'theme' in config else None self.new_tab = config['new_tab'] if 'new_tab' in config else False self.alt_redirect = config['alts'] if 'alts' in config else False self.mobile = mobile self.user_keys = user_keys self.main_divs = ResultSet('') self._elements = 0 def __getitem__(self, name): return getattr(self, name) @property def elements(self): return self._elements def get_theme_file(self): """Returns the contents of the theme file as a string, if it exists. Otherwise returns empty string Returns: str: contents of the theme file """ contents = "" if self.theme: theme_file = f'app/static/css/themes/{self.theme}.css' if os.path.exists(theme_file): contents = open(theme_file).read() return contents def parse_theme_colors(self): """parses the css theme and looks for re-skinning colors. Specifically looks for the .reskin CSS selector. If no selector is found, returns default background 'fff' Returns: dict: Key-value dictionary of the properties """ result = {'background-color':'fff'} if self.theme: sheet = cssutils.parseString(self.get_theme_file()) if self.dark: selector_name = ".reskin-dark" else: selector_name = ".reskin" reskin_selector = [i for i in sheet if i.selectorText==selector_name] if len(reskin_selector) == 0: return result for css_prop in reskin_selector[0].style: result[css_prop.name] = css_prop.value return result def reskin(self, page): # Aesthetic only re-skinning page = page.replace('>G<', '>Wh<') pattern = re.compile('4285f4|ea4335|fbcc05|34a853|fbbc05', re.IGNORECASE) page = pattern.sub('685e79', page) theme_colors = self.parse_theme_colors() page = page.replace('fff', theme_colors['background-color'].replace("#","")) if self.dark: page = page.replace('202124', 'ddd').replace('1967D2', '3b85ea') page = page.replace('