Example #1
0
def javascript_alert(url, js_msg, abort_on):
    """Display a javascript alert."""
    log.js.debug("alert: {}".format(js_msg))
    if config.get('ui', 'modal-js-dialog'):
        raise CallSuper

    if config.get('content', 'ignore-javascript-alert'):
        return

    msg = 'From <b>{}</b>:<br/>{}'.format(html.escape(url.toDisplayString()),
                                          html.escape(js_msg))
    message.ask('Javascript alert', msg, mode=usertypes.PromptMode.alert,
                abort_on=abort_on)
Example #2
0
def javascript_alert(url, js_msg, abort_on):
    """Display a javascript alert."""
    log.js.debug("alert: {}".format(js_msg))
    if config.val.content.javascript.modal_dialog:
        raise CallSuper

    if not config.val.content.javascript.alert:
        return

    msg = 'From <b>{}</b>:<br/>{}'.format(html.escape(url.toDisplayString()),
                                          html.escape(js_msg))
    message.ask('Javascript alert', msg, mode=usertypes.PromptMode.alert,
                abort_on=abort_on)
Example #3
0
def javascript_alert(url, js_msg, abort_on):
    """Display a javascript alert."""
    log.js.debug("alert: {}".format(js_msg))
    if config.val.content.javascript.modal_dialog:
        raise CallSuper

    if not config.val.content.javascript.alert:
        return

    msg = 'From <b>{}</b>:<br/>{}'.format(html.escape(url.toDisplayString()),
                                          _format_msg(js_msg))
    urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded)
    message.ask('Javascript alert', msg, mode=usertypes.PromptMode.alert,
                abort_on=abort_on, url=urlstr)
Example #4
0
    def javaScriptAlert(self, frame, js_msg):
        """Override javaScriptAlert to use the statusbar."""
        log.js.debug("alert: {}".format(js_msg))
        if config.get('ui', 'modal-js-dialog'):
            return super().javaScriptAlert(frame, js_msg)

        if (self._is_shutting_down or
                config.get('content', 'ignore-javascript-alert')):
            return

        msg = 'From <b>{}</b>:<br/>{}'.format(
            html.escape(self.mainFrame().url().toDisplayString()),
            html.escape(js_msg))
        message.ask('Javascript alert', msg, mode=usertypes.PromptMode.alert,
                    abort_on=[self.loadStarted, self.shutting_down])
Example #5
0
def javascript_alert(url, js_msg, abort_on, *, escape_msg=True):
    """Display a javascript alert."""
    log.js.debug("alert: {}".format(js_msg))
    if config.val.content.javascript.modal_dialog:
        raise CallSuper

    if not config.val.content.javascript.alert:
        return

    js_msg = html.escape(js_msg) if escape_msg else js_msg
    msg = 'From <b>{}</b>:<br/>{}'.format(html.escape(url.toDisplayString()),
                                          js_msg)
    urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded)
    message.ask('Javascript alert', msg, mode=usertypes.PromptMode.alert,
                abort_on=abort_on, url=urlstr)
Example #6
0
    def on_ssl_errors(self, reply, errors):
        """Decide if SSL errors should be ignored or not.

        This slot is called on SSL/TLS errors by the self.sslErrors signal.

        Args:
            reply: The QNetworkReply that is encountering the errors.
            errors: A list of errors.
        """
        ssl_strict = config.get('network', 'ssl-strict')
        if ssl_strict == 'ask':
            err_string = '\n'.join('- ' + err.errorString() for err in errors)
            answer = message.ask(
                self._win_id,
                'SSL errors - continue?\n{}'.format(err_string),
                mode=usertypes.PromptMode.yesno)
            if answer:
                reply.ignoreSslErrors()
        elif ssl_strict:
            pass
        else:
            for err in errors:
                # FIXME we might want to use warn here (non-fatal error)
                # https://github.com/The-Compiler/qutebrowser/issues/114
                message.error(self._win_id,
                              'SSL error: {}'.format(err.errorString()))
            reply.ignoreSslErrors()
Example #7
0
 def shouldInterruptJavaScript(self):
     """Override shouldInterruptJavaScript to use the statusbar."""
     answer = message.ask(self._win_id, "Interrupt long-running "
                          "javascript?", usertypes.PromptMode.yesno)
     if answer is None:
         answer = True
     return answer
Example #8
0
 def _on_proxy_authentication_required(self, url, authenticator,
                                       proxy_host):
     """Called when a proxy needs authentication."""
     msg = "<b>{}</b> requires a username and password.".format(
         html_utils.escape(proxy_host))
     answer = message.ask(
         title="Proxy authentication required", text=msg,
         mode=usertypes.PromptMode.user_pwd,
         abort_on=[self.shutting_down, self.load_started])
     if answer is not None:
         authenticator.setUser(answer.user)
         authenticator.setPassword(answer.password)
     else:
         try:
             # pylint: disable=no-member, useless-suppression
             sip.assign(authenticator, QAuthenticator())
             # pylint: enable=no-member, useless-suppression
         except AttributeError:
             url_string = url.toDisplayString()
             error_page = jinja.render(
                 'error.html',
                 title="Error loading page: {}".format(url_string),
                 url=url_string, error="Proxy authentication required",
                 icon='')
             self.set_html(error_page)
