def jblock_print_frequency(): """Print a string representation of the current frequency data.""" global jblock_buckets if jblock_buckets is None: return freq = jblock_buckets.get_token_frequency() message.info(str(freq))
def _on_lists_downloaded(self) -> None: """Install block lists after files have been downloaded.""" with open(self._local_hosts_file, 'w', encoding='utf-8') as f: for host in sorted(self._blocked_hosts): f.write(host + '\n') message.info("adblock: Read {} hosts from {} sources.".format( len(self._blocked_hosts), self._done_count))
def jblock_reload(quiet=False): """Reload jblock rules from disk.""" global init_time global jblock_buckets global psl global whitelist_urls init_time = time.perf_counter() lines = [] if JBLOCK_RULES.exists(): with open(JBLOCK_RULES, "r", encoding="utf-8") as f: lines = f.readlines() freq = None if JBLOCK_FREQ.exists(): with open(JBLOCK_FREQ, "rb") as f: freq = pickle.load(f) jblock_buckets = bucket.JBlockBuckets(lines, token_frequency=freq) init_time = time.perf_counter() - init_time if not quiet: message.info("Loaded {} rules from lists.".format(len(jblock_buckets))) # Init whitelist (handled entirely in integration) if JBLOCK_WHITELIST.exists(): with open(JBLOCK_WHITELIST, 'r') as f: whitelist_urls = frozenset( filter(None, map(operator.methodcaller('strip'), f))) # initialize PSL psl = fpdomain.PSL(PSL_FILE)
def zoom(tab: apitypes.Tab, level: str = None, count: int = None, quiet: bool = False) -> None: """Set the zoom level for the current tab. The zoom can be given as argument or as [count]. If neither is given, the zoom is set to the default zoom. If both are given, use [count]. Args: level: The zoom percentage to set. count: The zoom percentage to set. quiet: Don't show a zoom level message. """ if count is not None: int_level = count elif level is not None: try: int_level = int(level.rstrip('%')) except ValueError: raise cmdutils.CommandError( "zoom: Invalid int value {}".format(level)) else: int_level = int(config.val.zoom.default) try: tab.zoom.set_factor(int_level / 100) except ValueError: raise cmdutils.CommandError("Can't zoom {}%!".format(int_level)) if not quiet: message.info("Zoom level: {}%".format(int_level), replace=True)
def read_cache(self) -> None: """Initialize the adblocking engine from cache file.""" try: cache_exists = self._cache_path.is_file() except OSError: logger.error("Failed to read adblock cache", exc_info=True) return if cache_exists: logger.debug("Loading cached adblock data: %s", self._cache_path) try: self._engine.deserialize_from_file(str(self._cache_path)) except ValueError as e: if str(e) != "DeserializationError": # All Rust exceptions get turned into a ValueError by # python-adblock raise message.error( "Reading adblock filter data failed (corrupted data?). " "Please run :adblock-update.") else: if (config.val.content.blocking.adblock.lists and not self._has_basedir and config.val.content.blocking.enabled and self.enabled): message.info("Run :adblock-update to get adblock lists.")
def _on_lists_downloaded(self, done_count: int, filter_set: "adblock.FilterSet") -> None: """Install block lists after files have been downloaded.""" self._engine = adblock.Engine(filter_set) self._engine.serialize_to_file(str(self._cache_path)) message.info( f"braveadblock: Filters successfully read from {done_count} sources." )
def callback(data: str) -> None: """Write the data to disk.""" try: with open(dest, 'w', encoding='utf-8') as f: f.write(data) except OSError as e: message.error('Could not write page: {}'.format(e)) else: message.info("Dumped page to {}.".format(dest))
def message_info(text: str, count: int = 1) -> None: """Show an info message in the statusbar. Args: text: The text to show. count: How many times to show the message """ for _ in range(count): message.info(text)
def redirect(info: interceptor.Request): url = info.request_url if url.host() == 'www.reddit.com': url.setHost('old.reddit.com') try: info.redirect(url) message.info("Redirecting to " + url.toString()) except RedirectException: pass
def read_cache(self) -> None: """Initialize the adblocking engine from cache file.""" if self._cache_path.is_file(): logger.debug("Loading cached adblock data: %s", self._cache_path) self._engine.deserialize_from_file(str(self._cache_path)) else: if (config.val.content.blocking.adblock.lists and not self._has_basedir and config.val.content.blocking.enabled and self.enabled): message.info("Run :adblock-update to get adblock lists.")
def int_fn(info: interceptor.Request): """Block the given request if necessary.""" if (info.resource_type != interceptor.ResourceType.main_frame or info.request_url.scheme() in {"data", "blob"}): return url = info.request_url redir = REDIRECT_MAP.get(url.host()) if redir is not None and redir(url) is not False: message.info("Redirecting to " + url.toString()) info.redirect(url)
def _on_lists_downloaded(self, done_count: int) -> None: """Install block lists after files have been downloaded.""" try: with open(self._local_hosts_file, "w", encoding="utf-8") as f: for host in sorted(self._blocked_hosts): f.write(host + "\n") message.info( "hostblock: Read {} hosts from {} sources.".format( len(self._blocked_hosts), done_count)) except OSError: logger.exception("Failed to write host block list!")
def message_info(text: str, count: int = 1, rich: bool = False) -> None: """Show an info message in the statusbar. Args: text: The text to show. count: How many times to show the message. rich: Render the given text as https://doc.qt.io/qt-5/richtext-html-subset.html[Qt Rich Text]. """ for _ in range(count): message.info(text, rich=rich)
def _on_download_finished(self, fileobj: IO[bytes], filter_set: "adblock.FilterSet") -> None: """When a blocklist download finishes, add it to the given filter set. Arguments: fileobj: The finished download's contents. """ fileobj.seek(0) try: with io.TextIOWrapper(fileobj, encoding="utf-8") as text_io: filter_set.add_filter_list(text_io.read()) except UnicodeDecodeError: message.info("braveadblock: Block list is not valid utf-8")
def zoom_out(tab: apitypes.Tab, count: int = 1, quiet: bool = False) -> None: """Decrease the zoom level for the current tab. Args: count: How many steps to zoom out. quiet: Don't show a zoom level message. """ try: perc = tab.zoom.apply_offset(-count) except ValueError as e: raise cmdutils.CommandError(e) if not quiet: message.info("Zoom level: {}%".format(int(perc)), replace=True)
def int_fn(info: interceptor.Request): """Redirect logic.""" url = info.request_url if (info.resource_type != interceptor.ResourceType.main_frame) or ( url.scheme() in {"data", "blob",} ): return host = url.host() if host[:4] == "www.": host = host[4:] redir = REDIRECT_MAP.get(host) if redir is not None and redir(url) is not False: message.info("Redirecting to " + url.toString()) info.redirect(url)
def read_hosts(self) -> None: """Read hosts from the existing blocked-hosts file.""" self._blocked_hosts = set() self._read_hosts_file(self._config_hosts_file, self._config_blocked_hosts) found = self._read_hosts_file(self._local_hosts_file, self._blocked_hosts) if not found: if (config.val.content.blocking.hosts.lists and not self._has_basedir and config.val.content.blocking.enabled and self.enabled): message.info("Run :adblock-update to get adblock lists.")
def read_hosts(self) -> None: """Read hosts from the existing blocked-hosts file.""" self._blocked_hosts = set() self._read_hosts_file(self._config_hosts_file, self._config_blocked_hosts) found = self._read_hosts_file(self._local_hosts_file, self._blocked_hosts) if not found: if (config.val.content.host_blocking.lists and not self._has_basedir and config.val.content.host_blocking.enabled): message.info("Run :adblock-update to get adblock lists.")
def read_cache(self) -> None: """Initialize the adblocking engine from cache file.""" try: cache_exists = self._cache_path.is_file() except OSError: logger.error("Failed to read adblock cache", exc_info=True) return if cache_exists: logger.debug("Loading cached adblock data: %s", self._cache_path) self._engine.deserialize_from_file(str(self._cache_path)) else: if (config.val.content.blocking.adblock.lists and not self._has_basedir and config.val.content.blocking.enabled and self.enabled): message.info("Run :adblock-update to get adblock lists.")
def jblock_update(quiet=False): """Pull adblock lists from the internet onto disk.""" global psl page = "" lists = qbconfig.val.content.host_blocking.lists # TODO handle local block lists for l in lists: r = urllib.request.Request(l.toString(), headers={"User-Agent": "Mozilla/5.0"}) page += urllib.request.urlopen(r).read().decode("utf-8") if not quiet: message.info("Pulled {} lines from {} sources".format( len(page), len(lists))) with open(JBLOCK_RULES, "w") as f: f.write(page) if not quiet: message.info("Updating public suffix list.") psl.update(PSL_FILE)
def toggle_proxy(): if c.content.proxy == global_proxy: c.content.proxy = acl_proxy message.info(f"Switch proxy to {acl_proxy}") elif c.content.proxy == acl_proxy: c.content.proxy = 'none' message.info(f"Switch proxy to none") else: c.content.proxy = global_proxy message.info(f"Switch proxy to {global_proxy}")
def jblock_print_avg_block_time(): """Print the average amount of time spent blocking.""" message.info(str(blocking_time / blocking_num))
def jmatrix_toggle(quiet=False): global JMATRIX_ENABLED JMATRIX_ENABLED = not JMATRIX_ENABLED enabled_str = "enabled" if JMATRIX_ENABLED else "disabled" if not quiet: message.info("jmatrix has been " + enabled_str)
def home(tab: apitypes.Tab) -> None: """Open main startpage in current tab.""" if tab.navigation_blocked(): message.info("Tab is pinned!") else: tab.load_url(config.val.url.start_pages[0])
def jblock_print_buckets(): """Print a summary of the hottest buckets.""" global jblock_buckets if jblock_buckets is None: return message.info(jblock_buckets.summary_str())
def home(tab: apitypes.Tab) -> None: """Open main startpage in current tab.""" if tab.data.pinned: message.info("Tab is pinned!") else: tab.load_url(config.val.url.start_pages[0])
def jblock_print_init_time(): """Print initialization time.""" message.info(str(init_time))
def jblock_print_total_block_time(): """Print the total amount of time spent blocking.""" message.info(str(blocking_time))
def jblock_print_slowest_urls(): """Print the urls that we spent the most time handling.""" message.info(str(sorted(slowest_urls, reverse=True)))
def jblock_print_history(): """Print all handled urls.""" message.info("\n".join(block_history))