Exemple #1
0
def message_error(text: str) -> None:
    """Show an error message in the statusbar.

    Args:
        text: The text to show.
    """
    message.error(text)
Exemple #2
0
    def _merge_file(self, byte_io: io.BytesIO) -> None:
        """Read and merge host files.

        Args:
            byte_io: The BytesIO object of the completed download.
        """
        error_count = 0
        line_count = 0
        try:
            f = get_fileobj(byte_io)
        except (OSError, zipfile.BadZipFile, zipfile.LargeZipFile,
                LookupError) as e:
            message.error("adblock: Error while reading {}: {} - {}".format(
                byte_io.name, e.__class__.__name__, e))
            return

        for line in f:
            line_count += 1
            ok = self._parse_line(line)
            if not ok:
                error_count += 1

        logger.debug("{}: read {} lines".format(byte_io.name, line_count))
        if error_count > 0:
            message.error("adblock: {} read errors for {}".format(
                error_count, byte_io.name))
Exemple #3
0
def jmatrix_toggle_rule(tab: apitypes.Tab, rule: str):
    """View request types made on this host and block/allow them.

	Requests are collated based on the host of the URL, so you may see requests from other pages on the same host.

	"""
    try:
        action, res_type, dest = rule.split()
    except ValueError:
        raise cmdutils.CommandError(
            "Expected input of the form \"block/allow request_type "
            "destination_host\"")
    if action.upper() == "BLOCK":
        action = jmatrix.rule.Action.ALLOW
    else:
        action = jmatrix.rule.Action.BLOCK
    if res_type == '*':
        res_type = "ALL"
    try:
        res_type = jmatrix.rule.Type[res_type.upper()]
    except KeyError:
        message.error("Type '{}' not recognized".format(res_type))
    origin = tab.url().host()
    JMATRIX_RULES.matrix_rules[origin][dest][res_type] = action
    # Change our seen requests to match so it'll show up in the completion
    # without having to reload the page.
    SEEN_REQUESTS.matrix_rules[origin][dest][res_type] = action
Exemple #4
0
    def single_cb(elem: Optional[apitypes.WebElement]) -> None:
        """Click a single element."""
        if elem is None:
            message.error(
                f"No element found {_FILTER_ERRORS[filter_](value)}!")
            return

        do_click(elem)
Exemple #5
0
def _wrap_find_at_pos(
        value: str, tab: apitypes.Tab,
        callback: Callable[[Optional[apitypes.WebElement]], None]) -> None:
    try:
        point = utils.parse_point(value)
    except ValueError as e:
        message.error(str(e))
        return
    tab.elements.find_at_pos(point, callback)
Exemple #6
0
 def _insert_text_cb(elem: apitypes.WebElement) -> None:
     if elem is None:
         message.error("No element focused!")
         return
     try:
         elem.insert_text(text)
     except apitypes.WebElemError as e:
         message.error(str(e))
         return
Exemple #7
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))
Exemple #8
0
    def on_file_updated() -> None:
        """Source the new config when editing finished.

		"""
        try:
            jmatrix_read_config()
        except:
            message.error(
                "Unexpected error while reloading rules file. Check syntax?")
Exemple #9
0
 def single_cb(elem: apitypes.WebElement) -> None:
     """Click a single element."""
     if elem is None:
         message.error("No element found with id {}!".format(value))
         return
     try:
         elem.click(target, force_event=force_event)
     except apitypes.WebElemError as e:
         message.error(str(e))
         return
Exemple #10
0
    def _import_local(self, filename: str) -> None:
        """Adds the contents of a file to the blocklist.

        Args:
            filename: path to a local file to import.
        """
        try:
            fileobj = open(filename, 'rb')
        except OSError as e:
            message.error("adblock: Error while reading {}: {}".format(
                filename, e.strerror))
            return
        download = _FakeDownload(fileobj)
        self._in_progress.append(download)
        self._on_download_finished(download)
Exemple #11
0
 def do_click(elem: apitypes.WebElement) -> None:
     try:
         elem.click(target, force_event=force_event)
     except apitypes.WebElemError as e:
         message.error(str(e))
Exemple #12
0
def click_element(
        tab: apitypes.Tab,
        filter_: str,
        value: str = None,
        *,  # noqa: C901
        target: apitypes.ClickTarget = apitypes.ClickTarget.normal,
        force_event: bool = False,
        select_first: bool = False) -> None:
    """Click the element matching the given filter.

    The given filter needs to result in exactly one element, otherwise, an
    error is shown.

    Args:
        filter_: How to filter the elements.

            - id: Get an element based on its ID.
            - css: Filter by a CSS selector.
            - position: Click the element at specified position.
               Specify `value` as 'x,y'.
            - focused: Click the currently focused element.
        value: The value to filter for. Optional for 'focused' filter.
        target: How to open the clicked element (normal/tab/tab-bg/window).
        force_event: Force generating a fake click event.
        select_first: Select first matching element if there are multiple.
    """
    def do_click(elem: apitypes.WebElement) -> None:
        try:
            elem.click(target, force_event=force_event)
        except apitypes.WebElemError as e:
            message.error(str(e))

    def single_cb(elem: Optional[apitypes.WebElement]) -> None:
        """Click a single element."""
        if elem is None:
            message.error(
                f"No element found {_FILTER_ERRORS[filter_](value)}!")
            return

        do_click(elem)

    def multiple_cb(elems: Sequence[apitypes.WebElement]) -> None:
        if not elems:
            message.error(
                f"No element found {_FILTER_ERRORS[filter_](value)}!")
            return

        if not select_first and len(elems) > 1:
            message.error(
                f"Multiple elements found {_FILTER_ERRORS[filter_](value)}!")
            return

        do_click(elems[0])

    if value is None and filter_ != 'focused':
        raise cmdutils.CommandError("Argument 'value' is only "
                                    "optional with filter 'focused'!")

    if filter_ == "id":
        assert value is not None
        tab.elements.find_id(elem_id=value, callback=single_cb)
    elif filter_ == "css":
        assert value is not None
        tab.elements.find_css(
            value,
            callback=multiple_cb,
            error_cb=lambda exc: message.error(str(exc)),
        )
    elif filter_ == "position":
        assert value is not None
        _wrap_find_at_pos(value, tab=tab, callback=single_cb)
    elif filter_ == "focused":
        tab.elements.find_focused(callback=single_cb)
    else:
        raise utils.Unreachable(filter_)
Exemple #13
0
 def print_callback(ok: bool) -> None:
     if not ok:
         message.error("Printing failed!")