Example #9
0
 def on_proxy_authentication_required(self, _proxy, authenticator):
     """Called when a proxy needs authentication."""
     answer = message.ask(self._win_id,
                          "Proxy username ({}):".format(
                              authenticator.realm()),
                          mode=usertypes.PromptMode.user_pwd)
     self._fill_authenticator(authenticator, answer)
 def _on_proxy_authentication_required(self, url, authenticator,
                                       proxy_host):
     """Called when a proxy needs authentication."""
     msg = "<b>{}</b> requires a username and password.".format(
         html_utils.escape(proxy_host))
     answer = message.ask(title="Proxy authentication required",
                          text=msg,
                          mode=usertypes.PromptMode.user_pwd,
                          abort_on=[self.shutting_down, self.load_started])
     if answer is not None:
         authenticator.setUser(answer.user)
         authenticator.setPassword(answer.password)
     else:
         try:
             # pylint: disable=no-member, useless-suppression
             sip.assign(authenticator, QAuthenticator())
         except AttributeError:
             url_string = url.toDisplayString()
             error_page = jinja.render(
                 'error.html',
                 title="Error loading page: {}".format(url_string),
                 url=url_string,
                 error="Proxy authentication required",
                 icon='')
             self.set_html(error_page)
Example #11
0
 def closeEvent(self, e):
     """Override closeEvent to display a confirmation if needed."""
     if crashsignal.is_crashing:
         e.accept()
         return
     confirm_quit = config.get('ui', 'confirm-quit')
     tab_count = self.tabbed_browser.count()
     download_manager = objreg.get('download-manager', scope='window',
                                   window=self.win_id)
     download_count = download_manager.running_downloads()
     quit_texts = []
     # Ask if multiple-tabs are open
     if 'multiple-tabs' in confirm_quit and tab_count > 1:
         quit_texts.append("{} {} open.".format(
             tab_count, "tab is" if tab_count == 1 else "tabs are"))
     # Ask if multiple downloads running
     if 'downloads' in confirm_quit and download_count > 0:
         quit_texts.append("{} {} running.".format(
             tab_count,
             "download is" if tab_count == 1 else "downloads are"))
     # Process all quit messages that user must confirm
     if quit_texts or 'always' in confirm_quit:
         text = '\n'.join(['Really quit?'] + quit_texts)
         confirmed = message.ask(self.win_id, text,
                                 usertypes.PromptMode.yesno,
                                 default=True)
         # Stop asking if the user cancels
         if not confirmed:
             log.destroy.debug("Cancelling closing of window {}".format(
                 self.win_id))
             e.ignore()
             return
     e.accept()
     self._do_close()
Example #12
0
 def closeEvent(self, e):
     """Override closeEvent to display a confirmation if needed."""
     if crashsignal.is_crashing:
         e.accept()
         return
     confirm_quit = config.get('ui', 'confirm-quit')
     tab_count = self.tabbed_browser.count()
     download_manager = objreg.get('download-manager', scope='window',
                                   window=self.win_id)
     download_count = download_manager.rowCount()
     quit_texts = []
     # Ask if multiple-tabs are open
     if 'multiple-tabs' in confirm_quit and tab_count > 1:
         quit_texts.append("{} {} open.".format(
             tab_count, "tab is" if tab_count == 1 else "tabs are"))
     # Ask if multiple downloads running
     if 'downloads' in confirm_quit and download_count > 0:
         quit_texts.append("{} {} running.".format(
             tab_count,
             "download is" if tab_count == 1 else "downloads are"))
     # Process all quit messages that user must confirm
     if quit_texts or 'always' in confirm_quit:
         text = '\n'.join(['Really quit?'] + quit_texts)
         confirmed = message.ask(self.win_id, text,
                                 usertypes.PromptMode.yesno,
                                 default=True)
         # Stop asking if the user cancels
         if not confirmed:
             log.destroy.debug("Cancelling closing of window {}".format(
                 self.win_id))
             e.ignore()
             return
     e.accept()
     self._do_close()
Example #13
0
def feature_permission(url,
                       option,
                       msg,
                       yes_action,
                       no_action,
                       abort_on,
                       blocking=False):
    """Handle a feature permission request.

    Args:
        url: The URL the request was done for.
        option: An option name to check.
        msg: A string like "show notifications"
        yes_action: A callable to call if the request was approved
        no_action: A callable to call if the request was denied
        abort_on: A list of signals which interrupt the question.
        blocking: If True, ask a blocking question.

    Return:
        The Question object if a question was asked (and blocking=False),
        None otherwise.
    """
    config_val = config.instance.get(option, url=url)
    if config_val == 'ask':
        if url.isValid():
            urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded)
            text = "Allow the website at <b>{}</b> to {}?".format(
                html.escape(url.toDisplayString()), msg)
        else:
            urlstr = None
            option = None  # For message.ask/confirm_async
            text = "Allow the website to {}?".format(msg)

        if blocking:
            answer = message.ask(abort_on=abort_on,
                                 title='Permission request',
                                 text=text,
                                 url=urlstr,
                                 option=option,
                                 mode=usertypes.PromptMode.yesno)
            if answer:
                yes_action()
            else:
                no_action()
            return None
        else:
            return message.confirm_async(yes_action=yes_action,
                                         no_action=no_action,
                                         cancel_action=no_action,
                                         abort_on=abort_on,
                                         title='Permission request',
                                         text=text,
                                         url=urlstr,
                                         option=option)
    elif config_val:
        yes_action()
        return None
    else:
        no_action()
        return None
