Exemple #1
0
def open_uri(uri):
    """ Open a URI in an external (web) browser. The given argument has
    to be a properly formed URI including the scheme (fe. HTTP). """

    # Situation 1, user defined a way of handling the protocol
    protocol = uri[:uri.find(":")]
    protocol_handlers = config.sections["urls"]["protocols"]

    if protocol in protocol_handlers and protocol_handlers[protocol]:
        try:
            execute_command(protocol_handlers[protocol], uri)
            return True

        except RuntimeError as error:
            log.add(error)

    if protocol == "slsk":
        OPEN_SOULSEEK_URL(uri.strip())  # pylint:disable=not-callable
        return True

    # Situation 2, user did not define a way of handling the protocol
    try:
        if not webbrowser.open(uri):
            raise webbrowser.Error("no known URL provider available")

        return True

    except Exception as error:
        log.add(_("Failed to open URL: %s"), error)

    return False
Exemple #2
0
    def test_open_in_browser_fail__no_browser_controller(
        self, mocker: MockerFixture, controller: Controller
    ) -> None:
        os.environ["DISPLAY"] = ":0"
        error = "No runnable browser found"
        mocked_report_error = mocker.patch(MODULE + ".Controller.report_error")
        mocker.patch(MODULE + ".webbrowser.get").side_effect = webbrowser.Error(error)

        controller.open_in_browser("https://chat.zulip.org/#narrow/stream/test")

        mocked_report_error.assert_called_once_with(f"ERROR: {error}")
Exemple #3
0
def _dcv_connect(args):
    """
    Execute pcluster dcv connect command.

    :param args: pcluster cli arguments.
    """
    result = PclusterApi().describe_cluster_instances(
        cluster_name=args.cluster_name,
        region=get_region(),
        node_type=NodeType.HEAD_NODE)
    if isinstance(result, list) and len(result) == 1:
        head_node_ip = result[0].public_ip_address or result[
            0].private_ip_address
        # Prepare ssh command to execute in the head node instance
        cmd = 'ssh {CFN_USER}@{HEAD_NODE_IP} {KEY} "{REMOTE_COMMAND} /home/{CFN_USER}"'.format(
            CFN_USER=result[0].user,
            HEAD_NODE_IP=head_node_ip,
            KEY="-i {0}".format(args.key_path) if args.key_path else "",
            REMOTE_COMMAND=DCV_CONNECT_SCRIPT,
        )

        try:
            url = _retry(_retrieve_dcv_session_url,
                         func_args=[cmd, args.cluster_name, head_node_ip],
                         attempts=4)
            url_message = "Please use the following one-time URL in your browser within 30 seconds:\n{0}".format(
                url)

            if args.show_url:
                print(url_message)
                return

            try:
                if not webbrowser.open_new(url):
                    raise webbrowser.Error("Unable to open the Web browser.")
            except webbrowser.Error as e:
                print("%s\n%s", e, url_message)

        except DCVConnectionError as e:
            error(
                "Something went wrong during DCV connection.\n{0}"
                "Please check the logs in the /var/log/parallelcluster/ folder "
                "of the head node and submit an issue {1}\n".format(
                    e, PCLUSTER_ISSUES_LINK))
    else:
        error(f"Unable to connect to the cluster.\n{result.message}")
def _use_web_client(cmd, instance):
    """
    Starts the connection with the web client and default browser.
    :param cmd: ssh command line
    :param instance: instance address
    """
    try:
        url = retry(_retrieve_dcv_session_url, func_args=[cmd, instance], attempts=4)
        url_message = "Please use the following one-time URL in your browser within 30 seconds:\n{0}".format(url)
    except DCVConnectionError as e:
        error(
             "Something went wrong during DCV connection.\n{0}".format(e)
        )

    try:
        if not webbrowser.open_new(url):
            raise webbrowser.Error("Unable to open the Web browser.")
    except webbrowser.Error as e:
        print("{0}\n{1}".format(e, url_message))
