예제 #1
0
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))
예제 #2
0
 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))
예제 #3
0
 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))
예제 #4
0
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)
예제 #5
0
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)
예제 #6
0
    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.")
예제 #7
0
 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."
     )
예제 #8
0
 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))
예제 #9
0
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)
예제 #10
0
 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))
예제 #11
0
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)
예제 #12
0
파일: config.py 프로젝트: lufte/dotfiles
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
예제 #13
0
 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.")
예제 #14
0
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)
예제 #15
0
 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!")
예제 #16
0
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)
예제 #17
0
    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")
예제 #18
0
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)
예제 #19
0
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)
예제 #20
0
    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.")
예제 #21
0
    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.")
예제 #22
0
    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.")
예제 #23
0
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)
예제 #24
0
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}")
예제 #25
0
def jblock_print_avg_block_time():
    """Print the average amount of time spent blocking."""
    message.info(str(blocking_time / blocking_num))
예제 #26
0
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)
예제 #27
0
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])
예제 #28
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())
예제 #29
0
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])
예제 #30
0
def jblock_print_init_time():
    """Print initialization time."""
    message.info(str(init_time))
예제 #31
0
def jblock_print_total_block_time():
    """Print the total amount of time spent blocking."""
    message.info(str(blocking_time))
예제 #32
0
def jblock_print_slowest_urls():
    """Print the urls that we spent the most time handling."""
    message.info(str(sorted(slowest_urls, reverse=True)))
예제 #33
0
def jblock_print_history():
    """Print all handled urls."""
    message.info("\n".join(block_history))