Example #14
0
    def on_ssl_errors(self, reply, errors):
        """Decide if SSL errors should be ignored or not.

        This slot is called on SSL/TLS errors by the self.sslErrors signal.

        Args:
            reply: The QNetworkReply that is encountering the errors.
            errors: A list of errors.
        """
        ssl_strict = config.get('network', 'ssl-strict')
        if ssl_strict == 'ask':
            err_string = '\n'.join('- ' + err.errorString() for err in errors)
            answer = message.ask(
                self._win_id,
                'SSL errors - continue?\n{}'.format(err_string),
                mode=usertypes.PromptMode.yesno)
            if answer:
                reply.ignoreSslErrors()
        elif ssl_strict:
            pass
        else:
            for err in errors:
                # FIXME we might want to use warn here (non-fatal error)
                # https://github.com/The-Compiler/qutebrowser/issues/114
                message.error(self._win_id,
                              'SSL error: {}'.format(err.errorString()))
            reply.ignoreSslErrors()
Example #15
0
 def closeEvent(self, e):
     """Override closeEvent to display a confirmation if needed."""
     confirm_quit = config.get("ui", "confirm-quit")
     tab_count = self.tabbed_browser.count()
     download_manager = objreg.get("download-manager", scope="window", window=self.win_id)
     download_count = download_manager.rowCount()
     quit_texts = []
     # Close if set to never ask for confirmation
     if "never" in confirm_quit:
         pass
     # Ask if multiple-tabs are open
     if "multiple-tabs" in confirm_quit and tab_count > 1:
         quit_texts.append("{} {} open.".format(tab_count, "tab is" if tab_count == 1 else "tabs are"))
     # Ask if multiple downloads running
     if "downloads" in confirm_quit and download_count > 0:
         quit_texts.append("{} {} running.".format(tab_count, "download is" if tab_count == 1 else "downloads are"))
     # Process all quit messages that user must confirm
     if quit_texts or "always" in confirm_quit:
         text = "\n".join(["Really quit?"] + quit_texts)
         confirmed = message.ask(self.win_id, text, usertypes.PromptMode.yesno, default=True)
         # Stop asking if the user cancels
         if not confirmed:
             log.destroy.debug("Cancelling closing of window {}".format(self.win_id))
             e.ignore()
             return
     e.accept()
     objreg.get("session-manager").save_last_window_session()
     self._save_geometry()
     log.destroy.debug("Closing window {}".format(self.win_id))
     self.tabbed_browser.shutdown()
Example #16
0
    def _ask(self, title, text, mode, owner=None, default=None):
        """Ask a blocking question in the statusbar.

        Args:
            title: The title to display to the user.
            text: The text to display to the user.
            mode: A PromptMode.
            owner: An object which will abort the question if destroyed, or
                   None.

        Return:
            The answer the user gave or None if the prompt was cancelled.
        """
        abort_on = [self.shutting_down]
        if owner is not None:
            abort_on.append(owner.destroyed)

        # This might be a generic network manager, e.g. one belonging to a
        # DownloadManager. In this case, just skip the webview thing.
        if self._tab_id is not None:
            tab = objreg.get('tab', scope='tab', window=self._win_id,
                             tab=self._tab_id)
            abort_on.append(tab.load_started)

        return message.ask(title=title, text=text, mode=mode,
                           abort_on=abort_on, default=default)
Example #17
0
 def shouldInterruptJavaScript(self):
     """Override shouldInterruptJavaScript to use the statusbar."""
     answer = message.ask("Interrupt long-running javascript?",
                          usertypes.PromptMode.yesno)
     if answer is None:
         answer = True
     return answer
Example #18
0
 def javaScriptPrompt(self, _frame, msg, default):
     """Override javaScriptPrompt to use the statusbar."""
     answer = message.ask(self._win_id, "js: {}".format(msg),
                          usertypes.PromptMode.text, default)
     if answer is None:
         return (False, "")
     else:
         return (True, answer)
Example #19
0
 def javaScriptPrompt(self, _frame, msg, default):
     """Override javaScriptPrompt to use the statusbar."""
     answer = message.ask(self._win_id, "js: {}".format(msg),
                          usertypes.PromptMode.text, default)
     if answer is None:
         return (False, "")
     else:
         return (True, answer)
Example #20
0
    def javaScriptAlert(self, frame, js_msg):
        """Override javaScriptAlert to use the statusbar."""
        log.js.debug("alert: {}".format(js_msg))
        if config.get('ui', 'modal-js-dialog'):
            return super().javaScriptAlert(frame, js_msg)

        if (self._is_shutting_down
                or config.get('content', 'ignore-javascript-alert')):
            return

        msg = 'From <b>{}</b>:<br/>{}'.format(
            html.escape(self.mainFrame().url().toDisplayString()),
            html.escape(js_msg))
        message.ask('Javascript alert',
                    msg,
                    mode=usertypes.PromptMode.alert,
                    abort_on=[self.loadStarted, self.shutting_down])
Example #21
0
def javascript_confirm(url, js_msg, abort_on):
    """Display a javascript confirm prompt."""
    log.js.debug("confirm: {}".format(js_msg))
    if config.get('ui', 'modal-js-dialog'):
        raise CallSuper

    msg = 'From <b>{}</b>:<br/>{}'.format(html.escape(url.toDisplayString()),
                                          html.escape(js_msg))
    ans = message.ask('Javascript confirm', msg,
                      mode=usertypes.PromptMode.yesno,
                      abort_on=abort_on)
    return bool(ans)