def dcv_connect(args):
    """
    Execute pcluster dcv connect command.

    :param args: pcluster cli arguments.
    """
    # Parse configuration file to read the AWS section
    PclusterConfig.init_aws(
    )  # FIXME it always searches for the default configuration file

    # Prepare ssh command to execute in the head node instance
    stack = get_stack(get_stack_name(args.cluster_name))
    shared_dir = get_cfn_param(stack.get("Parameters"), "SharedDir")
    head_node_ip, username = get_head_node_ip_and_username(args.cluster_name)
    cmd = 'ssh {CFN_USER}@{HEAD_NODE_IP} {KEY} "{REMOTE_COMMAND} {DCV_SHARED_DIR}"'.format(
        CFN_USER=username,
        HEAD_NODE_IP=head_node_ip,
        KEY="-i {0}".format(args.key_path) if args.key_path else "",
        REMOTE_COMMAND=DCV_CONNECT_SCRIPT,
        DCV_SHARED_DIR=shared_dir,
    )

    try:
        url = retry(_retrieve_dcv_session_url,
                    func_args=[cmd, args.cluster_name, head_node_ip],
                    attempts=4)
        url_message = "Please use the following one-time URL in your browser within 30 seconds:\n{0}".format(
            url)
    except DCVConnectionError as e:
        error("Something went wrong during DCV connection.\n{0}"
              "Please check the logs in the /var/log/parallelcluster/ folder "
              "of the head node and submit an issue {1}\n".format(
                  e, PCLUSTER_ISSUES_LINK))

    if args.show_url:
        LOGGER.info(url_message)
        return

    try:
        if not webbrowser.open_new(url):
            raise webbrowser.Error("Unable to open the Web browser.")
    except webbrowser.Error as e:
        LOGGER.info("{0}\n{1}".format(e, url_message))
 def askForCaptcha(self, url):
     """Show the user a CAPTCHA image and return the answer."""
     try:
         import webbrowser
         pywikibot.output(u'Opening CAPTCHA in your web browser...')
         if webbrowser.open(url):
             return pywikibot.input(
                 u'What is the solution of the CAPTCHA that is shown in '
                 u'your web browser?')
         else:
             raise webbrowser.Error(
                 'webbrowser.open failed to open a web browser')
     except Exception:
         pywikibot.output(u'Error in opening web browser: %s' %
                          sys.exc_info()[0])
         pywikibot.output(
             u'Please copy this url to your web browser and open it:\n %s' %
             url)
         return pywikibot.input(
             u'What is the solution of the CAPTCHA at this url ?')
Exemple #7
0
def open_file_path(file_path, command=None):
    """ Currently used to either open a folder or play an audio file
    Tries to run a user-specified command first, and falls back to
    the system default. """

    try:
        file_path = os.path.normpath(file_path)

        if command and "$" in command:
            execute_command(command, file_path)

        elif sys.platform == "win32":
            os.startfile(file_path)

        elif sys.platform == "darwin":
            execute_command("open $", file_path)

        elif not webbrowser.open(file_path):
            raise webbrowser.Error("no known URL provider available")

    except Exception as error:
        log.add(_("Failed to open file path: %s"), error)
Exemple #8
0
def main(a):

    spaced(500)
    logo(valuedLogo)
    spaced(5)
    print('Running ' + platformType)
    spaced(1)
    print('Type \'help\' for a list of commands')
    spaced(2)
    if (a):
        while (a):
            spaced(1)

            firstCommand = input('> ')

            spaced(1)

            if (firstCommand == 'help' or firstCommand == 'Help'
                    or firstCommand == 'HELP'):
                spaced(2)
                help()
                spaced(2)

            elif (firstCommand == 'gui' or firstCommand == 'Gui'
                  or firstCommand == 'GUI'):
                webpage = "index.html"
                webbrowser.get('firefox').open(webpage)
                webbrowser.get('chrome').open(webpage)
                os.system('start ' + webpage)

                if (webbrowser.Error()):
                    print('Error: Could not launch applet')
                else:
                    print('Launched')

            elif (firstCommand == 'I know'):
                I_Know()
            elif (firstCommand == 'sike8' or firstCommand == 'Sike8'
                  or firstCommand == 'SIKE8'):
                spaced(2)
                sike8()
                spaced(2)

            elif (firstCommand == 'random' or firstCommand == 'Random'
                  or firstCommand == 'RANDOM'):
                spaced(1)
                randomGen()
                spaced(1)

            elif (firstCommand == 'hackermode' or firstCommand == 'Hackermode'
                  or firstCommand == 'HACKERMODE'):
                print('Function stills to be written')

            elif (firstCommand == 'logo' or firstCommand == 'Logo'
                  or firstCommand == 'LOGO'):
                spaced(10)
                logo(valuedLogo)

            elif (firstCommand == 'clear' or firstCommand == 'Clear'
                  or firstCommand == 'CLEAR'):
                spaced(300)

            elif (firstCommand == 'exit' or firstCommand == 'Exit'
                  or firstCommand == 'EXIT'):
                spaced(2)
                print('Entering normal terminal mode')
                spaced(2)
                a = False
                exit
            else:
                print('Command \"' + firstCommand + '\" Unrecognized')

    else:
        spaced(2)
        print('Entering normal terminal mode')
        spaced(2)
        exit
        def open(self, url, new):
            import webbrowser

            raise webbrowser.Error("Failure")
Exemple #10
0
 def test_call_browser_fails(self):
     self.open_browser.side_effect = webbrowser.Error()
     self.handler(**self.pending_authorization)
     self.assert_text_in_output(self.user_code, self.verification_uri)
     self.open_browser.assert_called_with(self.verification_uri_complete)
Exemple #11
0
def test_no_browser_auth():
    webbrowser.get = Mock(side_effect=webbrowser.Error())
    with patch('webbrowser.open') as op:
        _mock_dcos_run([util.which('dcos')], False)
        assert op.call_count == 0
def go_to_github():
    try:
        webbrowser.open("https://dislbenn")
    except webbrowser.Error() as error:
        print(error)
Exemple #13
0
def no_browser(x):
    raise webbrowser.Error()