import webbrowser
import time


def get_oauth_pin(oauth_url, open_browser=True):
    """Prompt the user for the OAuth PIN.

    By default, a browser will open the authorization page. If `open_browser`
    is false, the authorization URL will just be printed instead.
    """

    print('Opening: {}\n'.format(oauth_url))

    if open_browser:
        print("""
In the web browser window that opens please choose to Allow
access. Copy the PIN number that appears on the next page and paste or
type it here:
    """)

        try:
            r = webbrowser.open(oauth_url)
            time.sleep(2)
            if not r:
                raise Exception()
        except:
            print("""
Uh, I couldn't open a browser on your computer. Please go here to get
your PIN:

""" + oauth_url)

    else:
        print("""
Please go to the following URL, authorize the app, and copy the PIN:

""" + oauth_url)

    return input('Please enter the PIN: ').strip()