Example #22
0
def ignore_certificate_errors(url, errors, abort_on):
    """Display a certificate error question.

    Args:
        url: The URL the errors happened in
        errors: A list of QSslErrors or QWebEngineCertificateErrors

    Return:
        True if the error should be ignored, False otherwise.
    """
    ssl_strict = config.instance.get('content.ssl_strict', url=url)
    log.webview.debug("Certificate errors {!r}, strict {}".format(
        errors, ssl_strict))

    for error in errors:
        if not error.is_overridable():
            raise AssertionError(repr(error))

    if ssl_strict == 'ask':
        err_template = jinja.environment.from_string("""
            Errors while loading <b>{{url.toDisplayString()}}</b>:<br/>
            <ul>
            {% for err in errors %}
                <li>{{err}}</li>
            {% endfor %}
            </ul>
        """.strip())
        msg = err_template.render(url=url, errors=errors)

        urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded)
        ignore = message.ask(title="Certificate errors - continue?",
                             text=msg,
                             mode=usertypes.PromptMode.yesno,
                             default=False,
                             abort_on=abort_on,
                             url=urlstr)
        if ignore is None:
            # prompt aborted
            ignore = False
        return ignore
    elif ssl_strict is False:
        log.webview.debug("ssl_strict is False, only warning about errors")
        for err in errors:
            # FIXME we might want to use warn here (non-fatal error)
            # https://github.com/qutebrowser/qutebrowser/issues/114
            message.error('Certificate error: {}'.format(err))
        return True
    elif ssl_strict is True:
        return False
    else:
        raise ValueError("Invalid ssl_strict value {!r}".format(ssl_strict))
    raise utils.Unreachable
Example #23
0
def javascript_confirm(url, js_msg, abort_on):
    """Display a javascript confirm prompt."""
    log.js.debug("confirm: {}".format(js_msg))
    if config.val.content.javascript.modal_dialog:
        raise CallSuper

    msg = 'From <b>{}</b>:<br/>{}'.format(html.escape(url.toDisplayString()),
                                          _format_msg(js_msg))
    urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded)
    ans = message.ask('Javascript confirm', msg,
                      mode=usertypes.PromptMode.yesno,
                      abort_on=abort_on, url=urlstr)
    return bool(ans)
Example #24
0
    def _javascript_prompt(self, _frame, msg, default):
        """Override javaScriptPrompt to use the statusbar.

        We use this approach and override the method conditionally in __init__
        because overriding javaScriptPrompt was broken in 5.3.0.

        http://www.riverbankcomputing.com/pipermail/pyqt/2014-June/034385.html
        """
        answer = message.ask("js: {}".format(msg), usertypes.PromptMode.text,
                             default)
        if answer is None:
            return (False, "")
        else:
            return (True, answer)
Example #25
0
def authentication_required(url, authenticator, abort_on):
    """Ask a prompt for an authentication question."""
    realm = authenticator.realm()
    if realm:
        msg = '<b>{}</b> says:<br/>{}'.format(
            html.escape(url.toDisplayString()), html.escape(realm))
    else:
        msg = '<b>{}</b> needs authentication'.format(
            html.escape(url.toDisplayString()))
    answer = message.ask(title="Authentication required", text=msg,
                         mode=usertypes.PromptMode.user_pwd,
                         abort_on=abort_on)
    if answer is not None:
        authenticator.setUser(answer.user)
        authenticator.setPassword(answer.password)
Example #26
0
def ignore_certificate_errors(url, errors, abort_on):
    """Display a certificate error question.

    Args:
        url: The URL the errors happened in
        errors: A list of QSslErrors or QWebEngineCertificateErrors

    Return:
        True if the error should be ignored, False otherwise.
    """
    ssl_strict = config.val.content.ssl_strict
    log.webview.debug("Certificate errors {!r}, strict {}".format(
        errors, ssl_strict))

    for error in errors:
        assert error.is_overridable(), repr(error)

    if ssl_strict == 'ask':
        err_template = jinja.environment.from_string("""
            Errors while loading <b>{{url.toDisplayString()}}</b>:<br/>
            <ul>
            {% for err in errors %}
                <li>{{err}}</li>
            {% endfor %}
            </ul>
        """.strip())
        msg = err_template.render(url=url, errors=errors)

        urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded)
        ignore = message.ask(title="Certificate errors - continue?", text=msg,
                             mode=usertypes.PromptMode.yesno, default=False,
                             abort_on=abort_on, url=urlstr)
        if ignore is None:
            # prompt aborted
            ignore = False
        return ignore
    elif ssl_strict is False:
        log.webview.debug("ssl_strict is False, only warning about errors")
        for err in errors:
            # FIXME we might want to use warn here (non-fatal error)
            # https://github.com/qutebrowser/qutebrowser/issues/114
            message.error('Certificate error: {}'.format(err))
        return True
    elif ssl_strict is True:
        return False
    else:
        raise ValueError("Invalid ssl_strict value {!r}".format(ssl_strict))
    raise utils.Unreachable
Example #27
0
    def javaScriptConfirm(self, frame, js_msg):
        """Override javaScriptConfirm to use the statusbar."""
        log.js.debug("confirm: {}".format(js_msg))
        if config.get('ui', 'modal-js-dialog'):
            return super().javaScriptConfirm(frame, js_msg)

        if self._is_shutting_down:
            return False

        msg = 'From <b>{}</b>:<br/>{}'.format(
            html.escape(self.mainFrame().url().toDisplayString()),
            html.escape(js_msg))
        ans = message.ask('Javascript confirm', msg,
                          mode=usertypes.PromptMode.yesno,
                          abort_on=[self.loadStarted, self.shutting_down])
        return bool(ans)
Example #28
0
def authentication_required(url, authenticator, abort_on):
    """Ask a prompt for an authentication question."""
    realm = authenticator.realm()
    if realm:
        msg = '<b>{}</b> says:<br/>{}'.format(
            html.escape(url.toDisplayString()), html.escape(realm))
    else:
        msg = '<b>{}</b> needs authentication'.format(
            html.escape(url.toDisplayString()))
    answer = message.ask(title="Authentication required", text=msg,
                         mode=usertypes.PromptMode.user_pwd,
                         abort_on=abort_on)
    if answer is not None:
        authenticator.setUser(answer.user)
        authenticator.setPassword(answer.password)
    return answer
Example #29
0
def feature_permission(url, option, msg, yes_action, no_action, abort_on,
                       blocking=False):
    """Handle a feature permission request.

    Args:
        url: The URL the request was done for.
        option: An option name to check.
        msg: A string like "show notifications"
        yes_action: A callable to call if the request was approved
        no_action: A callable to call if the request was denied
        abort_on: A list of signals which interrupt the question.
        blocking: If True, ask a blocking question.

    Return:
        The Question object if a question was asked (and blocking=False),
        None otherwise.
    """
    config_val = config.instance.get(option, url=url)
    if config_val == 'ask':
        if url.isValid():
            urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded)
            text = "Allow the website at <b>{}</b> to {}?".format(
                html.escape(url.toDisplayString()), msg)
        else:
            urlstr = None
            text = "Allow the website to {}?".format(msg)

        if blocking:
            answer = message.ask(abort_on=abort_on, title='Permission request',
                                 text=text, url=urlstr,
                                 mode=usertypes.PromptMode.yesno)
            if answer:
                yes_action()
            else:
                no_action()
            return None
        else:
            return message.confirm_async(
                yes_action=yes_action, no_action=no_action,
                cancel_action=no_action, abort_on=abort_on,
                title='Permission request', text=text, url=urlstr)
    elif config_val:
        yes_action()
        return None
    else:
        no_action()
        return None
Example #30
0
 def javaScriptPrompt(self, _frame, js_msg, default):
     """Override javaScriptPrompt to use the statusbar."""
     if (self._is_shutting_down or
             config.get('content', 'ignore-javascript-prompt')):
         return (False, "")
     msg = '<b>{}</b> asks:<br/>{}'.format(
         html.escape(self.mainFrame().url().toDisplayString()),
         html.escape(js_msg))
     answer = message.ask('Javascript prompt', msg,
                          mode=usertypes.PromptMode.text,
                          default=default,
                          abort_on=[self.loadStarted,
                                    self.shutting_down])
     if answer is None:
         return (False, "")
     else:
         return (True, answer)
Example #31
0
    def javaScriptConfirm(self, frame, js_msg):
        """Override javaScriptConfirm to use the statusbar."""
        log.js.debug("confirm: {}".format(js_msg))
        if config.get('ui', 'modal-js-dialog'):
            return super().javaScriptConfirm(frame, js_msg)

        if self._is_shutting_down:
            return False

        msg = 'From <b>{}</b>:<br/>{}'.format(
            html.escape(self.mainFrame().url().toDisplayString()),
            html.escape(js_msg))
        ans = message.ask('Javascript confirm',
                          msg,
                          mode=usertypes.PromptMode.yesno,
                          abort_on=[self.loadStarted, self.shutting_down])
        return bool(ans)
Example #32
0
 def closeEvent(self, e):
     """Override closeEvent to display a confirmation if needed."""
     confirm_quit = config.get('ui', 'confirm-quit')
     count = self._tabbed_browser.count()
     if confirm_quit == 'never':
         e.accept()
     elif confirm_quit == 'multiple-tabs' and count <= 1:
         e.accept()
     else:
         text = "Close {} {}?".format(
             count, "tab" if count == 1 else "tabs")
         confirmed = message.ask(text, usertypes.PromptMode.yesno,
                                 default=True)
         if confirmed:
             e.accept()
         else:
             e.ignore()
Example #33
0
 def javaScriptPrompt(self, _frame, js_msg, default):
     """Override javaScriptPrompt to use the statusbar."""
     if (self._is_shutting_down
             or config.get('content', 'ignore-javascript-prompt')):
         return (False, "")
     msg = '<b>{}</b> asks:<br/>{}'.format(
         html.escape(self.mainFrame().url().toDisplayString()),
         html.escape(js_msg))
     answer = message.ask(
         'Javascript prompt',
         msg,
         mode=usertypes.PromptMode.text,
         default=default,
         abort_on=[self.loadStarted, self.shutting_down])
     if answer is None:
         return (False, "")
     else:
         return (True, answer)
Example #34
0
    def closeEvent(self, e):
        """Override closeEvent to display a confirmation if needed."""
        if crashsignal.is_crashing:
            e.accept()
            return
        confirm_quit = config.get('ui', 'confirm-quit')
        tab_count = self.tabbed_browser.count()
        download_model = objreg.get('download-model',
                                    scope='window',
                                    window=self.win_id)
        download_count = download_model.running_downloads()
        quit_texts = []
        # Ask if multiple-tabs are open
        if 'multiple-tabs' in confirm_quit and tab_count > 1:
            quit_texts.append("{} {} open.".format(
                tab_count, "tab is" if tab_count == 1 else "tabs are"))
        # Ask if multiple downloads running
        if 'downloads' in confirm_quit and download_count > 0:
            quit_texts.append("{} {} running.".format(
                download_count,
                "download is" if download_count == 1 else "downloads are"))
        # Process all quit messages that user must confirm
        if quit_texts or 'always' in confirm_quit:
            msg = jinja2.Template("""
                <ul>
                {% for text in quit_texts %}
                   <li>{{text}}</li>
                {% endfor %}
                </ul>
            """.strip()).render(quit_texts=quit_texts)
            confirmed = message.ask('Really quit?',
                                    msg,
                                    mode=usertypes.PromptMode.yesno,
                                    default=True)

            # Stop asking if the user cancels
            if not confirmed:
                log.destroy.debug("Cancelling closing of window {}".format(
                    self.win_id))
                e.ignore()
                return
        e.accept()
        self._do_close()
Example #35
0
def javascript_prompt(url, js_msg, default, abort_on):
    """Display a javascript prompt."""
    log.js.debug("prompt: {}".format(js_msg))
    if config.get('ui', 'modal-js-dialog'):
        raise CallSuper
    if config.get('content', 'ignore-javascript-prompt'):
        return (False, "")

    msg = '<b>{}</b> asks:<br/>{}'.format(html.escape(url.toDisplayString()),
                                          html.escape(js_msg))
    answer = message.ask('Javascript prompt', msg,
                         mode=usertypes.PromptMode.text,
                         default=default,
                         abort_on=abort_on)

    if answer is None:
        return (False, "")
    else:
        return (True, answer)
Example #36
0
 def on_proxy_authentication_required(self, proxy, authenticator):
     """Called when a proxy needs authentication."""
     proxy_id = ProxyId(proxy.type(), proxy.hostName(), proxy.port())
     if proxy_id in _proxy_auth_cache:
         authinfo = _proxy_auth_cache[proxy_id]
         authenticator.setUser(authinfo.user)
         authenticator.setPassword(authinfo.password)
     else:
         msg = '<b>{}</b> says:<br/>{}'.format(
             html.escape(proxy.hostName()),
             html.escape(authenticator.realm()))
         abort_on = self._get_abort_signals()
         answer = message.ask(
             title="Proxy authentication required", text=msg,
             mode=usertypes.PromptMode.user_pwd, abort_on=abort_on)
         if answer is not None:
             authenticator.setUser(answer.user)
             authenticator.setPassword(answer.password)
             _proxy_auth_cache[proxy_id] = answer
 def on_proxy_authentication_required(self, proxy, authenticator):
     """Called when a proxy needs authentication."""
     proxy_id = ProxyId(proxy.type(), proxy.hostName(), proxy.port())
     if proxy_id in _proxy_auth_cache:
         user, password = _proxy_auth_cache[proxy_id]
         authenticator.setUser(user)
         authenticator.setPassword(password)
     else:
         msg = '<b>{}</b> says:<br/>{}'.format(
             html.escape(proxy.hostName()),
             html.escape(authenticator.realm()))
         abort_on = self._get_abort_signals()
         answer = message.ask(
             title="Proxy authentication required", text=msg,
             mode=usertypes.PromptMode.user_pwd, abort_on=abort_on)
         if answer is not None:
             authenticator.setUser(answer.user)
             authenticator.setPassword(answer.password)
             _proxy_auth_cache[proxy_id] = answer
Example #38
0
def javascript_prompt(url, js_msg, default, abort_on):
    """Display a javascript prompt."""
    log.js.debug("prompt: {}".format(js_msg))
    if config.val.content.javascript.modal_dialog:
        raise CallSuper
    if not config.val.content.javascript.prompt:
        return (False, "")

    msg = '<b>{}</b> asks:<br/>{}'.format(html.escape(url.toDisplayString()),
                                          _format_msg(js_msg))
    urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded)
    answer = message.ask('Javascript prompt', msg,
                         mode=usertypes.PromptMode.text,
                         default=default,
                         abort_on=abort_on, url=urlstr)

    if answer is None:
        return (False, "")
    else:
        return (True, answer)
Example #39
0
 def _on_proxy_authentication_required(self, url, authenticator,
                                       proxy_host):
     """Called when a proxy needs authentication."""
     msg = "<b>{}</b> requires a username and password.".format(
         html_utils.escape(proxy_host))
     urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded)
     answer = message.ask(
         title="Proxy authentication required", text=msg,
         mode=usertypes.PromptMode.user_pwd,
         abort_on=[self.shutting_down, self.load_started], url=urlstr)
     if answer is not None:
         authenticator.setUser(answer.user)
         authenticator.setPassword(answer.password)
     else:
         try:
             # pylint: disable=no-member, useless-suppression
             sip.assign(authenticator, QAuthenticator())
             # pylint: enable=no-member, useless-suppression
         except AttributeError:
             self._show_error_page(url, "Proxy authentication required")
Example #40
0
 def _on_proxy_authentication_required(self, url, authenticator,
                                       proxy_host):
     """Called when a proxy needs authentication."""
     msg = "<b>{}</b> requires a username and password.".format(
         html_utils.escape(proxy_host))
     urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded)
     answer = message.ask(
         title="Proxy authentication required", text=msg,
         mode=usertypes.PromptMode.user_pwd,
         abort_on=[self.shutting_down, self.load_started], url=urlstr)
     if answer is not None:
         authenticator.setUser(answer.user)
         authenticator.setPassword(answer.password)
     else:
         try:
             # pylint: disable=no-member, useless-suppression
             sip.assign(authenticator, QAuthenticator())
             # pylint: enable=no-member, useless-suppression
         except AttributeError:
             self._show_error_page(url, "Proxy authentication required")
Example #41
0
    def closeEvent(self, e):
        """Override closeEvent to display a confirmation if needed."""
        if crashsignal.is_crashing:
            e.accept()
            return
        confirm_quit = config.get('ui', 'confirm-quit')
        tab_count = self.tabbed_browser.count()
        download_model = objreg.get('download-model', scope='window',
                                    window=self.win_id)
        download_count = download_model.running_downloads()
        quit_texts = []
        # Ask if multiple-tabs are open
        if 'multiple-tabs' in confirm_quit and tab_count > 1:
            quit_texts.append("{} {} open.".format(
                tab_count, "tab is" if tab_count == 1 else "tabs are"))
        # Ask if multiple downloads running
        if 'downloads' in confirm_quit and download_count > 0:
            quit_texts.append("{} {} running.".format(
                download_count,
                "download is" if download_count == 1 else "downloads are"))
        # Process all quit messages that user must confirm
        if quit_texts or 'always' in confirm_quit:
            msg = jinja2.Template("""
                <ul>
                {% for text in quit_texts %}
                   <li>{{text}}</li>
                {% endfor %}
                </ul>
            """.strip()).render(quit_texts=quit_texts)
            confirmed = message.ask('Really quit?', msg,
                                    mode=usertypes.PromptMode.yesno,
                                    default=True)

            # Stop asking if the user cancels
            if not confirmed:
                log.destroy.debug("Cancelling closing of window {}".format(
                    self.win_id))
                e.ignore()
                return
        e.accept()
        self._do_close()
Example #42
0
def javascript_prompt(url, js_msg, default, abort_on, *, escape_msg=True):
    """Display a javascript prompt."""
    log.js.debug("prompt: {}".format(js_msg))
    if config.val.content.javascript.modal_dialog:
        raise CallSuper
    if not config.val.content.javascript.prompt:
        return (False, "")

    js_msg = html.escape(js_msg) if escape_msg else js_msg
    msg = '<b>{}</b> asks:<br/>{}'.format(html.escape(url.toDisplayString()),
                                          js_msg)
    urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded)
    answer = message.ask('Javascript prompt', msg,
                         mode=usertypes.PromptMode.text,
                         default=default,
                         abort_on=abort_on, url=urlstr)

    if answer is None:
        return (False, "")
    else:
        return (True, answer)
Example #43
0
    def _confirm_quit(self):
        """Confirm that this window should be closed.

        Return:
            True if closing is okay, False if a closeEvent should be ignored.
        """
        tab_count = self.tabbed_browser.widget.count()
        window_count = len(objreg.window_registry)
        download_count = self._download_model.running_downloads()
        quit_texts = []
        # Ask if multiple-tabs are open
        if 'multiple-tabs' in config.val.confirm_quit and tab_count > 1:
            quit_texts.append("{} tabs are open.".format(tab_count))
        # Ask if downloads running
        if ('downloads' in config.val.confirm_quit and download_count > 0
                and window_count <= 1):
            quit_texts.append("{} {} running.".format(
                download_count,
                "download is" if download_count == 1 else "downloads are"))
        # Process all quit messages that user must confirm
        if quit_texts or 'always' in config.val.confirm_quit:
            msg = jinja.environment.from_string("""
                <ul>
                {% for text in quit_texts %}
                   <li>{{text}}</li>
                {% endfor %}
                </ul>
            """.strip()).render(quit_texts=quit_texts)
            confirmed = message.ask('Really quit?',
                                    msg,
                                    mode=usertypes.PromptMode.yesno,
                                    default=True)

            # Stop asking if the user cancels
            if not confirmed:
                log.destroy.debug("Cancelling closing of window {}".format(
                    self.win_id))
                return False

        return True
Example #44
0
 def closeEvent(self, e):
     """Override closeEvent to display a confirmation if needed."""
     confirm_quit = config.get('ui', 'confirm-quit')
     count = self._tabbed_browser.count()
     if confirm_quit == 'never':
         pass
     elif confirm_quit == 'multiple-tabs' and count <= 1:
         pass
     else:
         text = "Close {} {}?".format(
             count, "tab" if count == 1 else "tabs")
         confirmed = message.ask(self.win_id, text,
                                 usertypes.PromptMode.yesno, default=True)
         if not confirmed:
             log.destroy.debug("Cancelling losing of window {}".format(
                 self.win_id))
             e.ignore()
             return
     e.accept()
     objreg.get('app').geometry = bytes(self.saveGeometry())
     log.destroy.debug("Closing window {}".format(self.win_id))
     self._tabbed_browser.shutdown()
Example #45
0
 def closeEvent(self, e):
     """Override closeEvent to display a confirmation if needed."""
     confirm_quit = config.get('ui', 'confirm-quit')
     count = self._tabbed_browser.count()
     if confirm_quit == 'never':
         pass
     elif confirm_quit == 'multiple-tabs' and count <= 1:
         pass
     else:
         text = "Close {} {}?".format(
             count, "tab" if count == 1 else "tabs")
         confirmed = message.ask(self.win_id, text,
                                 usertypes.PromptMode.yesno, default=True)
         if not confirmed:
             log.destroy.debug("Cancelling losing of window {}".format(
                 self.win_id))
             e.ignore()
             return
     e.accept()
     objreg.get('app').geometry = bytes(self.saveGeometry())
     log.destroy.debug("Closing window {}".format(self.win_id))
     self._tabbed_browser.shutdown()
Example #46
0
 def closeEvent(self, e):
     """Override closeEvent to display a confirmation if needed."""
     confirm_quit = config.get('ui', 'confirm-quit')
     tab_count = self._tabbed_browser.count()
     download_manager = objreg.get('download-manager', scope='window',
                                   window=self.win_id)
     download_count = download_manager.rowCount()
     quit_texts = []
     # Close if set to never ask for confirmation
     if 'never' in confirm_quit:
         pass
     # Ask if multiple-tabs are open
     if 'multiple-tabs' in confirm_quit and tab_count > 1:
         quit_texts.append("{} {} open.".format(
             tab_count, "tab is" if tab_count == 1 else "tabs are"))
     # Ask if multiple downloads running
     if 'downloads' in confirm_quit and download_count > 0:
         quit_texts.append("{} {} running.".format(
             tab_count,
             "download is" if tab_count == 1 else "downloads are"))
     # Process all quit messages that user must confirm
     if quit_texts or 'always' in confirm_quit:
         text = '\n'.join(['Really quit?'] + quit_texts)
         confirmed = message.ask(self.win_id, text,
                                 usertypes.PromptMode.yesno,
                                 default=True)
         # Stop asking if the user cancels
         if not confirmed:
             log.destroy.debug("Cancelling closing of window {}".format(
                 self.win_id))
             e.ignore()
             return
     e.accept()
     if len(objreg.window_registry) == 1:
         objreg.get('session-manager').save_last_window_session()
     objreg.get('app').geometry = bytes(self.saveGeometry())
     log.destroy.debug("Closing window {}".format(self.win_id))
     self._tabbed_browser.shutdown()
Example #47
0
 def javaScriptConfirm(self, _frame, msg):
     """Override javaScriptConfirm to use the statusbar."""
     ans = message.ask(self._win_id, "[js confirm] {}".format(msg),
                       usertypes.PromptMode.yesno)
     return bool(ans)
Example #48
0
def ignore_certificate_error(
        *,
        request_url: QUrl,
        first_party_url: QUrl,
        error: usertypes.AbstractCertificateErrorWrapper,
        abort_on: Iterable[pyqtBoundSignal],
) -> bool:
    """Display a certificate error question.

    Args:
        request_url: The URL of the request where the errors happened.
        first_party_url: The URL of the page we're visiting. Might be an invalid QUrl.
        error: A single error.
        abort_on: Signals aborting a question.

    Return:
        True if the error should be ignored, False otherwise.
    """
    conf = config.instance.get('content.tls.certificate_errors', url=request_url)
    log.network.debug(f"Certificate error {error!r}, config {conf}")

    assert error.is_overridable(), repr(error)

    # We get the first party URL with a heuristic - with HTTP -> HTTPS redirects, the
    # scheme might not match.
    is_resource = (
        first_party_url.isValid() and
        not request_url.matches(
            first_party_url,
            QUrl.RemoveScheme))  # type: ignore[arg-type]

    if conf == 'ask' or conf == 'ask-block-thirdparty' and not is_resource:
        err_template = jinja.environment.from_string("""
            {% if is_resource %}
            <p>
                Error while loading resource <b>{{request_url.toDisplayString()}}</b><br/>
                on page <b>{{first_party_url.toDisplayString()}}</b>:
            </p>
            {% else %}
            <p>Error while loading page <b>{{request_url.toDisplayString()}}</b>:</p>
            {% endif %}

            {{error.html()|safe}}

            {% if is_resource %}
            <p><i>Consider reporting this to the website operator, or set
            <tt>content.tls.certificate_errors</tt> to <tt>ask-block-thirdparty</tt> to
            always block invalid resource loads.</i></p>
            {% endif %}

            Do you want to ignore these errors and continue loading the page <b>insecurely</b>?
        """.strip())
        msg = err_template.render(
            request_url=request_url,
            first_party_url=first_party_url,
            is_resource=is_resource,
            error=error,
        )

        urlstr = request_url.toString(
            QUrl.RemovePassword | QUrl.FullyEncoded)  # type: ignore[arg-type]
        ignore = message.ask(title="Certificate error", text=msg,
                             mode=usertypes.PromptMode.yesno, default=False,
                             abort_on=abort_on, url=urlstr)
        if ignore is None:
            # prompt aborted
            ignore = False
        return ignore
    elif conf == 'load-insecurely':
        message.error(f'Certificate error: {error}')
        return True
    elif conf == 'block':
        return False
    elif conf == 'ask-block-thirdparty' and is_resource:
        log.network.error(
            f"Certificate error in resource load: {error}\n"
            f"  request URL:     {request_url.toDisplayString()}\n"
            f"  first party URL: {first_party_url.toDisplayString()}")
        return False
    raise utils.Unreachable(conf, is_resource)
Example #49
0
 def javaScriptConfirm(self, _frame, msg):
     """Override javaScriptConfirm to use the statusbar."""
     ans = message.ask("[js confirm] {}".format(msg),
                       usertypes.PromptMode.yesno)
     return bool(ans)
Example #50
0
 def javaScriptAlert(self, _frame, msg):
     """Override javaScriptAlert to use the statusbar."""
     message.ask("[js alert] {}".format(msg), usertypes.PromptMode.alert)
Example #51
0
 def on_proxy_authentication_required(self, _proxy, authenticator):
     """Called when a proxy needs authentication."""
     answer = message.ask(self._win_id, "Proxy username ({}):".format(
         authenticator.realm()), mode=usertypes.PromptMode.user_pwd)
     self._fill_authenticator(authenticator, answer)
Example #52
0
 def javaScriptAlert(self, _frame, msg):
     """Override javaScriptAlert to use the statusbar."""
     message.ask(self._win_id, "[js alert] {}".format(msg),
                 usertypes.PromptMode.alert)
Example #53
0
 def on_authentication_required(self, _reply, authenticator):
     """Called when a website needs authentication."""
     answer = message.ask("Username ({}):".format(authenticator.realm()),
                          mode=usertypes.PromptMode.user_pwd)
     self._fill_authenticator(authenticator, answer)